diff --git a/.golangci.yml b/.golangci.yml index 189136d486f2..997509963548 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -62,6 +62,10 @@ linters: - linters: - staticcheck text: 'SA1019: "github.com/aws/aws-sdk-go' + # cluster-api v1beta1 is deprecated but migration to v1beta2 is a separate effort + - linters: + - staticcheck + text: 'SA1019: "sigs.k8s.io/cluster-api/(.*)" is deprecated: This package is deprecated and is going to be removed when support for v1beta1 will be dropped.' paths: - third_party$ - builtin$ diff --git a/Dockerfile b/Dockerfile index 4681d41bb50e..129f8a9c48b3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -32,4 +32,4 @@ LABEL io.openshift.hypershift.control-plane-operator-applies-management-kas-netw LABEL io.openshift.hypershift.restricted-psa=true LABEL io.openshift.hypershift.control-plane-pki-operator-signs-csrs=true LABEL io.openshift.hypershift.hosted-cluster-config-operator-reports-node-count=true -LABEL io.openshift.hypershift.control-plane-operator.v2-isdefault=true \ No newline at end of file +LABEL io.openshift.hypershift.control-plane-operator.v2-isdefault=true diff --git a/Makefile b/Makefile index fb28e94361c8..c31989b250ba 100644 --- a/Makefile +++ b/Makefile @@ -244,9 +244,8 @@ hypershift-api: $(CONTROLLER_GEN) $(CODE_GEN) .PHONY: cluster-api cluster-api: $(CONTROLLER_GEN) rm -rf cmd/install/assets/cluster-api/*.yaml - $(CONTROLLER_GEN) $(CRD_OPTIONS) paths="./vendor/sigs.k8s.io/cluster-api/api/..." output:crd:artifacts:config=cmd/install/assets/cluster-api - $(CONTROLLER_GEN) $(CRD_OPTIONS) paths="./vendor/sigs.k8s.io/cluster-api/exp/api/..." output:crd:artifacts:config=cmd/install/assets/cluster-api - $(CONTROLLER_GEN) $(CRD_OPTIONS) paths="./vendor/sigs.k8s.io/cluster-api/exp/ipam/api/..." output:crd:artifacts:config=cmd/install/assets/cluster-api + $(CONTROLLER_GEN) $(CRD_OPTIONS) paths="./vendor/sigs.k8s.io/cluster-api/api/core/..." output:crd:artifacts:config=cmd/install/assets/cluster-api + $(CONTROLLER_GEN) $(CRD_OPTIONS) paths="./vendor/sigs.k8s.io/cluster-api/api/ipam/..." output:crd:artifacts:config=cmd/install/assets/cluster-api $(CONTROLLER_GEN) $(CRD_OPTIONS) paths="./vendor/sigs.k8s.io/cluster-api/api/addons/..." output:crd:artifacts:config=cmd/install/assets/cluster-api .PHONY: cluster-api-provider-aws diff --git a/api/.golangci.yml b/api/.golangci.yml index 80e2916f9de2..c27d38314d37 100644 --- a/api/.golangci.yml +++ b/api/.golangci.yml @@ -120,6 +120,10 @@ linters: - kubeapilinter path: hypershift/v1beta1/hosted_controlplane.go text: 'nobools: field HostedControlPlaneStatus.Initialized should not use a bool. Use a string type with meaningful constant values as an enum.' + - linters: + - kubeapilinter + path: hypershift/v1beta1/hosted_controlplane.go + text: 'nobools: field HostedControlPlaneInitializationStatus.ControlPlaneInitialized pointer should not use a bool. Use a string type with meaningful constant values as an enum.' - linters: - kubeapilinter path: hypershift/v1beta1/hosted_controlplane.go diff --git a/api/go.mod b/api/go.mod index 2aafadaa9f0c..2aa67d67cdb9 100644 --- a/api/go.mod +++ b/api/go.mod @@ -21,24 +21,33 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/emicklei/go-restful/v3 v3.12.2 // indirect + github.com/emicklei/go-restful/v3 v3.13.0 // indirect github.com/evanphx/json-patch v5.9.11+incompatible // indirect github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect github.com/go-logr/logr v1.4.3 // indirect - github.com/go-openapi/jsonpointer v0.21.1 // indirect - github.com/go-openapi/jsonreference v0.21.0 // indirect - github.com/go-openapi/swag v0.23.1 // indirect + github.com/go-openapi/jsonpointer v0.22.4 // indirect + github.com/go-openapi/jsonreference v0.21.4 // indirect + github.com/go-openapi/swag v0.25.4 // indirect + github.com/go-openapi/swag/cmdutils v0.25.4 // indirect + github.com/go-openapi/swag/conv v0.25.4 // indirect + github.com/go-openapi/swag/fileutils v0.25.4 // indirect + github.com/go-openapi/swag/jsonname v0.25.4 // indirect + github.com/go-openapi/swag/jsonutils v0.25.4 // indirect + github.com/go-openapi/swag/loading v0.25.4 // indirect + github.com/go-openapi/swag/mangling v0.25.4 // indirect + github.com/go-openapi/swag/netutils v0.25.4 // indirect + github.com/go-openapi/swag/stringutils v0.25.4 // indirect + github.com/go-openapi/swag/typeutils v0.25.4 // indirect + github.com/go-openapi/swag/yamlutils v0.25.4 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/btree v1.1.3 // indirect - github.com/google/gnostic-models v0.7.0 // indirect + github.com/google/gnostic-models v0.7.1 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/mailru/easyjson v0.9.0 // indirect github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect @@ -46,12 +55,11 @@ require ( github.com/onsi/ginkgo/v2 v2.28.1 // indirect github.com/onsi/gomega v1.39.1 // indirect github.com/patrickmn/go-cache v2.1.0+incompatible // indirect - github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_golang v1.23.2 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.67.5 // indirect - github.com/prometheus/procfs v0.16.1 // indirect + github.com/prometheus/procfs v0.19.2 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect github.com/samber/lo v1.51.0 // indirect @@ -72,22 +80,21 @@ require ( golang.org/x/tools v0.42.0 // indirect gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect google.golang.org/protobuf v1.36.11 // indirect - gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect + gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/apiextensions-apiserver v0.34.3 // indirect k8s.io/client-go v0.34.3 // indirect k8s.io/cloud-provider v0.34.1 // indirect k8s.io/component-base v0.34.3 // indirect - k8s.io/component-helpers v0.34.2 // indirect + k8s.io/component-helpers v0.34.3 // indirect k8s.io/csi-translation-lib v0.34.1 // indirect k8s.io/klog/v2 v2.130.1 // indirect - k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b // indirect + k8s.io/kube-openapi v0.0.0-20251125145642-4e65d59e963e // indirect sigs.k8s.io/controller-runtime v0.22.4 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/karpenter v1.8.2 // indirect sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.3.1 // indirect sigs.k8s.io/yaml v1.6.0 // indirect ) diff --git a/api/go.sum b/api/go.sum index d701e911796e..868897c43a68 100644 --- a/api/go.sum +++ b/api/go.sum @@ -47,8 +47,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs 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/emicklei/go-restful/v3 v3.12.2 h1:DhwDP0vY3k8ZzE0RunuJy8GhNpPL6zqLkDf9B/a0/xU= -github.com/emicklei/go-restful/v3 v3.12.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= +github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/evanphx/json-patch v5.9.11+incompatible h1:ixHHqfcGvxhWkniF1tWxBHA0yb4Z+d1UQi45df52xW8= github.com/evanphx/json-patch v5.9.11+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= @@ -61,20 +61,48 @@ github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= -github.com/go-openapi/jsonpointer v0.21.1 h1:whnzv/pNXtK2FbX/W9yJfRmE2gsmkfahjMKB0fZvcic= -github.com/go-openapi/jsonpointer v0.21.1/go.mod h1:50I1STOfbY1ycR8jGz8DaMeLCdXiI6aDteEdRNNzpdk= -github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= -github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= -github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZU= -github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0= +github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4= +github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80= +github.com/go-openapi/jsonreference v0.21.4 h1:24qaE2y9bx/q3uRK/qN+TDwbok1NhbSmGjjySRCHtC8= +github.com/go-openapi/jsonreference v0.21.4/go.mod h1:rIENPTjDbLpzQmQWCj5kKj3ZlmEh+EFVbz3RTUh30/4= +github.com/go-openapi/swag v0.25.4 h1:OyUPUFYDPDBMkqyxOTkqDYFnrhuhi9NR6QVUvIochMU= +github.com/go-openapi/swag v0.25.4/go.mod h1:zNfJ9WZABGHCFg2RnY0S4IOkAcVTzJ6z2Bi+Q4i6qFQ= +github.com/go-openapi/swag/cmdutils v0.25.4 h1:8rYhB5n6WawR192/BfUu2iVlxqVR9aRgGJP6WaBoW+4= +github.com/go-openapi/swag/cmdutils v0.25.4/go.mod h1:pdae/AFo6WxLl5L0rq87eRzVPm/XRHM3MoYgRMvG4A0= +github.com/go-openapi/swag/conv v0.25.4 h1:/Dd7p0LZXczgUcC/Ikm1+YqVzkEeCc9LnOWjfkpkfe4= +github.com/go-openapi/swag/conv v0.25.4/go.mod h1:3LXfie/lwoAv0NHoEuY1hjoFAYkvlqI/Bn5EQDD3PPU= +github.com/go-openapi/swag/fileutils v0.25.4 h1:2oI0XNW5y6UWZTC7vAxC8hmsK/tOkWXHJQH4lKjqw+Y= +github.com/go-openapi/swag/fileutils v0.25.4/go.mod h1:cdOT/PKbwcysVQ9Tpr0q20lQKH7MGhOEb6EwmHOirUk= +github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI= +github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag= +github.com/go-openapi/swag/jsonutils v0.25.4 h1:VSchfbGhD4UTf4vCdR2F4TLBdLwHyUDTd1/q4i+jGZA= +github.com/go-openapi/swag/jsonutils v0.25.4/go.mod h1:7OYGXpvVFPn4PpaSdPHJBtF0iGnbEaTk8AvBkoWnaAY= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4 h1:IACsSvBhiNJwlDix7wq39SS2Fh7lUOCJRmx/4SN4sVo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4/go.mod h1:Mt0Ost9l3cUzVv4OEZG+WSeoHwjWLnarzMePNDAOBiM= +github.com/go-openapi/swag/loading v0.25.4 h1:jN4MvLj0X6yhCDduRsxDDw1aHe+ZWoLjW+9ZQWIKn2s= +github.com/go-openapi/swag/loading v0.25.4/go.mod h1:rpUM1ZiyEP9+mNLIQUdMiD7dCETXvkkC30z53i+ftTE= +github.com/go-openapi/swag/mangling v0.25.4 h1:2b9kBJk9JvPgxr36V23FxJLdwBrpijI26Bx5JH4Hp48= +github.com/go-openapi/swag/mangling v0.25.4/go.mod h1:6dxwu6QyORHpIIApsdZgb6wBk/DPU15MdyYj/ikn0Hg= +github.com/go-openapi/swag/netutils v0.25.4 h1:Gqe6K71bGRb3ZQLusdI8p/y1KLgV4M/k+/HzVSqT8H0= +github.com/go-openapi/swag/netutils v0.25.4/go.mod h1:m2W8dtdaoX7oj9rEttLyTeEFFEBvnAx9qHd5nJEBzYg= +github.com/go-openapi/swag/stringutils v0.25.4 h1:O6dU1Rd8bej4HPA3/CLPciNBBDwZj9HiEpdVsb8B5A8= +github.com/go-openapi/swag/stringutils v0.25.4/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0= +github.com/go-openapi/swag/typeutils v0.25.4 h1:1/fbZOUN472NTc39zpa+YGHn3jzHWhv42wAJSN91wRw= +github.com/go-openapi/swag/typeutils v0.25.4/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE= +github.com/go-openapi/swag/yamlutils v0.25.4 h1:6jdaeSItEUb7ioS9lFoCZ65Cne1/RZtPBZ9A56h92Sw= +github.com/go-openapi/swag/yamlutils v0.25.4/go.mod h1:MNzq1ulQu+yd8Kl7wPOut/YHAAU/H6hL91fF+E2RFwc= +github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4= +github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg= +github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls= +github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= -github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= -github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= +github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= +github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -88,8 +116,6 @@ 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.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= @@ -102,8 +128,6 @@ 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/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4= -github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -128,8 +152,6 @@ github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaR github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 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= @@ -139,8 +161,8 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= -github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= -github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= +github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws= +github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= @@ -223,8 +245,8 @@ google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4= -gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= +gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= +gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= @@ -241,14 +263,14 @@ k8s.io/cloud-provider v0.34.1 h1:FS+4C1vq9pIngd/5LR5Jha1sEbn+fo0HJitgZmUyBNc= k8s.io/cloud-provider v0.34.1/go.mod h1:ghyQYfQIWZAXKNS+TEgEiQ8wPuhzIVt3wFO6rKqS/rQ= k8s.io/component-base v0.34.3 h1:zsEgw6ELqK0XncCQomgO9DpUIzlrYuZYA0Cgo+JWpVk= k8s.io/component-base v0.34.3/go.mod h1:5iIlD8wPfWE/xSHTRfbjuvUul2WZbI2nOUK65XL0E/c= -k8s.io/component-helpers v0.34.2 h1:RIUGDdU+QFzeVKLZ9f05sXTNAtJrRJ3bnbMLrogCrvM= -k8s.io/component-helpers v0.34.2/go.mod h1:pLi+GByuRTeFjjcezln8gHL7LcT6HImkwVQ3A2SQaEE= +k8s.io/component-helpers v0.34.3 h1:Iws1GQfM89Lxo7IZITGmVdFOW0Bmyd7SVwwIu1/CCkE= +k8s.io/component-helpers v0.34.3/go.mod h1:S8HjjMTrUDVMVPo2EdNYRtQx9uIEIueQYdPMOe9UxJs= k8s.io/csi-translation-lib v0.34.1 h1:8+QMIWBwPGFsqWw9eAvimA2GaHXGgLLYT61I1NzDnXw= k8s.io/csi-translation-lib v0.34.1/go.mod h1:QXytPJ1KzYQaiMgVm82ANG+RGAUf276m8l9gFT+R6Xg= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= -k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b h1:MloQ9/bdJyIu9lb1PzujOPolHyvO06MXG5TUIj2mNAA= -k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b/go.mod h1:UZ2yyWbFTpuhSbFhv24aGNOdoRdJZgsIObGBUaYVsts= +k8s.io/kube-openapi v0.0.0-20251125145642-4e65d59e963e h1:iW9ChlU0cU16w8MpVYjXk12dqQ4BPFBEgif+ap7/hqQ= +k8s.io/kube-openapi v0.0.0-20251125145642-4e65d59e963e/go.mod h1:kdmbQkyfwUagLfXIad1y2TdrjPFWp2Q89B3qkRwf/pQ= k8s.io/utils v0.0.0-20260108192941-914a6e750570 h1:JT4W8lsdrGENg9W+YwwdLJxklIuKWdRm+BC+xt33FOY= k8s.io/utils v0.0.0-20260108192941-914a6e750570/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= sigs.k8s.io/controller-runtime v0.22.4 h1:GEjV7KV3TY8e+tJ2LCTxUTanW4z/FmNB7l327UfMq9A= @@ -257,7 +279,7 @@ sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5E sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v6 v6.3.0 h1:jTijUJbW353oVOd9oTlifJqOGEkUw2jB/fXCbTiQEco= -sigs.k8s.io/structured-merge-diff/v6 v6.3.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/structured-merge-diff/v6 v6.3.1 h1:JrhdFMqOd/+3ByqlP2I45kTOZmTRLBUm5pvRjeheg7E= +sigs.k8s.io/structured-merge-diff/v6 v6.3.1/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/api/hypershift/v1beta1/hosted_controlplane.go b/api/hypershift/v1beta1/hosted_controlplane.go index 585a3b3d4193..a79f948481e4 100644 --- a/api/hypershift/v1beta1/hosted_controlplane.go +++ b/api/hypershift/v1beta1/hosted_controlplane.go @@ -332,6 +332,12 @@ type HostedControlPlaneStatus struct { // +kubebuilder:default=false Initialized bool `json:"initialized"` + // initialization contains observations of the HostedControlPlane initialization process. + // This satisfies the CAPI v1beta2 ControlPlane provider contract: + // https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + // +optional + Initialization HostedControlPlaneInitializationStatus `json:"initialization,omitzero,omitempty"` + // externalManagedControlPlane indicates to cluster-api that the control plane // is managed by an external service. // https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 @@ -447,3 +453,17 @@ type HostedControlPlaneList struct { // +kubebuilder:validation:MaxItems=100 Items []HostedControlPlane `json:"items"` } + +// HostedControlPlaneInitializationStatus provides observations of the HostedControlPlane initialization process. +// This satisfies the CAPI v1beta2 ControlPlane provider contract: +// https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1361-L1379 +// +kubebuilder:validation:MinProperties=1 +type HostedControlPlaneInitializationStatus struct { + // controlPlaneInitialized is true when the control plane is functional enough to accept requests. + // Once this condition is marked true, its value is never changed. See the Ready condition for an + // indication of the current readiness of the cluster's control plane. + // This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + // +optional + // +default=false + ControlPlaneInitialized *bool `json:"controlPlaneInitialized,omitempty"` +} diff --git a/api/hypershift/v1beta1/zz_generated.deepcopy.go b/api/hypershift/v1beta1/zz_generated.deepcopy.go index 558be0746f8f..d10fca24596b 100644 --- a/api/hypershift/v1beta1/zz_generated.deepcopy.go +++ b/api/hypershift/v1beta1/zz_generated.deepcopy.go @@ -2482,6 +2482,26 @@ func (in *HostedControlPlane) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HostedControlPlaneInitializationStatus) DeepCopyInto(out *HostedControlPlaneInitializationStatus) { + *out = *in + if in.ControlPlaneInitialized != nil { + in, out := &in.ControlPlaneInitialized, &out.ControlPlaneInitialized + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HostedControlPlaneInitializationStatus. +func (in *HostedControlPlaneInitializationStatus) DeepCopy() *HostedControlPlaneInitializationStatus { + if in == nil { + return nil + } + out := new(HostedControlPlaneInitializationStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HostedControlPlaneList) DeepCopyInto(out *HostedControlPlaneList) { *out = *in @@ -2636,6 +2656,7 @@ func (in *HostedControlPlaneStatus) DeepCopyInto(out *HostedControlPlaneStatus) (*in)[i].DeepCopyInto(&(*out)[i]) } } + in.Initialization.DeepCopyInto(&out.Initialization) if in.ExternalManagedControlPlane != nil { in, out := &in.ExternalManagedControlPlane, &out.ExternalManagedControlPlane *out = new(bool) diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/AAA_ungated.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/AAA_ungated.yaml index 686911fdc570..aff707008e73 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/AAA_ungated.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/AAA_ungated.yaml @@ -6388,6 +6388,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/AutoNodeKarpenter.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/AutoNodeKarpenter.yaml index 5734a4a07203..ce10f2665187 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/AutoNodeKarpenter.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/AutoNodeKarpenter.yaml @@ -6529,6 +6529,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ClusterUpdateAcceptRisks.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ClusterUpdateAcceptRisks.yaml index 73c5127c6d3a..a81952295603 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ClusterUpdateAcceptRisks.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ClusterUpdateAcceptRisks.yaml @@ -6371,6 +6371,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ClusterVersionOperatorConfiguration.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ClusterVersionOperatorConfiguration.yaml index add1e279eb0a..ef58edd35a15 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ClusterVersionOperatorConfiguration.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ClusterVersionOperatorConfiguration.yaml @@ -6391,6 +6391,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDC.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDC.yaml index d43b7e886e58..70dda84120c6 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDC.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDC.yaml @@ -6869,6 +6869,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDCWithUIDAndExtraClaimMappings.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDCWithUIDAndExtraClaimMappings.yaml index 537ca6bcd8d5..0be4260efc85 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDCWithUIDAndExtraClaimMappings.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDCWithUIDAndExtraClaimMappings.yaml @@ -7009,6 +7009,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDCWithUpstreamParity.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDCWithUpstreamParity.yaml index 694d7f503dee..0d579399829f 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDCWithUpstreamParity.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ExternalOIDCWithUpstreamParity.yaml @@ -6825,6 +6825,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/GCPPlatform.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/GCPPlatform.yaml index 1b783eed7864..75d5cdefc8f9 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/GCPPlatform.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/GCPPlatform.yaml @@ -6791,6 +6791,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/HCPEtcdBackup.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/HCPEtcdBackup.yaml index 2d02293b2ce7..db63a7869197 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/HCPEtcdBackup.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/HCPEtcdBackup.yaml @@ -6436,6 +6436,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/HyperShiftOnlyDynamicResourceAllocation.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/HyperShiftOnlyDynamicResourceAllocation.yaml index 840711e1f717..31010b28f2d6 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/HyperShiftOnlyDynamicResourceAllocation.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/HyperShiftOnlyDynamicResourceAllocation.yaml @@ -6393,6 +6393,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ImageStreamImportMode.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ImageStreamImportMode.yaml index de33ad869174..de17da687597 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ImageStreamImportMode.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/ImageStreamImportMode.yaml @@ -6400,6 +6400,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/KMSEncryptionProvider.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/KMSEncryptionProvider.yaml index d21ea317bbdd..35bbe40a8271 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/KMSEncryptionProvider.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/KMSEncryptionProvider.yaml @@ -6447,6 +6447,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/OpenStack.yaml b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/OpenStack.yaml index 202b102df79c..b88646c74a1d 100644 --- a/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/OpenStack.yaml +++ b/api/hypershift/v1beta1/zz_generated.featuregated-crd-manifests/hostedcontrolplanes.hypershift.openshift.io/OpenStack.yaml @@ -6922,6 +6922,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/api/vendor/github.com/emicklei/go-restful/v3/.travis.yml b/api/vendor/github.com/emicklei/go-restful/v3/.travis.yml deleted file mode 100644 index 3a0bf5ff1b81..000000000000 --- a/api/vendor/github.com/emicklei/go-restful/v3/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -go: - - 1.x - -before_install: - - go test -v - -script: - - go test -race -coverprofile=coverage.txt -covermode=atomic - -after_success: - - bash <(curl -s https://codecov.io/bash) \ No newline at end of file diff --git a/api/vendor/github.com/emicklei/go-restful/v3/CHANGES.md b/api/vendor/github.com/emicklei/go-restful/v3/CHANGES.md index 6f24dfff562e..4fcd920abea4 100644 --- a/api/vendor/github.com/emicklei/go-restful/v3/CHANGES.md +++ b/api/vendor/github.com/emicklei/go-restful/v3/CHANGES.md @@ -1,5 +1,9 @@ # Change history of go-restful +## [v3.13.0] - 2025-08-14 + +- optimize performance of path matching in CurlyRouter ( thanks @wenhuang, Wen Huang) + ## [v3.12.2] - 2025-02-21 - allow empty payloads in post,put,patch, issue #580 ( thanks @liggitt, Jordan Liggitt) diff --git a/api/vendor/github.com/emicklei/go-restful/v3/README.md b/api/vendor/github.com/emicklei/go-restful/v3/README.md index 3fb40d198087..50a79ab692d7 100644 --- a/api/vendor/github.com/emicklei/go-restful/v3/README.md +++ b/api/vendor/github.com/emicklei/go-restful/v3/README.md @@ -84,6 +84,7 @@ func (u UserResource) findUser(request *restful.Request, response *restful.Respo - Configurable (trace) logging - Customizable gzip/deflate readers and writers using CompressorProvider registration - Inject your own http.Handler using the `HttpMiddlewareHandlerToFilter` function +- Added `SetPathTokenCacheEnabled` and `SetCustomVerbCacheEnabled` to disable regexp caching (default=true) ## How to customize There are several hooks to customize the behavior of the go-restful package. diff --git a/api/vendor/github.com/emicklei/go-restful/v3/curly.go b/api/vendor/github.com/emicklei/go-restful/v3/curly.go index 6fd2bcd5a117..eec43bfd0674 100644 --- a/api/vendor/github.com/emicklei/go-restful/v3/curly.go +++ b/api/vendor/github.com/emicklei/go-restful/v3/curly.go @@ -9,11 +9,35 @@ import ( "regexp" "sort" "strings" + "sync" ) // CurlyRouter expects Routes with paths that contain zero or more parameters in curly brackets. type CurlyRouter struct{} +var ( + regexCache sync.Map // Cache for compiled regex patterns + pathTokenCacheEnabled = true // Enable/disable path token regex caching +) + +// SetPathTokenCacheEnabled enables or disables path token regex caching for CurlyRouter. +// When disabled, regex patterns will be compiled on every request. +// When enabled (default), compiled regex patterns are cached for better performance. +func SetPathTokenCacheEnabled(enabled bool) { + pathTokenCacheEnabled = enabled +} + +// getCachedRegexp retrieves a compiled regex from the cache if found and valid. +// Returns the regex and true if found and valid, nil and false otherwise. +func getCachedRegexp(cache *sync.Map, pattern string) (*regexp.Regexp, bool) { + if cached, found := cache.Load(pattern); found { + if regex, ok := cached.(*regexp.Regexp); ok { + return regex, true + } + } + return nil, false +} + // SelectRoute is part of the Router interface and returns the best match // for the WebService and its Route for the given Request. func (c CurlyRouter) SelectRoute( @@ -113,8 +137,28 @@ func (c CurlyRouter) regularMatchesPathToken(routeToken string, colon int, reque } return true, true } - matched, err := regexp.MatchString(regPart, requestToken) - return (matched && err == nil), false + + // Check cache first (if enabled) + if pathTokenCacheEnabled { + if regex, found := getCachedRegexp(®exCache, regPart); found { + matched := regex.MatchString(requestToken) + return matched, false + } + } + + // Compile the regex + regex, err := regexp.Compile(regPart) + if err != nil { + return false, false + } + + // Cache the regex (if enabled) + if pathTokenCacheEnabled { + regexCache.Store(regPart, regex) + } + + matched := regex.MatchString(requestToken) + return matched, false } var jsr311Router = RouterJSR311{} @@ -168,7 +212,7 @@ func (c CurlyRouter) computeWebserviceScore(requestTokens []string, routeTokens if matchesToken { score++ // extra score for regex match } - } + } } else { // not a parameter if eachRequestToken != eachRouteToken { diff --git a/api/vendor/github.com/emicklei/go-restful/v3/custom_verb.go b/api/vendor/github.com/emicklei/go-restful/v3/custom_verb.go index bfc17efde80f..0b98eeb091cd 100644 --- a/api/vendor/github.com/emicklei/go-restful/v3/custom_verb.go +++ b/api/vendor/github.com/emicklei/go-restful/v3/custom_verb.go @@ -1,14 +1,28 @@ package restful +// Copyright 2025 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + import ( "fmt" "regexp" + "sync" ) var ( - customVerbReg = regexp.MustCompile(":([A-Za-z]+)$") + customVerbReg = regexp.MustCompile(":([A-Za-z]+)$") + customVerbCache sync.Map // Cache for compiled custom verb regexes + customVerbCacheEnabled = true // Enable/disable custom verb regex caching ) +// SetCustomVerbCacheEnabled enables or disables custom verb regex caching. +// When disabled, custom verb regex patterns will be compiled on every request. +// When enabled (default), compiled custom verb regex patterns are cached for better performance. +func SetCustomVerbCacheEnabled(enabled bool) { + customVerbCacheEnabled = enabled +} + func hasCustomVerb(routeToken string) bool { return customVerbReg.MatchString(routeToken) } @@ -20,7 +34,23 @@ func isMatchCustomVerb(routeToken string, pathToken string) bool { } customVerb := rs[1] - specificVerbReg := regexp.MustCompile(fmt.Sprintf(":%s$", customVerb)) + regexPattern := fmt.Sprintf(":%s$", customVerb) + + // Check cache first (if enabled) + if customVerbCacheEnabled { + if specificVerbReg, found := getCachedRegexp(&customVerbCache, regexPattern); found { + return specificVerbReg.MatchString(pathToken) + } + } + + // Compile the regex + specificVerbReg := regexp.MustCompile(regexPattern) + + // Cache the regex (if enabled) + if customVerbCacheEnabled { + customVerbCache.Store(regexPattern, specificVerbReg) + } + return specificVerbReg.MatchString(pathToken) } diff --git a/api/vendor/github.com/emicklei/go-restful/v3/doc.go b/api/vendor/github.com/emicklei/go-restful/v3/doc.go index 69b13057d017..80809225b8d5 100644 --- a/api/vendor/github.com/emicklei/go-restful/v3/doc.go +++ b/api/vendor/github.com/emicklei/go-restful/v3/doc.go @@ -1,7 +1,7 @@ /* Package restful , a lean package for creating REST-style WebServices without magic. -WebServices and Routes +### WebServices and Routes A WebService has a collection of Route objects that dispatch incoming Http Requests to a function calls. Typically, a WebService has a root path (e.g. /users) and defines common MIME types for its routes. @@ -30,14 +30,14 @@ The (*Request, *Response) arguments provide functions for reading information fr See the example https://github.com/emicklei/go-restful/blob/v3/examples/user-resource/restful-user-resource.go with a full implementation. -Regular expression matching Routes +### Regular expression matching Routes A Route parameter can be specified using the format "uri/{var[:regexp]}" or the special version "uri/{var:*}" for matching the tail of the path. For example, /persons/{name:[A-Z][A-Z]} can be used to restrict values for the parameter "name" to only contain capital alphabetic characters. Regular expressions must use the standard Go syntax as described in the regexp package. (https://code.google.com/p/re2/wiki/Syntax) This feature requires the use of a CurlyRouter. -Containers +### Containers A Container holds a collection of WebServices, Filters and a http.ServeMux for multiplexing http requests. Using the statements "restful.Add(...) and restful.Filter(...)" will register WebServices and Filters to the Default Container. @@ -47,7 +47,7 @@ You can create your own Container and create a new http.Server for that particul container := restful.NewContainer() server := &http.Server{Addr: ":8081", Handler: container} -Filters +### Filters A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. You can use filters to perform generic logging, measurement, authentication, redirect, set response headers etc. @@ -60,22 +60,21 @@ Use the following statement to pass the request,response pair to the next filter chain.ProcessFilter(req, resp) -Container Filters +### Container Filters These are processed before any registered WebService. // install a (global) filter for the default container (processed before any webservice) restful.Filter(globalLogging) -WebService Filters +### WebService Filters These are processed before any Route of a WebService. // install a webservice filter (processed before any route) ws.Filter(webserviceLogging).Filter(measureTime) - -Route Filters +### Route Filters These are processed before calling the function associated with the Route. @@ -84,7 +83,7 @@ These are processed before calling the function associated with the Route. See the example https://github.com/emicklei/go-restful/blob/v3/examples/filters/restful-filters.go with full implementations. -Response Encoding +### Response Encoding Two encodings are supported: gzip and deflate. To enable this for all responses: @@ -95,20 +94,20 @@ Alternatively, you can create a Filter that performs the encoding and install it See the example https://github.com/emicklei/go-restful/blob/v3/examples/encoding/restful-encoding-filter.go -OPTIONS support +### OPTIONS support By installing a pre-defined container filter, your Webservice(s) can respond to the OPTIONS Http request. Filter(OPTIONSFilter()) -CORS +### CORS By installing the filter of a CrossOriginResourceSharing (CORS), your WebService(s) can handle CORS requests. cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} Filter(cors.Filter) -Error Handling +### Error Handling Unexpected things happen. If a request cannot be processed because of a failure, your service needs to tell via the response what happened and why. For this reason HTTP status codes exist and it is important to use the correct code in every exceptional situation. @@ -137,11 +136,11 @@ The request does not have or has an unknown Accept Header set for this operation The request does not have or has an unknown Content-Type Header set for this operation. -ServiceError +### ServiceError In addition to setting the correct (error) Http status code, you can choose to write a ServiceError message on the response. -Performance options +### Performance options This package has several options that affect the performance of your service. It is important to understand them and how you can change it. @@ -156,30 +155,27 @@ Default value is true If content encoding is enabled then the default strategy for getting new gzip/zlib writers and readers is to use a sync.Pool. Because writers are expensive structures, performance is even more improved when using a preloaded cache. You can also inject your own implementation. -Trouble shooting +### Trouble shooting This package has the means to produce detail logging of the complete Http request matching process and filter invocation. Enabling this feature requires you to set an implementation of restful.StdLogger (e.g. log.Logger) instance such as: restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) -Logging +### Logging The restful.SetLogger() method allows you to override the logger used by the package. By default restful uses the standard library `log` package and logs to stdout. Different logging packages are supported as long as they conform to `StdLogger` interface defined in the `log` sub-package, writing an adapter for your preferred package is simple. -Resources +### Resources -[project]: https://github.com/emicklei/go-restful +(c) 2012-2025, http://ernestmicklei.com. MIT License +[project]: https://github.com/emicklei/go-restful [examples]: https://github.com/emicklei/go-restful/blob/master/examples - -[design]: http://ernestmicklei.com/2012/11/11/go-restful-api-design/ - +[design]: http://ernestmicklei.com/2012/11/11/go-restful-api-design/ [showcases]: https://github.com/emicklei/mora, https://github.com/emicklei/landskape - -(c) 2012-2015, http://ernestmicklei.com. MIT License */ package restful diff --git a/api/vendor/github.com/go-openapi/jsonpointer/.cliff.toml b/api/vendor/github.com/go-openapi/jsonpointer/.cliff.toml new file mode 100644 index 000000000000..702629f5dc30 --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonpointer/.cliff.toml @@ -0,0 +1,181 @@ +# git-cliff ~ configuration file +# https://git-cliff.org/docs/configuration + +[changelog] +header = """ +""" + +footer = """ + +----- + +**[{{ remote.github.repo }}]({{ self::remote_url() }}) license terms** + +[![License][license-badge]][license-url] + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: {{ self::remote_url() }}/?tab=Apache-2.0-1-ov-file#readme + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" + +body = """ +{%- if version %} +## [{{ version | trim_start_matches(pat="v") }}]({{ self::remote_url() }}/tree/{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }} +{%- else %} +## [unreleased] +{%- endif %} +{%- if message %} + {%- raw %}\n{% endraw %} +{{ message }} + {%- raw %}\n{% endraw %} +{%- endif %} +{%- if version %} + {%- if previous.version %} + +**Full Changelog**: <{{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}> + {%- endif %} +{%- else %} + {%- raw %}\n{% endraw %} +{%- endif %} + +{%- if statistics %}{% if statistics.commit_count %} + {%- raw %}\n{% endraw %} +{{ statistics.commit_count }} commits in this release. + {%- raw %}\n{% endraw %} +{%- endif %}{% endif %} +----- + +{%- for group, commits in commits | group_by(attribute="group") %} + {%- raw %}\n{% endraw %} +### {{ group | upper_first }} + {%- raw %}\n{% endraw %} + {%- for commit in commits %} + {%- if commit.remote.pr_title %} + {%- set commit_message = commit.remote.pr_title %} + {%- else %} + {%- set commit_message = commit.message %} + {%- endif %} +* {{ commit_message | split(pat="\n") | first | trim }} + {%- if commit.remote.username %} +{%- raw %} {% endraw %}by [@{{ commit.remote.username }}](https://github.com/{{ commit.remote.username }}) + {%- endif %} + {%- if commit.remote.pr_number %} +{%- raw %} {% endraw %}in [#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) + {%- endif %} +{%- raw %} {% endraw %}[...]({{ self::remote_url() }}/commit/{{ commit.id }}) + {%- endfor %} +{%- endfor %} + +{%- if github %} +{%- raw %}\n{% endraw -%} + {%- set all_contributors = github.contributors | length %} + {%- if github.contributors | filter(attribute="username", value="dependabot[bot]") | length < all_contributors %} +----- + +### People who contributed to this release + {% endif %} + {%- for contributor in github.contributors | filter(attribute="username") | sort(attribute="username") %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* [@{{ contributor.username }}](https://github.com/{{ contributor.username }}) + {%- endif %} + {%- endfor %} + + {% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} +----- + {%- raw %}\n{% endraw %} + +### New Contributors + {%- endif %} + + {%- for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* @{{ contributor.username }} made their first contribution + {%- if contributor.pr_number %} + in [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ + {%- endif %} + {%- endif %} + {%- endfor %} +{%- endif %} + +{%- raw %}\n{% endraw %} + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" +# Remove leading and trailing whitespaces from the changelog's body. +trim = true +# Render body even when there are no releases to process. +render_always = true +# An array of regex based postprocessors to modify the changelog. +postprocessors = [ + # Replace the placeholder with a URL. + #{ pattern = '', replace = "https://github.com/orhun/git-cliff" }, +] +# output file path +# output = "test.md" + +[git] +# Parse commits according to the conventional commits specification. +# See https://www.conventionalcommits.org +conventional_commits = false +# Exclude commits that do not match the conventional commits specification. +filter_unconventional = false +# Require all commits to be conventional. +# Takes precedence over filter_unconventional. +require_conventional = false +# Split commits on newlines, treating each line as an individual commit. +split_commits = false +# An array of regex based parsers to modify commit messages prior to further processing. +commit_preprocessors = [ + # Replace issue numbers with link templates to be updated in `changelog.postprocessors`. + #{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, + # Check spelling of the commit message using https://github.com/crate-ci/typos. + # If the spelling is incorrect, it will be fixed automatically. + #{ pattern = '.*', replace_command = 'typos --write-changes -' } +] +# Prevent commits that are breaking from being excluded by commit parsers. +protect_breaking_commits = false +# An array of regex based parsers for extracting data from the commit message. +# Assigns commits to groups. +# Optionally sets the commit's scope and can decide to exclude commits from further processing. +commit_parsers = [ + { message = "^[Cc]hore\\([Rr]elease\\): prepare for", skip = true }, + { message = "(^[Mm]erge)|([Mm]erge conflict)", skip = true }, + { field = "author.name", pattern = "dependabot*", group = "Updates" }, + { message = "([Ss]ecurity)|([Vv]uln)", group = "Security" }, + { body = "(.*[Ss]ecurity)|([Vv]uln)", group = "Security" }, + { message = "([Cc]hore\\(lint\\))|(style)|(lint)|(codeql)|(golangci)", group = "Code quality" }, + { message = "(^[Dd]oc)|((?i)readme)|(badge)|(typo)|(documentation)", group = "Documentation" }, + { message = "(^[Ff]eat)|(^[Ee]nhancement)", group = "Implemented enhancements" }, + { message = "(^ci)|(\\(ci\\))|(fixup\\s+ci)|(fix\\s+ci)|(license)|(example)", group = "Miscellaneous tasks" }, + { message = "^test", group = "Testing" }, + { message = "(^fix)|(panic)", group = "Fixed bugs" }, + { message = "(^refact)|(rework)", group = "Refactor" }, + { message = "(^[Pp]erf)|(performance)", group = "Performance" }, + { message = "(^[Cc]hore)", group = "Miscellaneous tasks" }, + { message = "^[Rr]evert", group = "Reverted changes" }, + { message = "(upgrade.*?go)|(go\\s+version)", group = "Updates" }, + { message = ".*", group = "Other" }, +] +# Exclude commits that are not matched by any commit parser. +filter_commits = false +# An array of link parsers for extracting external references, and turning them into URLs, using regex. +link_parsers = [] +# Include only the tags that belong to the current branch. +use_branch_tags = false +# Order releases topologically instead of chronologically. +topo_order = false +# Order releases topologically instead of chronologically. +topo_order_commits = true +# Order of commits in each group/release within the changelog. +# Allowed values: newest, oldest +sort_commits = "newest" +# Process submodules commits +recurse_submodules = false + +#[remote.github] +#owner = "go-openapi" diff --git a/api/vendor/github.com/go-openapi/jsonpointer/.gitignore b/api/vendor/github.com/go-openapi/jsonpointer/.gitignore index 769c244007b5..59cd29489150 100644 --- a/api/vendor/github.com/go-openapi/jsonpointer/.gitignore +++ b/api/vendor/github.com/go-openapi/jsonpointer/.gitignore @@ -1 +1,4 @@ -secrets.yml +*.out +*.cov +.idea +.env diff --git a/api/vendor/github.com/go-openapi/jsonpointer/.golangci.yml b/api/vendor/github.com/go-openapi/jsonpointer/.golangci.yml index d2fafb8a2bb0..fdae591bce71 100644 --- a/api/vendor/github.com/go-openapi/jsonpointer/.golangci.yml +++ b/api/vendor/github.com/go-openapi/jsonpointer/.golangci.yml @@ -1,56 +1,66 @@ -linters-settings: - gocyclo: - min-complexity: 45 - dupl: - threshold: 200 - goconst: - min-len: 2 - min-occurrences: 3 - +version: "2" linters: - enable-all: true + default: all disable: - - recvcheck - - unparam - - lll - - gochecknoinits - - gochecknoglobals + - depguard - funlen - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage + - exhaustruct - nlreturn - - errorlint - - nestif - - godot - - gofumpt + - nonamedreturns + - noinlineerr - paralleltest + - recvcheck + - testpackage - tparallel - - thelper - - exhaustruct - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - #- deadcode - #- interfacer - #- scopelint - #- varcheck - #- structcheck - #- golint - #- nosnakecase - #- maligned - #- goerr113 - #- ifshort - #- gomnd - #- exhaustivestruct + - whitespace + - wrapcheck + - wsl + - wsl_v5 + settings: + dupl: + threshold: 200 + goconst: + min-len: 2 + min-occurrences: 3 + cyclop: + max-complexity: 20 + gocyclo: + min-complexity: 20 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + - gofumpt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ +issues: + # Maximum issues count per one linter. + # Set to 0 to disable. + # Default: 50 + max-issues-per-linter: 0 + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 0 diff --git a/api/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md b/api/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md new file mode 100644 index 000000000000..03c098316d45 --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md @@ -0,0 +1,24 @@ +# Contributors + +- Repository: ['go-openapi/jsonpointer'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 12 | 95 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 48 | https://github.com/go-openapi/jsonpointer/commits?author=fredbi | +| @casualjim | 33 | https://github.com/go-openapi/jsonpointer/commits?author=casualjim | +| @magodo | 3 | https://github.com/go-openapi/jsonpointer/commits?author=magodo | +| @youyuanwu | 3 | https://github.com/go-openapi/jsonpointer/commits?author=youyuanwu | +| @gaiaz-iusipov | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gaiaz-iusipov | +| @gbjk | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gbjk | +| @gordallott | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gordallott | +| @ianlancetaylor | 1 | https://github.com/go-openapi/jsonpointer/commits?author=ianlancetaylor | +| @mfleader | 1 | https://github.com/go-openapi/jsonpointer/commits?author=mfleader | +| @Neo2308 | 1 | https://github.com/go-openapi/jsonpointer/commits?author=Neo2308 | +| @olivierlemasle | 1 | https://github.com/go-openapi/jsonpointer/commits?author=olivierlemasle | +| @testwill | 1 | https://github.com/go-openapi/jsonpointer/commits?author=testwill | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/api/vendor/github.com/go-openapi/jsonpointer/LICENSE b/api/vendor/github.com/go-openapi/jsonpointer/LICENSE index d64569567334..261eeb9e9f8b 100644 --- a/api/vendor/github.com/go-openapi/jsonpointer/LICENSE +++ b/api/vendor/github.com/go-openapi/jsonpointer/LICENSE @@ -1,4 +1,3 @@ - Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/api/vendor/github.com/go-openapi/jsonpointer/NOTICE b/api/vendor/github.com/go-openapi/jsonpointer/NOTICE new file mode 100644 index 000000000000..f3b51939a95b --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonpointer/NOTICE @@ -0,0 +1,39 @@ +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonpointer, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0. + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original software was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). + +github.com/sigh-399/jsonpointer +=========================== + +// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// SPDX-License-Identifier: Apache-2.0 + +Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/api/vendor/github.com/go-openapi/jsonpointer/README.md b/api/vendor/github.com/go-openapi/jsonpointer/README.md index 0108f1d572d7..b61b63fd9af8 100644 --- a/api/vendor/github.com/go-openapi/jsonpointer/README.md +++ b/api/vendor/github.com/go-openapi/jsonpointer/README.md @@ -1,19 +1,149 @@ -# gojsonpointer [![Build Status](https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/jsonpointer/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) +# jsonpointer -[![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/jsonpointer/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer.svg)](https://pkg.go.dev/github.com/go-openapi/jsonpointer) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/jsonpointer)](https://goreportcard.com/report/github.com/go-openapi/jsonpointer) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Slack Channel][slack-logo]![slack-badge]][slack-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -An implementation of JSON Pointer - Go language +--- + +An implementation of JSON Pointer for golang, which supports go `struct`. ## Status -Completed YES -Tested YES +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/jsonpointer +``` + +## Basic usage + +See also some [examples](./examples_test.go) + +### Retrieving a value + +```go + import ( + "github.com/go-openapi/jsonpointer" + ) + + + var doc any + + ... + + pointer, err := jsonpointer.New("/foo/1") + if err != nil { + ... // error: e.g. invalid JSON pointer specification + } + + value, kind, err := pointer.Get(doc) + if err != nil { + ... // error: e.g. key not found, index out of bounds, etc. + } + + ... +``` + +### Setting a value + +```go + ... + var doc any + ... + pointer, err := jsonpointer.New("/foo/1") + if err != nil { + ... // error: e.g. invalid JSON pointer specification + } + + doc, err = p.Set(doc, "value") + if err != nil { + ... // error: e.g. key not found, index out of bounds, etc. + } +``` + +## Change log + +See ## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 -### Note -The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. + + +also known as [RFC6901](https://www.rfc-editor.org/rfc/rfc6901) + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +See the license [NOTICE](./NOTICE), which recalls the licensing terms of all the pieces of software +on top of which it has been built. + +## Limitations + +The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, +the reference token MUST contain either...' is not implemented. + +That is because our implementation of the JSON pointer only supports explicit references to array elements: +the provision in the spec to resolve non-existent members as "the last element in the array", +using the special trailing character "-" is not implemented. + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/jsonpointer/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/jsonpointer +[vuln-scan-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer +[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonpointer.svg +[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonpointer + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonpointer +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonpointer +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonpointer +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonpointer + +[doc-badge]: https://img.shields.io/badge/doc-site-blue?link=https%3A%2F%2Fgoswagger.io%2Fgo-openapi%2F +[doc-url]: https://goswagger.io/go-openapi +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/jsonpointer +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/jsonpointer/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/jsonpointer +[goversion-url]: https://github.com/go-openapi/jsonpointer/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/jsonpointer +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/jsonpointer/latest diff --git a/api/vendor/github.com/go-openapi/jsonpointer/SECURITY.md b/api/vendor/github.com/go-openapi/jsonpointer/SECURITY.md new file mode 100644 index 000000000000..2a7b6f0910d9 --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonpointer/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.22.x | :white_check_mark: | + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +please report it privately to the maintainers. + +Please follow the instructions provided by github to +[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). + +TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". diff --git a/api/vendor/github.com/go-openapi/jsonpointer/errors.go b/api/vendor/github.com/go-openapi/jsonpointer/errors.go index b84343d9d74e..8c50dde8bcf3 100644 --- a/api/vendor/github.com/go-openapi/jsonpointer/errors.go +++ b/api/vendor/github.com/go-openapi/jsonpointer/errors.go @@ -1,5 +1,10 @@ +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package jsonpointer +import "fmt" + type pointerError string func (e pointerError) Error() string { @@ -7,12 +12,24 @@ func (e pointerError) Error() string { } const ( - // ErrPointer is an error raised by the jsonpointer package + // ErrPointer is a sentinel error raised by all errors from this package. ErrPointer pointerError = "JSON pointer error" - // ErrInvalidStart states that a JSON pointer must start with a separator ("/") + // ErrInvalidStart states that a JSON pointer must start with a separator ("/"). ErrInvalidStart pointerError = `JSON pointer must be empty or start with a "` + pointerSeparator - // ErrUnsupportedValueType indicates that a value of the wrong type is being set + // ErrUnsupportedValueType indicates that a value of the wrong type is being set. ErrUnsupportedValueType pointerError = "only structs, pointers, maps and slices are supported for setting values" ) + +func errNoKey(key string) error { + return fmt.Errorf("object has no key %q: %w", key, ErrPointer) +} + +func errOutOfBounds(length, idx int) error { + return fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", length-1, idx, ErrPointer) +} + +func errInvalidReference(token string) error { + return fmt.Errorf("invalid token reference %q: %w", token, ErrPointer) +} diff --git a/api/vendor/github.com/go-openapi/jsonpointer/pointer.go b/api/vendor/github.com/go-openapi/jsonpointer/pointer.go index a08cd68ac04e..7df49af3b96a 100644 --- a/api/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ b/api/vendor/github.com/go-openapi/jsonpointer/pointer.go @@ -1,28 +1,7 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonpointer -// repository-desc An implementation of JSON Pointer - Go language -// -// description Main and unique file. -// -// created 25-02-2013 +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 +// Package jsonpointer provides a golang implementation for json pointers. package jsonpointer import ( @@ -33,7 +12,7 @@ import ( "strconv" "strings" - "github.com/go-openapi/swag" + "github.com/go-openapi/swag/jsonname" ) const ( @@ -41,70 +20,273 @@ const ( pointerSeparator = `/` ) -var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() -var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() - -// JSONPointable is an interface for structs to implement when they need to customize the -// json pointer process +// JSONPointable is an interface for structs to implement, +// when they need to customize the json pointer process or want to avoid the use of reflection. type JSONPointable interface { - JSONLookup(string) (any, error) + // JSONLookup returns a value pointed at this (unescaped) key. + JSONLookup(key string) (any, error) } -// JSONSetable is an interface for structs to implement when they need to customize the -// json pointer process +// JSONSetable is an interface for structs to implement, +// when they need to customize the json pointer process or want to avoid the use of reflection. type JSONSetable interface { - JSONSet(string, any) error + // JSONSet sets the value pointed at the (unescaped) key. + JSONSet(key string, value any) error } -// New creates a new json pointer for the given string -func New(jsonPointerString string) (Pointer, error) { +// Pointer is a representation of a json pointer. +// +// Use [Pointer.Get] to retrieve a value or [Pointer.Set] to set a value. +// +// It works with any go type interpreted as a JSON document, which means: +// +// - if a type implements [JSONPointable], its [JSONPointable.JSONLookup] method is used to resolve [Pointer.Get] +// - if a type implements [JSONSetable], its [JSONPointable.JSONSet] method is used to resolve [Pointer.Set] +// - a go map[K]V is interpreted as an object, with type K assignable to a string +// - a go slice []T is interpreted as an array +// - a go struct is interpreted as an object, with exported fields interpreted as keys +// - promoted fields from an embedded struct are traversed +// - scalars (e.g. int, float64 ...), channels, functions and go arrays cannot be traversed +// +// For struct s resolved by reflection, key mappings honor the conventional struct tag `json`. +// +// Fields that do not specify a `json` tag, or specify an empty one, or are tagged as `json:"-"` are ignored. +// +// # Limitations +// +// - Unlike go standard marshaling, untagged fields do not default to the go field name and are ignored. +// - anonymous fields are not traversed if untagged +type Pointer struct { + referenceTokens []string +} +// New creates a new json pointer from its string representation. +func New(jsonPointerString string) (Pointer, error) { var p Pointer err := p.parse(jsonPointerString) + return p, err +} +// Get uses the pointer to retrieve a value from a JSON document. +// +// It returns the value with its type as a [reflect.Kind] or an error. +func (p *Pointer) Get(document any) (any, reflect.Kind, error) { + return p.get(document, jsonname.DefaultJSONNameProvider) } -// Pointer the json pointer reprsentation -type Pointer struct { - referenceTokens []string +// Set uses the pointer to set a value from a data type +// that represent a JSON document. +// +// It returns the updated document. +func (p *Pointer) Set(document any, value any) (any, error) { + return document, p.set(document, value, jsonname.DefaultJSONNameProvider) } -// "Constructor", parses the given string JSON pointer -func (p *Pointer) parse(jsonPointerString string) error { +// DecodedTokens returns the decoded (unescaped) tokens of this JSON pointer. +func (p *Pointer) DecodedTokens() []string { + result := make([]string, 0, len(p.referenceTokens)) + for _, token := range p.referenceTokens { + result = append(result, Unescape(token)) + } - var err error + return result +} - if jsonPointerString != emptyPointer { - if !strings.HasPrefix(jsonPointerString, pointerSeparator) { - err = errors.Join(ErrInvalidStart, ErrPointer) - } else { - referenceTokens := strings.Split(jsonPointerString, pointerSeparator) - p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) - } +// IsEmpty returns true if this is an empty json pointer. +// +// This indicates that it points to the root document. +func (p *Pointer) IsEmpty() bool { + return len(p.referenceTokens) == 0 +} + +// String representation of a pointer. +func (p *Pointer) String() string { + if len(p.referenceTokens) == 0 { + return emptyPointer } - return err + return pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) } -// Get uses the pointer to retrieve a value from a JSON document -func (p *Pointer) Get(document any) (any, reflect.Kind, error) { - return p.get(document, swag.DefaultJSONNameProvider) +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: %w", tk, ErrPointer) + } + default: + return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) + } + } + return offset, nil } -// Set uses the pointer to set a value from a JSON document -func (p *Pointer) Set(document any, value any) (any, error) { - return document, p.set(document, value, swag.DefaultJSONNameProvider) +// "Constructor", parses the given string JSON pointer. +func (p *Pointer) parse(jsonPointerString string) error { + if jsonPointerString == emptyPointer { + return nil + } + + if !strings.HasPrefix(jsonPointerString, pointerSeparator) { + // non empty pointer must start with "/" + return errors.Join(ErrInvalidStart, ErrPointer) + } + + referenceTokens := strings.Split(jsonPointerString, pointerSeparator) + p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) + + return nil } -// GetForToken gets a value for a json pointer token 1 level deep -func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { - return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) +func (p *Pointer) get(node any, nameProvider *jsonname.NameProvider) (any, reflect.Kind, error) { + if nameProvider == nil { + nameProvider = jsonname.DefaultJSONNameProvider + } + + kind := reflect.Invalid + + // full document when empty + if len(p.referenceTokens) == 0 { + return node, kind, nil + } + + for _, token := range p.referenceTokens { + decodedToken := Unescape(token) + + r, knd, err := getSingleImpl(node, decodedToken, nameProvider) + if err != nil { + return nil, knd, err + } + node = r + } + + rValue := reflect.ValueOf(node) + kind = rValue.Kind() + + return node, kind, nil } -// SetForToken gets a value for a json pointer token 1 level deep -func SetForToken(document any, decodedToken string, value any) (any, error) { - return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) +func (p *Pointer) set(node, data any, nameProvider *jsonname.NameProvider) error { + knd := reflect.ValueOf(node).Kind() + + if knd != reflect.Pointer && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { + return errors.Join( + fmt.Errorf("unexpected type: %T", node), //nolint:err113 // err wrapping is carried out by errors.Join, not fmt.Errorf. + ErrUnsupportedValueType, + ErrPointer, + ) + } + + l := len(p.referenceTokens) + + // full document when empty + if l == 0 { + return nil + } + + if nameProvider == nil { + nameProvider = jsonname.DefaultJSONNameProvider + } + + var decodedToken string + lastIndex := l - 1 + + if lastIndex > 0 { // skip if we only have one token in pointer + for _, token := range p.referenceTokens[:lastIndex] { + decodedToken = Unescape(token) + next, err := p.resolveNodeForToken(node, decodedToken, nameProvider) + if err != nil { + return err + } + + node = next + } + } + + // last token + decodedToken = Unescape(p.referenceTokens[lastIndex]) + + return setSingleImpl(node, data, decodedToken, nameProvider) +} + +func (p *Pointer) resolveNodeForToken(node any, decodedToken string, nameProvider *jsonname.NameProvider) (next any, err error) { + // check for nil during traversal + if isNil(node) { + return nil, fmt.Errorf("cannot traverse through nil value at %q: %w", decodedToken, ErrPointer) + } + + pointable, ok := node.(JSONPointable) + if ok { + r, err := pointable.JSONLookup(decodedToken) + if err != nil { + return nil, err + } + + fld := reflect.ValueOf(r) + if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Pointer { + return fld.Addr().Interface(), nil + } + + return r, nil + } + + rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() + + switch kind { + case reflect.Struct: + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return nil, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) + } + + return typeFromValue(rValue.FieldByName(nm)), nil + + case reflect.Map: + kv := reflect.ValueOf(decodedToken) + mv := rValue.MapIndex(kv) + + if !mv.IsValid() { + return nil, errNoKey(decodedToken) + } + + return typeFromValue(mv), nil + + case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return nil, errors.Join(err, ErrPointer) + } + + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return nil, errOutOfBounds(sLength, tokenIndex) + } + + return typeFromValue(rValue.Index(tokenIndex)), nil + + default: + return nil, errInvalidReference(decodedToken) + } } func isNil(input any) bool { @@ -113,15 +295,33 @@ func isNil(input any) bool { } kind := reflect.TypeOf(input).Kind() - switch kind { //nolint:exhaustive - case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: + switch kind { + case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Chan: return reflect.ValueOf(input).IsNil() default: return false } } -func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { +func typeFromValue(v reflect.Value) any { + if v.CanAddr() && v.Kind() != reflect.Interface && v.Kind() != reflect.Map && v.Kind() != reflect.Slice && v.Kind() != reflect.Pointer { + return v.Addr().Interface() + } + + return v.Interface() +} + +// GetForToken gets a value for a json pointer token 1 level deep. +func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { + return getSingleImpl(document, decodedToken, jsonname.DefaultJSONNameProvider) +} + +// SetForToken sets a value for a json pointer token 1 level deep. +func SetForToken(document any, decodedToken string, value any) (any, error) { + return document, setSingleImpl(document, value, decodedToken, jsonname.DefaultJSONNameProvider) +} + +func getSingleImpl(node any, decodedToken string, nameProvider *jsonname.NameProvider) (any, reflect.Kind, error) { rValue := reflect.Indirect(reflect.ValueOf(node)) kind := rValue.Kind() if isNil(node) { @@ -139,13 +339,15 @@ func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvide return getSingleImpl(*typed, decodedToken, nameProvider) } - switch kind { //nolint:exhaustive + switch kind { case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { return nil, kind, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } + fld := rValue.FieldByName(nm) + return fld.Interface(), kind, nil case reflect.Map: @@ -155,261 +357,100 @@ func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvide if mv.IsValid() { return mv.Interface(), kind, nil } - return nil, kind, fmt.Errorf("object has no key %q: %w", decodedToken, ErrPointer) + + return nil, kind, errNoKey(decodedToken) case reflect.Slice: tokenIndex, err := strconv.Atoi(decodedToken) if err != nil { - return nil, kind, err + return nil, kind, errors.Join(err, ErrPointer) } sLength := rValue.Len() if tokenIndex < 0 || tokenIndex >= sLength { - return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", sLength-1, tokenIndex, ErrPointer) + return nil, kind, errOutOfBounds(sLength, tokenIndex) } elem := rValue.Index(tokenIndex) return elem.Interface(), kind, nil default: - return nil, kind, fmt.Errorf("invalid token reference %q: %w", decodedToken, ErrPointer) + return nil, kind, errInvalidReference(decodedToken) } - } -func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameProvider) error { - rValue := reflect.Indirect(reflect.ValueOf(node)) +func setSingleImpl(node, data any, decodedToken string, nameProvider *jsonname.NameProvider) error { + // check for nil to prevent panic when calling rValue.Type() + if isNil(node) { + return fmt.Errorf("cannot set field %q on nil value: %w", decodedToken, ErrPointer) + } - if ns, ok := node.(JSONSetable); ok { // pointer impl + if ns, ok := node.(JSONSetable); ok { return ns.JSONSet(decodedToken, data) } - if rValue.Type().Implements(jsonSetableType) { - return node.(JSONSetable).JSONSet(decodedToken, data) - } + rValue := reflect.Indirect(reflect.ValueOf(node)) - switch rValue.Kind() { //nolint:exhaustive + switch rValue.Kind() { case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { return fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } + fld := rValue.FieldByName(nm) - if fld.IsValid() { - fld.Set(reflect.ValueOf(data)) + if !fld.CanSet() { + return fmt.Errorf("can't set struct field %s to %v: %w", nm, data, ErrPointer) } + + value := reflect.ValueOf(data) + valueType := value.Type() + assignedType := fld.Type() + + if !valueType.AssignableTo(assignedType) { + return fmt.Errorf("can't set value with type %T to field %s with type %v: %w", data, nm, assignedType, ErrPointer) + } + + fld.Set(value) + return nil case reflect.Map: kv := reflect.ValueOf(decodedToken) rValue.SetMapIndex(kv, reflect.ValueOf(data)) + return nil case reflect.Slice: tokenIndex, err := strconv.Atoi(decodedToken) if err != nil { - return err + return errors.Join(err, ErrPointer) } + sLength := rValue.Len() if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", sLength, tokenIndex, ErrPointer) + return errOutOfBounds(sLength, tokenIndex) } elem := rValue.Index(tokenIndex) if !elem.CanSet() { return fmt.Errorf("can't set slice index %s to %v: %w", decodedToken, data, ErrPointer) } - elem.Set(reflect.ValueOf(data)) - return nil - - default: - return fmt.Errorf("invalid token reference %q: %w", decodedToken, ErrPointer) - } - -} -func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { + value := reflect.ValueOf(data) + valueType := value.Type() + assignedType := elem.Type() - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - kind := reflect.Invalid - - // Full document when empty - if len(p.referenceTokens) == 0 { - return node, kind, nil - } - - for _, token := range p.referenceTokens { - decodedToken := Unescape(token) - - r, knd, err := getSingleImpl(node, decodedToken, nameProvider) - if err != nil { - return nil, knd, err + if !valueType.AssignableTo(assignedType) { + return fmt.Errorf("can't set value with type %T to slice element %d with type %v: %w", data, tokenIndex, assignedType, ErrPointer) } - node = r - } - - rValue := reflect.ValueOf(node) - kind = rValue.Kind() - return node, kind, nil -} + elem.Set(value) -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 { - return errors.Join( - ErrUnsupportedValueType, - ErrPointer, - ) - } - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - // Full document when empty - if len(p.referenceTokens) == 0 { return nil - } - - lastI := len(p.referenceTokens) - 1 - for i, token := range p.referenceTokens { - isLastToken := i == lastI - decodedToken := Unescape(token) - - if isLastToken { - - return setSingleImpl(node, data, decodedToken, nameProvider) - } - - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - - if rValue.Type().Implements(jsonPointableType) { - r, err := node.(JSONPointable).JSONLookup(decodedToken) - if err != nil { - return err - } - fld := reflect.ValueOf(r) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = r - continue - } - - switch kind { //nolint:exhaustive - case reflect.Struct: - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) - } - fld := rValue.FieldByName(nm) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = fld.Interface() - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if !mv.IsValid() { - return fmt.Errorf("object has no key %q: %w", decodedToken, ErrPointer) - } - if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr { - node = mv.Addr().Interface() - continue - } - node = mv.Interface() - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", sLength, tokenIndex, ErrPointer) - } - - elem := rValue.Index(tokenIndex) - if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr { - node = elem.Addr().Interface() - continue - } - node = elem.Interface() - - default: - return fmt.Errorf("invalid token reference %q: %w", decodedToken, ErrPointer) - } - - } - - return nil -} - -// DecodedTokens returns the decoded tokens -func (p *Pointer) DecodedTokens() []string { - result := make([]string, 0, len(p.referenceTokens)) - for _, t := range p.referenceTokens { - result = append(result, Unescape(t)) - } - return result -} - -// IsEmpty returns true if this is an empty json pointer -// this indicates that it points to the root document -func (p *Pointer) IsEmpty() bool { - return len(p.referenceTokens) == 0 -} - -// Pointer to string representation function -func (p *Pointer) String() string { - - if len(p.referenceTokens) == 0 { - return emptyPointer - } - pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) - - 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: %w", tk, ErrPointer) - } - default: - return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) - } + default: + return errInvalidReference(decodedToken) } - return offset, nil } func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { @@ -439,13 +480,14 @@ func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) } } + return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer) } 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: %w", decodedToken, err, ErrPointer) + return 0, fmt.Errorf("token reference %q is not a number: %w: %w", decodedToken, err, ErrPointer) } var i int for i = 0; i < idx && dec.More(); i++ { @@ -471,10 +513,12 @@ func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { if !dec.More() { return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer) } + return dec.InputOffset(), nil } // drainSingle drains a single level of object or array. +// // The decoder has to guarantee the beginning delim (i.e. '{' or '[') has been consumed. func drainSingle(dec *json.Decoder) error { for dec.More() { @@ -496,14 +540,15 @@ func drainSingle(dec *json.Decoder) error { } } - // Consumes the ending delim + // consumes the ending delim if _, err := dec.Token(); err != nil { return err } + return nil } -// Specific JSON pointer encoding here +// JSON pointer encoding: // ~0 => ~ // ~1 => / // ... and vice versa @@ -515,16 +560,24 @@ const ( decRefTok1 = `/` ) -// Unescape unescapes a json pointer reference token string to the original representation +var ( + encRefTokReplacer = strings.NewReplacer(encRefTok1, decRefTok1, encRefTok0, decRefTok0) //nolint:gochecknoglobals // it's okay to declare a replacer as a private global + decRefTokReplacer = strings.NewReplacer(decRefTok1, encRefTok1, decRefTok0, encRefTok0) //nolint:gochecknoglobals // it's okay to declare a replacer as a private global +) + +// Unescape unescapes a json pointer reference token string to the original representation. func Unescape(token string) string { - step1 := strings.ReplaceAll(token, encRefTok1, decRefTok1) - step2 := strings.ReplaceAll(step1, encRefTok0, decRefTok0) - return step2 + return encRefTokReplacer.Replace(token) } -// Escape escapes a pointer reference token string +// Escape escapes a pointer reference token string. +// +// The JSONPointer specification defines "/" as a separator and "~" as an escape prefix. +// +// Keys containing such characters are escaped with the following rules: +// +// - "~" is escaped as "~0" +// - "/" is escaped as "~1" func Escape(token string) string { - step1 := strings.ReplaceAll(token, decRefTok0, encRefTok0) - step2 := strings.ReplaceAll(step1, decRefTok1, encRefTok1) - return step2 + return decRefTokReplacer.Replace(token) } diff --git a/api/vendor/github.com/go-openapi/jsonreference/.cliff.toml b/api/vendor/github.com/go-openapi/jsonreference/.cliff.toml new file mode 100644 index 000000000000..702629f5dc30 --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonreference/.cliff.toml @@ -0,0 +1,181 @@ +# git-cliff ~ configuration file +# https://git-cliff.org/docs/configuration + +[changelog] +header = """ +""" + +footer = """ + +----- + +**[{{ remote.github.repo }}]({{ self::remote_url() }}) license terms** + +[![License][license-badge]][license-url] + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: {{ self::remote_url() }}/?tab=Apache-2.0-1-ov-file#readme + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" + +body = """ +{%- if version %} +## [{{ version | trim_start_matches(pat="v") }}]({{ self::remote_url() }}/tree/{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }} +{%- else %} +## [unreleased] +{%- endif %} +{%- if message %} + {%- raw %}\n{% endraw %} +{{ message }} + {%- raw %}\n{% endraw %} +{%- endif %} +{%- if version %} + {%- if previous.version %} + +**Full Changelog**: <{{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}> + {%- endif %} +{%- else %} + {%- raw %}\n{% endraw %} +{%- endif %} + +{%- if statistics %}{% if statistics.commit_count %} + {%- raw %}\n{% endraw %} +{{ statistics.commit_count }} commits in this release. + {%- raw %}\n{% endraw %} +{%- endif %}{% endif %} +----- + +{%- for group, commits in commits | group_by(attribute="group") %} + {%- raw %}\n{% endraw %} +### {{ group | upper_first }} + {%- raw %}\n{% endraw %} + {%- for commit in commits %} + {%- if commit.remote.pr_title %} + {%- set commit_message = commit.remote.pr_title %} + {%- else %} + {%- set commit_message = commit.message %} + {%- endif %} +* {{ commit_message | split(pat="\n") | first | trim }} + {%- if commit.remote.username %} +{%- raw %} {% endraw %}by [@{{ commit.remote.username }}](https://github.com/{{ commit.remote.username }}) + {%- endif %} + {%- if commit.remote.pr_number %} +{%- raw %} {% endraw %}in [#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) + {%- endif %} +{%- raw %} {% endraw %}[...]({{ self::remote_url() }}/commit/{{ commit.id }}) + {%- endfor %} +{%- endfor %} + +{%- if github %} +{%- raw %}\n{% endraw -%} + {%- set all_contributors = github.contributors | length %} + {%- if github.contributors | filter(attribute="username", value="dependabot[bot]") | length < all_contributors %} +----- + +### People who contributed to this release + {% endif %} + {%- for contributor in github.contributors | filter(attribute="username") | sort(attribute="username") %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* [@{{ contributor.username }}](https://github.com/{{ contributor.username }}) + {%- endif %} + {%- endfor %} + + {% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} +----- + {%- raw %}\n{% endraw %} + +### New Contributors + {%- endif %} + + {%- for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* @{{ contributor.username }} made their first contribution + {%- if contributor.pr_number %} + in [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ + {%- endif %} + {%- endif %} + {%- endfor %} +{%- endif %} + +{%- raw %}\n{% endraw %} + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" +# Remove leading and trailing whitespaces from the changelog's body. +trim = true +# Render body even when there are no releases to process. +render_always = true +# An array of regex based postprocessors to modify the changelog. +postprocessors = [ + # Replace the placeholder with a URL. + #{ pattern = '', replace = "https://github.com/orhun/git-cliff" }, +] +# output file path +# output = "test.md" + +[git] +# Parse commits according to the conventional commits specification. +# See https://www.conventionalcommits.org +conventional_commits = false +# Exclude commits that do not match the conventional commits specification. +filter_unconventional = false +# Require all commits to be conventional. +# Takes precedence over filter_unconventional. +require_conventional = false +# Split commits on newlines, treating each line as an individual commit. +split_commits = false +# An array of regex based parsers to modify commit messages prior to further processing. +commit_preprocessors = [ + # Replace issue numbers with link templates to be updated in `changelog.postprocessors`. + #{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, + # Check spelling of the commit message using https://github.com/crate-ci/typos. + # If the spelling is incorrect, it will be fixed automatically. + #{ pattern = '.*', replace_command = 'typos --write-changes -' } +] +# Prevent commits that are breaking from being excluded by commit parsers. +protect_breaking_commits = false +# An array of regex based parsers for extracting data from the commit message. +# Assigns commits to groups. +# Optionally sets the commit's scope and can decide to exclude commits from further processing. +commit_parsers = [ + { message = "^[Cc]hore\\([Rr]elease\\): prepare for", skip = true }, + { message = "(^[Mm]erge)|([Mm]erge conflict)", skip = true }, + { field = "author.name", pattern = "dependabot*", group = "Updates" }, + { message = "([Ss]ecurity)|([Vv]uln)", group = "Security" }, + { body = "(.*[Ss]ecurity)|([Vv]uln)", group = "Security" }, + { message = "([Cc]hore\\(lint\\))|(style)|(lint)|(codeql)|(golangci)", group = "Code quality" }, + { message = "(^[Dd]oc)|((?i)readme)|(badge)|(typo)|(documentation)", group = "Documentation" }, + { message = "(^[Ff]eat)|(^[Ee]nhancement)", group = "Implemented enhancements" }, + { message = "(^ci)|(\\(ci\\))|(fixup\\s+ci)|(fix\\s+ci)|(license)|(example)", group = "Miscellaneous tasks" }, + { message = "^test", group = "Testing" }, + { message = "(^fix)|(panic)", group = "Fixed bugs" }, + { message = "(^refact)|(rework)", group = "Refactor" }, + { message = "(^[Pp]erf)|(performance)", group = "Performance" }, + { message = "(^[Cc]hore)", group = "Miscellaneous tasks" }, + { message = "^[Rr]evert", group = "Reverted changes" }, + { message = "(upgrade.*?go)|(go\\s+version)", group = "Updates" }, + { message = ".*", group = "Other" }, +] +# Exclude commits that are not matched by any commit parser. +filter_commits = false +# An array of link parsers for extracting external references, and turning them into URLs, using regex. +link_parsers = [] +# Include only the tags that belong to the current branch. +use_branch_tags = false +# Order releases topologically instead of chronologically. +topo_order = false +# Order releases topologically instead of chronologically. +topo_order_commits = true +# Order of commits in each group/release within the changelog. +# Allowed values: newest, oldest +sort_commits = "newest" +# Process submodules commits +recurse_submodules = false + +#[remote.github] +#owner = "go-openapi" diff --git a/api/vendor/github.com/go-openapi/jsonreference/.editorconfig b/api/vendor/github.com/go-openapi/jsonreference/.editorconfig new file mode 100644 index 000000000000..3152da69a5d7 --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonreference/.editorconfig @@ -0,0 +1,26 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +# Set default charset +[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] +charset = utf-8 + +# Tab indentation (no size specified) +[*.go] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false + +# Matches the exact files either package.json or .travis.yml +[{package.json,.travis.yml}] +indent_style = space +indent_size = 2 diff --git a/api/vendor/github.com/go-openapi/jsonreference/.golangci.yml b/api/vendor/github.com/go-openapi/jsonreference/.golangci.yml index 22f8d21cca19..fdae591bce71 100644 --- a/api/vendor/github.com/go-openapi/jsonreference/.golangci.yml +++ b/api/vendor/github.com/go-openapi/jsonreference/.golangci.yml @@ -1,61 +1,66 @@ -linters-settings: - govet: - check-shadowing: true - golint: - min-confidence: 0 - gocyclo: - min-complexity: 45 - maligned: - suggest-new: true - dupl: - threshold: 200 - goconst: - min-len: 2 - min-occurrences: 3 - +version: "2" linters: - enable-all: true + default: all disable: - - maligned - - unparam - - lll - - gochecknoinits - - gochecknoglobals + - depguard - funlen - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage + - exhaustruct - nlreturn - - gomnd - - exhaustivestruct - - goerr113 - - errorlint - - nestif - - godot - - gofumpt + - nonamedreturns + - noinlineerr - paralleltest + - recvcheck + - testpackage - tparallel - - thelper - - ifshort - - exhaustruct - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - - deadcode - - interfacer - - scopelint - - varcheck - - structcheck - - golint - - nosnakecase + - whitespace + - wrapcheck + - wsl + - wsl_v5 + settings: + dupl: + threshold: 200 + goconst: + min-len: 2 + min-occurrences: 3 + cyclop: + max-complexity: 20 + gocyclo: + min-complexity: 20 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + - gofumpt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ +issues: + # Maximum issues count per one linter. + # Set to 0 to disable. + # Default: 50 + max-issues-per-linter: 0 + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 0 diff --git a/api/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md b/api/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md new file mode 100644 index 000000000000..9907d5d21243 --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md @@ -0,0 +1,21 @@ +# Contributors + +- Repository: ['go-openapi/jsonreference'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 9 | 68 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 31 | https://github.com/go-openapi/jsonreference/commits?author=fredbi | +| @casualjim | 25 | https://github.com/go-openapi/jsonreference/commits?author=casualjim | +| @youyuanwu | 5 | https://github.com/go-openapi/jsonreference/commits?author=youyuanwu | +| @olivierlemasle | 2 | https://github.com/go-openapi/jsonreference/commits?author=olivierlemasle | +| @apelisse | 1 | https://github.com/go-openapi/jsonreference/commits?author=apelisse | +| @gbjk | 1 | https://github.com/go-openapi/jsonreference/commits?author=gbjk | +| @honza | 1 | https://github.com/go-openapi/jsonreference/commits?author=honza | +| @Neo2308 | 1 | https://github.com/go-openapi/jsonreference/commits?author=Neo2308 | +| @erraggy | 1 | https://github.com/go-openapi/jsonreference/commits?author=erraggy | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/api/vendor/github.com/go-openapi/jsonreference/NOTICE b/api/vendor/github.com/go-openapi/jsonreference/NOTICE new file mode 100644 index 000000000000..f3b51939a95b --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonreference/NOTICE @@ -0,0 +1,39 @@ +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonpointer, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0. + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original software was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). + +github.com/sigh-399/jsonpointer +=========================== + +// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// SPDX-License-Identifier: Apache-2.0 + +Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/api/vendor/github.com/go-openapi/jsonreference/README.md b/api/vendor/github.com/go-openapi/jsonreference/README.md index c7fc2049c1d8..d479dbdc7318 100644 --- a/api/vendor/github.com/go-openapi/jsonreference/README.md +++ b/api/vendor/github.com/go-openapi/jsonreference/README.md @@ -1,19 +1,99 @@ -# gojsonreference [![Build Status](https://github.com/go-openapi/jsonreference/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/jsonreference/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonreference) +# jsonreference -[![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/jsonreference/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/jsonreference.svg)](https://pkg.go.dev/github.com/go-openapi/jsonreference) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/jsonreference)](https://goreportcard.com/report/github.com/go-openapi/jsonreference) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Slack Channel][slack-logo]![slack-badge]][slack-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -An implementation of JSON Reference - Go language +--- + +An implementation of JSON Reference for golang. ## Status -Feature complete. Stable API + +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/jsonreference +``` ## Dependencies + * https://github.com/go-openapi/jsonpointer +## Basic usage + +## Change log + +See + ## References * http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 * http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +See the license [NOTICE](./NOTICE), which recalls the licensing terms of all the pieces of software +on top of which it has been built. + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/jsonreference/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/jsonreference/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/jsonreference/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/jsonreference +[vuln-scan-badge]: https://github.com/go-openapi/jsonreference/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/jsonreference/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/jsonreference/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/jsonreference/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonreference.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fjsonreference +[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonreference.svg +[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonreference + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonreference +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonreference +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonreference +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonreference + +[doc-badge]: https://img.shields.io/badge/doc-site-blue?link=https%3A%2F%2Fgoswagger.io%2Fgo-openapi%2F +[doc-url]: https://goswagger.io/go-openapi +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/jsonreference +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/jsonreference +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/jsonreference/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/jsonreference +[goversion-url]: https://github.com/go-openapi/jsonreference/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/jsonreference +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/jsonreference/latest diff --git a/api/vendor/github.com/go-openapi/jsonreference/SECURITY.md b/api/vendor/github.com/go-openapi/jsonreference/SECURITY.md new file mode 100644 index 000000000000..2a7b6f0910d9 --- /dev/null +++ b/api/vendor/github.com/go-openapi/jsonreference/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.22.x | :white_check_mark: | + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +please report it privately to the maintainers. + +Please follow the instructions provided by github to +[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). + +TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". diff --git a/api/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go b/api/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go index f0610cf1e577..a08b47320e7d 100644 --- a/api/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go +++ b/api/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package internal import ( @@ -11,9 +14,11 @@ const ( defaultHTTPSPort = ":443" ) -// Regular expressions used by the normalizations -var rxPort = regexp.MustCompile(`(:\d+)/?$`) -var rxDupSlashes = regexp.MustCompile(`/{2,}`) +// Regular expressions used by the normalizations. +var ( + rxPort = regexp.MustCompile(`(:\d+)/?$`) + rxDupSlashes = regexp.MustCompile(`/{2,}`) +) // NormalizeURL will normalize the specified URL // This was added to replace a previous call to the no longer maintained purell library: diff --git a/api/vendor/github.com/go-openapi/jsonreference/reference.go b/api/vendor/github.com/go-openapi/jsonreference/reference.go index cfdef03e5d94..6e3ae4995154 100644 --- a/api/vendor/github.com/go-openapi/jsonreference/reference.go +++ b/api/vendor/github.com/go-openapi/jsonreference/reference.go @@ -1,27 +1,5 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonreference -// repository-desc An implementation of JSON Reference - Go language -// -// description Main and unique file. -// -// created 26-02-2013 +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package jsonreference @@ -38,50 +16,50 @@ const ( fragmentRune = `#` ) -// New creates a new reference for the given string -func New(jsonReferenceString string) (Ref, error) { +var ErrChildURL = errors.New("child url is nil") + +// Ref represents a json reference object. +type Ref struct { + referenceURL *url.URL + referencePointer jsonpointer.Pointer + + HasFullURL bool + HasURLPathOnly bool + HasFragmentOnly bool + HasFileScheme bool + HasFullFilePath bool +} +// New creates a new reference for the given string. +func New(jsonReferenceString string) (Ref, error) { var r Ref err := r.parse(jsonReferenceString) return r, err - } // MustCreateRef parses the ref string and panics when it's invalid. -// Use the New method for a version that returns an error +// Use the New method for a version that returns an error. func MustCreateRef(ref string) Ref { r, err := New(ref) if err != nil { panic(err) } - return r -} -// Ref represents a json reference object -type Ref struct { - referenceURL *url.URL - referencePointer jsonpointer.Pointer - - HasFullURL bool - HasURLPathOnly bool - HasFragmentOnly bool - HasFileScheme bool - HasFullFilePath bool + return r } -// GetURL gets the URL for this reference +// GetURL gets the URL for this reference. func (r *Ref) GetURL() *url.URL { return r.referenceURL } -// GetPointer gets the json pointer for this reference +// GetPointer gets the json pointer for this reference. func (r *Ref) GetPointer() *jsonpointer.Pointer { return &r.referencePointer } -// String returns the best version of the url for this reference +// String returns the best version of the url for this reference. func (r *Ref) String() string { - if r.referenceURL != nil { return r.referenceURL.String() } @@ -93,7 +71,7 @@ func (r *Ref) String() string { return r.referencePointer.String() } -// IsRoot returns true if this reference is a root document +// IsRoot returns true if this reference is a root document. func (r *Ref) IsRoot() bool { return r.referenceURL != nil && !r.IsCanonical() && @@ -101,14 +79,32 @@ func (r *Ref) IsRoot() bool { r.referenceURL.Fragment == "" } -// IsCanonical returns true when this pointer starts with http(s):// or file:// +// IsCanonical returns true when this pointer starts with http(s):// or file://. func (r *Ref) IsCanonical() bool { return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL) } -// "Constructor", parses the given string JSON reference -func (r *Ref) parse(jsonReferenceString string) error { +// Inherits creates a new reference from a parent and a child +// If the child cannot inherit from the parent, an error is returned. +func (r *Ref) Inherits(child Ref) (*Ref, error) { + childURL := child.GetURL() + parentURL := r.GetURL() + if childURL == nil { + return nil, ErrChildURL + } + if parentURL == nil { + return &child, nil + } + + ref, err := New(parentURL.ResolveReference(childURL).String()) + if err != nil { + return nil, err + } + return &ref, nil +} +// "Constructor", parses the given string JSON reference. +func (r *Ref) parse(jsonReferenceString string) error { parsed, err := url.Parse(jsonReferenceString) if err != nil { return err @@ -137,22 +133,3 @@ func (r *Ref) parse(jsonReferenceString string) error { return nil } - -// Inherits creates a new reference from a parent and a child -// If the child cannot inherit from the parent, an error is returned -func (r *Ref) Inherits(child Ref) (*Ref, error) { - childURL := child.GetURL() - parentURL := r.GetURL() - if childURL == nil { - return nil, errors.New("child url is nil") - } - if parentURL == nil { - return &child, nil - } - - ref, err := New(parentURL.ResolveReference(childURL).String()) - if err != nil { - return nil, err - } - return &ref, nil -} diff --git a/api/vendor/github.com/go-openapi/swag/.codecov.yml b/api/vendor/github.com/go-openapi/swag/.codecov.yml new file mode 100644 index 000000000000..3354f44b28e9 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/.codecov.yml @@ -0,0 +1,4 @@ +ignore: + - jsonutils/fixtures_test + - jsonutils/adapters/ifaces/mocks + - jsonutils/adapters/testintegration/benchmarks diff --git a/api/vendor/github.com/go-openapi/swag/.golangci.yml b/api/vendor/github.com/go-openapi/swag/.golangci.yml index d2fafb8a2bb0..126264a6b898 100644 --- a/api/vendor/github.com/go-openapi/swag/.golangci.yml +++ b/api/vendor/github.com/go-openapi/swag/.golangci.yml @@ -1,56 +1,78 @@ -linters-settings: - gocyclo: - min-complexity: 45 - dupl: - threshold: 200 - goconst: - min-len: 2 - min-occurrences: 3 - +version: "2" linters: - enable-all: true + default: all disable: - - recvcheck - - unparam - - lll - - gochecknoinits - - gochecknoglobals + - cyclop + - depguard + - errchkjson + - errorlint + - exhaustruct + - forcetypeassert - funlen - - godox + - gochecknoglobals + - gochecknoinits - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage - - nlreturn - - errorlint - - nestif - godot - - gofumpt + - godox + - gomoddirectives + - gosmopolitan + - inamedparam + - intrange + - ireturn + - lll + - musttag + - modernize + - nestif + - nlreturn + - nonamedreturns + - noinlineerr - paralleltest - - tparallel + - recvcheck + - testpackage - thelper - - exhaustruct + - tagliatelle + - tparallel + - unparam - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - #- deadcode - #- interfacer - #- scopelint - #- varcheck - #- structcheck - #- golint - #- nosnakecase - #- maligned - #- goerr113 - #- ifshort - #- gomnd - #- exhaustivestruct + - whitespace + - wrapcheck + - wsl + - wsl_v5 + settings: + dupl: + threshold: 200 + goconst: + min-len: 2 + min-occurrences: 3 + gocyclo: + min-complexity: 45 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ +issues: + # Maximum issues count per one linter. + # Set to 0 to disable. + # Default: 50 + max-issues-per-linter: 0 + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 0 diff --git a/api/vendor/github.com/go-openapi/swag/.mockery.yml b/api/vendor/github.com/go-openapi/swag/.mockery.yml new file mode 100644 index 000000000000..8557cb58d331 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/.mockery.yml @@ -0,0 +1,30 @@ +all: false +dir: '{{.InterfaceDir}}' +filename: mocks_test.go +force-file-write: true +formatter: goimports +include-auto-generated: false +log-level: info +structname: '{{.Mock}}{{.InterfaceName}}' +pkgname: '{{.SrcPackageName}}' +recursive: false +require-template-schema-exists: true +template: matryer +template-schema: '{{.Template}}.schema.json' +packages: + github.com/go-openapi/swag/jsonutils/adapters/ifaces: + config: + dir: jsonutils/adapters/ifaces/mocks + filename: mocks.go + pkgname: 'mocks' + force-file-write: true + all: true + github.com/go-openapi/swag/jsonutils/adapters/testintegration: + config: + inpackage: true + dir: jsonutils/adapters/testintegration + force-file-write: true + all: true + interfaces: + EJMarshaler: + EJUnmarshaler: diff --git a/api/vendor/github.com/go-openapi/swag/README.md b/api/vendor/github.com/go-openapi/swag/README.md index a7292229980f..371fd55fdc36 100644 --- a/api/vendor/github.com/go-openapi/swag/README.md +++ b/api/vendor/github.com/go-openapi/swag/README.md @@ -1,23 +1,239 @@ # Swag [![Build Status](https://github.com/go-openapi/swag/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/swag/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) [![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/swag/master/LICENSE) +[![license](https://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) [![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/swag.svg)](https://pkg.go.dev/github.com/go-openapi/swag) [![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/swag)](https://goreportcard.com/report/github.com/go-openapi/swag) -Contains a bunch of helper functions for go-openapi and go-swagger projects. +Package `swag` contains a bunch of helper functions for go-openapi and go-swagger projects. You may also use it standalone for your projects. -* convert between value and pointers for builtin types -* convert from string to builtin types (wraps strconv) -* fast json concatenation -* search in path -* load from file or http -* name mangling +> **NOTE** +> `swag` is one of the foundational building blocks of the go-openapi initiative. +> Most repositories in `github.com/go-openapi/...` depend on it in some way. +> And so does our CLI tool `github.com/go-swagger/go-swagger`, +> as well as the code generated by this tool. +* [Contents](#contents) +* [Dependencies](#dependencies) +* [Release Notes](#release-notes) +* [Licensing](#licensing) +* [Note to contributors](#note-to-contributors) +* [TODOs, suggestions and plans](#todos-suggestions-and-plans) -This repo has only few dependencies outside of the standard library: +## Contents -* YAML utilities depend on `gopkg.in/yaml.v3` -* `github.com/mailru/easyjson v0.7.7` +`go-openapi/swag` exposes a collection of relatively independent modules. + +Moving forward, no additional feature will be added to the `swag` API directly at the root package level, +which remains there for backward-compatibility purposes. All exported top-level features are now deprecated. + +Child modules will continue to evolve and some new ones may be added in the future. + +| Module | Content | Main features | +|---------------|---------|---------------| +| `cmdutils` | utilities to work with CLIs || +| `conv` | type conversion utilities | convert between values and pointers for any types
convert from string to builtin types (wraps `strconv`)
require `./typeutils` (test dependency)
| +| `fileutils` | file utilities | | +| `jsonname` | JSON utilities | infer JSON names from `go` properties
| +| `jsonutils` | JSON utilities | fast json concatenation
read and write JSON from and to dynamic `go` data structures
~require `github.com/mailru/easyjson`~
| +| `loading` | file loading | load from file or http
require `./yamlutils`
| +| `mangling` | safe name generation | name mangling for `go`
| +| `netutils` | networking utilities | host, port from address
| +| `stringutils` | `string` utilities | search in slice (with case-insensitive)
split/join query parameters as arrays
| +| `typeutils` | `go` types utilities | check the zero value for any type
safe check for a nil value
| +| `yamlutils` | YAML utilities | converting YAML to JSON
loading YAML into a dynamic YAML document
maintaining the original order of keys in YAML objects
require `./jsonutils`
~require `github.com/mailru/easyjson`~
require `go.yaml.in/yaml/v3`
| + +--- + +## Dependencies + +The root module `github.com/go-openapi/swag` at the repo level maintains a few +dependencies outside of the standard library. + +* YAML utilities depend on `go.yaml.in/yaml/v3` +* JSON utilities depend on their registered adapter module: + * by default, only the standard library is used + * `github.com/mailru/easyjson` is now only a dependency for module + `github.com/go-openapi/swag/jsonutils/adapters/easyjson/json`, + for users willing to import that module. + * integration tests and benchmarks use all the dependencies are published as their own module +* other dependencies are test dependencies drawn from `github.com/stretchr/testify` + +## Release notes + +### v0.25.4 + +** mangling** + +Bug fix + +* [x] mangler may panic with pluralized overlapping initialisms + +Tests + +* [x] introduced fuzz tests + +### v0.25.3 + +** mangling** + +Bug fix + +* [x] mangler may panic with pluralized initialisms + +### v0.25.2 + +Minor changes due to internal maintenance that don't affect the behavior of the library. + +* [x] removed indirect test dependencies by switching all tests to `go-openapi/testify`, + a fork of `stretch/testify` with zero-dependencies. +* [x] improvements to CI to catch test reports. +* [x] modernized licensing annotations in source code, using the more compact SPDX annotations + rather than the full license terms. +* [x] simplified a bit JSON & YAML testing by using newly available assertions +* started the journey to an OpenSSF score card badge: + * [x] explicited permissions in CI workflows + * [x] published security policy + * pinned dependencies to github actions + * introduced fuzzing in tests + +### v0.25.1 + +* fixes a data race that could occur when using the standard library implementation of a JSON ordered map + +### v0.25.0 + +**New with this release**: + +* requires `go1.24`, as iterators are being introduced +* removes the dependency to `mailru/easyjson` by default (#68) + * functionality remains the same, but performance may somewhat degrade for applications + that relied on `easyjson` + * users of the JSON or YAML utilities who want to use `easyjson` as their preferred JSON serializer library + will be able to do so by registering this the corresponding JSON adapter at runtime. See below. + * ordered keys in JSON and YAML objects: this feature used to rely solely on `easyjson`. + With this release, an implementation relying on the standard `encoding/json` is provided. + * an independent [benchmark](./jsonutils/adapters/testintegration/benchmarks/README.md) to compare the different adapters +* improves the "float is integer" check (`conv.IsFloat64AJSONInteger`) (#59) +* removes the _direct_ dependency to `gopkg.in/yaml.v3` (indirect dependency is still incurred through `stretchr/testify`) (#127) +* exposed `conv.IsNil()` (previously kept private): a safe nil check (accounting for the "non-nil interface with nil value" nonsensical go trick) + +**What coming next?** + +Moving forward, we want to : +* provide an implementation of the JSON adapter based on `encoding/json/v2`, for `go1.25` builds. +* provide similar implementations for `goccy/go-json` and `jsoniterator/go`, and perhaps some other + similar libraries may be interesting too. + + +**How to explicitly register a dependency at runtime**? + +The following would maintain how JSON utilities proposed by `swag` used work, up to `v0.24.1`. + + ```go + import ( + "github.com/go-openapi/swag/jsonutils/adapters" + easyjson "github.com/go-openapi/swag/jsonutils/adapters/easyjson/json" + ) + + func init() { + easyjson.Register(adapters.Registry) + } + ``` + +Subsequent calls to `jsonutils.ReadJSON()` or `jsonutils.WriteJSON()` will switch to `easyjson` +whenever the passed data structures implement the `easyjson.Unmarshaler` or `easyjson.Marshaler` respectively, +or fallback to the standard library. + +For more details, you may also look at our +[integration tests](jsonutils/adapters/testintegration/integration_suite_test.go#29). + +### v0.24.0 + +With this release, we have largely modernized the API of `swag`: + +* The traditional `swag` API is still supported: code that imports `swag` will still + compile and work the same. +* A deprecation notice is published to encourage consumers of this library to adopt + the newer API +* **Deprecation notice** + * configuration through global variables is now deprecated, in favor of options passed as parameters + * all helper functions are moved to more specialized packages, which are exposed as + go modules. Importing such a module would reduce the footprint of dependencies. + * _all_ functions, variables, constants exposed by the deprecated API have now moved, so + that consumers of the new API no longer need to import github.com/go-openapi/swag, but + should import the desired sub-module(s). + +**New with this release**: + +* [x] type converters and pointer to value helpers now support generic types +* [x] name mangling now support pluralized initialisms (issue #46) + Strings like "contact IDs" are now recognized as such a plural form and mangled as a linter would expect. +* [x] performance: small improvements to reduce the overhead of convert/format wrappers (see issues #110, or PR #108) +* [x] performance: name mangling utilities run ~ 10% faster (PR #115) + +--- + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +## Note to contributors + +A mono-repo structure comes with some unavoidable extra pains... + +* Testing + +> The usual `go test ./...` command, run from the root of this repo won't work any longer to test all submodules. +> +> Each module constitutes an independant unit of test. So you have to run `go test` inside each module. +> Or you may take a look at how this is achieved by CI +> [here] https://github.com/go-openapi/swag/blob/master/.github/workflows/go-test.yml). +> +> There are also some alternative tricks using `go work`, for local development, if you feel comfortable with +> go workspaces. Perhaps some day, we'll have a `go work test` to run all tests without any hack. + +* Releasing + +> Each module follows its own independant module versioning. +> +> So you have tags like `mangling/v0.24.0`, `fileutils/v0.24.0` etc that are used by `go mod` and `go get` +> to refer to the tagged version of each module specifically. +> +> This means we may release patches etc to each module independently. +> +> We'd like to adopt the rule that modules in this repo would only differ by a patch version +> (e.g. `v0.24.5` vs `v0.24.3`), and we'll level all modules whenever a minor version is introduced. +> +> A script in `./hack` is provided to tag all modules with the same version in one go. + +* Continuous integration + +> At this moment, all tests in all modules are systematically run over the full test matrix (3 platform x 2 go releases). +> This generates quite a lot of jobs. +> +> We ought to reduce the number of jobs required to test a PR focused on only a few modules. + +## Todos, suggestions and plans + +All kinds of contributions are welcome. + +A few ideas: + +* [x] Complete the split of dependencies to isolate easyjson from the rest +* [x] Improve CI to reduce needed tests +* [x] Replace dependency to `gopkg.in/yaml.v3` (`yamlutil`) +* [ ] Improve mangling utilities (improve readability, support for capitalized words, + better word substitution for non-letter symbols...) +* [ ] Move back to this common shared pot a few of the technical features introduced by go-swagger independently + (e.g. mangle go package names, search package with go modules support, ...) +* [ ] Apply a similar mono-repo approach to go-openapi/strfmt which suffer from similar woes: bloated API, + imposed dependency to some database driver. +* [ ] Adapt `go-swagger` (incl. generated code) to the new `swag` API. +* [ ] Factorize some tests, as there is a lot of redundant testing code in `jsonutils` +* [ ] Benchmark & profiling: publish independently the tool built to analyze and chart benchmarks (e.g. similar to `benchvisual`) +* [ ] more thorough testing for nil / null case +* [ ] ci pipeline to manage releases +* [ ] cleaner mockery generation (doesn't work out of the box for all sub-modules) diff --git a/api/vendor/github.com/go-openapi/swag/SECURITY.md b/api/vendor/github.com/go-openapi/swag/SECURITY.md new file mode 100644 index 000000000000..72296a83135d --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.25.x | :white_check_mark: | + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +please report it privately to the maintainers. + +Please follow the instructions provided by github to +[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). + +TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". diff --git a/api/vendor/github.com/go-openapi/swag/cmdutils/LICENSE b/api/vendor/github.com/go-openapi/swag/cmdutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/cmdutils/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/api/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go b/api/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go new file mode 100644 index 000000000000..6c7bbb26f03d --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package cmdutils + +// CommandLineOptionsGroup represents a group of user-defined command line options. +// +// This is for instance used to configure command line arguments in API servers generated by go-swagger. +type CommandLineOptionsGroup struct { + ShortDescription string + LongDescription string + Options any +} diff --git a/api/vendor/github.com/go-openapi/swag/cmdutils/doc.go b/api/vendor/github.com/go-openapi/swag/cmdutils/doc.go new file mode 100644 index 000000000000..31f2c37538a0 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/cmdutils/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package cmdutils brings helpers for CLIs produced by go-openapi +package cmdutils diff --git a/api/vendor/github.com/go-openapi/swag/cmdutils_iface.go b/api/vendor/github.com/go-openapi/swag/cmdutils_iface.go new file mode 100644 index 000000000000..bd0c1fc12802 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/cmdutils_iface.go @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/cmdutils" + +// CommandLineOptionsGroup represents a group of user-defined command line options. +// +// Deprecated: use [cmdutils.CommandLineOptionsGroup] instead. +type CommandLineOptionsGroup = cmdutils.CommandLineOptionsGroup diff --git a/api/vendor/github.com/go-openapi/swag/conv/LICENSE b/api/vendor/github.com/go-openapi/swag/conv/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/conv/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/api/vendor/github.com/go-openapi/swag/conv/convert.go b/api/vendor/github.com/go-openapi/swag/conv/convert.go new file mode 100644 index 000000000000..f205c3913457 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/conv/convert.go @@ -0,0 +1,161 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +import ( + "math" + "strconv" + "strings" +) + +// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER +const ( + maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 + minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 + epsilon float64 = 1e-9 +) + +// IsFloat64AJSONInteger allows for integers [-2^53, 2^53-1] inclusive. +func IsFloat64AJSONInteger(f float64) bool { + if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { + return false + } + rounded := math.Round(f) + if f == rounded { + return true + } + if rounded == 0 { // f = 0.0 exited above + return false + } + + diff := math.Abs(f - rounded) + if diff == 0 { + return true + } + + // relative error Abs{f - Round(f)) / Round(f)} < ε ; Round(f) + return diff < epsilon*math.Abs(rounded) +} + +// ConvertFloat turns a string into a float numerical value. +func ConvertFloat[T Float](str string) (T, error) { + var v T + f, err := strconv.ParseFloat(str, bitsize(v)) + if err != nil { + return 0, err + } + + return T(f), nil +} + +// ConvertInteger turns a string into a signed integer. +func ConvertInteger[T Signed](str string) (T, error) { + var v T + f, err := strconv.ParseInt(str, 10, bitsize(v)) + if err != nil { + return 0, err + } + + return T(f), nil +} + +// ConvertUinteger turns a string into an unsigned integer. +func ConvertUinteger[T Unsigned](str string) (T, error) { + var v T + f, err := strconv.ParseUint(str, 10, bitsize(v)) + if err != nil { + return 0, err + } + + return T(f), nil +} + +// ConvertBool turns a string into a boolean. +// +// It supports a few more "true" strings than [strconv.ParseBool]: +// +// - it is not case sensitive ("trUe" or "FalsE" work) +// - "ok", "yes", "y", "on", "selected", "checked", "enabled" are all true +// - everything that is not true is false: there is never an actual error returned +func ConvertBool(str string) (bool, error) { + switch strings.ToLower(str) { + case "true", + "1", + "yes", + "ok", + "y", + "on", + "selected", + "checked", + "t", + "enabled": + return true, nil + default: + return false, nil + } +} + +// ConvertFloat32 turns a string into a float32. +func ConvertFloat32(str string) (float32, error) { return ConvertFloat[float32](str) } + +// ConvertFloat64 turns a string into a float64 +func ConvertFloat64(str string) (float64, error) { return ConvertFloat[float64](str) } + +// ConvertInt8 turns a string into an int8 +func ConvertInt8(str string) (int8, error) { return ConvertInteger[int8](str) } + +// ConvertInt16 turns a string into an int16 +func ConvertInt16(str string) (int16, error) { + i, err := strconv.ParseInt(str, 10, 16) + if err != nil { + return 0, err + } + return int16(i), nil +} + +// ConvertInt32 turns a string into an int32 +func ConvertInt32(str string) (int32, error) { + i, err := strconv.ParseInt(str, 10, 32) + if err != nil { + return 0, err + } + return int32(i), nil +} + +// ConvertInt64 turns a string into an int64 +func ConvertInt64(str string) (int64, error) { + return strconv.ParseInt(str, 10, 64) +} + +// ConvertUint8 turns a string into an uint8 +func ConvertUint8(str string) (uint8, error) { + i, err := strconv.ParseUint(str, 10, 8) + if err != nil { + return 0, err + } + return uint8(i), nil +} + +// ConvertUint16 turns a string into an uint16 +func ConvertUint16(str string) (uint16, error) { + i, err := strconv.ParseUint(str, 10, 16) + if err != nil { + return 0, err + } + return uint16(i), nil +} + +// ConvertUint32 turns a string into an uint32 +func ConvertUint32(str string) (uint32, error) { + i, err := strconv.ParseUint(str, 10, 32) + if err != nil { + return 0, err + } + return uint32(i), nil +} + +// ConvertUint64 turns a string into an uint64 +func ConvertUint64(str string) (uint64, error) { + return strconv.ParseUint(str, 10, 64) +} diff --git a/api/vendor/github.com/go-openapi/swag/conv/convert_types.go b/api/vendor/github.com/go-openapi/swag/conv/convert_types.go new file mode 100644 index 000000000000..cf4c6495ebc9 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/conv/convert_types.go @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +// Unlicensed credits (idea, concept) +// +// The idea to convert values to pointers and the other way around, was inspired, eons ago, by the aws go sdk. +// +// Nowadays, all sensible API sdk's expose a similar functionality. + +// Pointer returns a pointer to the value passed in. +func Pointer[T any](v T) *T { + return &v +} + +// Value returns a shallow copy of the value of the pointer passed in. +// +// If the pointer is nil, the returned value is the zero value. +func Value[T any](v *T) T { + if v != nil { + return *v + } + + var zero T + return zero +} + +// PointerSlice converts a slice of values into a slice of pointers. +func PointerSlice[T any](src []T) []*T { + dst := make([]*T, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// ValueSlice converts a slice of pointers into a slice of values. +// +// nil elements are zero values. +func ValueSlice[T any](src []*T) []T { + dst := make([]T, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// PointerMap converts a map of values into a map of pointers. +func PointerMap[K comparable, T any](src map[K]T) map[K]*T { + dst := make(map[K]*T) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// ValueMap converts a map of pointers into a map of values. +// +// nil elements are skipped. +func ValueMap[K comparable, T any](src map[K]*T) map[K]T { + dst := make(map[K]T) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} diff --git a/api/vendor/github.com/go-openapi/swag/conv/doc.go b/api/vendor/github.com/go-openapi/swag/conv/doc.go new file mode 100644 index 000000000000..1bd6ead6e2d1 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/conv/doc.go @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package conv exposes utilities to convert types. +// +// The Convert and Format families of functions are essentially a shorthand to [strconv] functions, +// using the decimal representation of numbers. +// +// Features: +// +// - from string representation to value ("Convert*") and reciprocally ("Format*") +// - from pointer to value ([Value]) and reciprocally ([Pointer]) +// - from slice of values to slice of pointers ([PointerSlice]) and reciprocally ([ValueSlice]) +// - from map of values to map of pointers ([PointerMap]) and reciprocally ([ValueMap]) +package conv diff --git a/api/vendor/github.com/go-openapi/swag/conv/format.go b/api/vendor/github.com/go-openapi/swag/conv/format.go new file mode 100644 index 000000000000..5b87b8e146bb --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/conv/format.go @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +import ( + "strconv" +) + +// FormatInteger turns an integer type into a string. +func FormatInteger[T Signed](value T) string { + return strconv.FormatInt(int64(value), 10) +} + +// FormatUinteger turns an unsigned integer type into a string. +func FormatUinteger[T Unsigned](value T) string { + return strconv.FormatUint(uint64(value), 10) +} + +// FormatFloat turns a floating point numerical value into a string. +func FormatFloat[T Float](value T) string { + return strconv.FormatFloat(float64(value), 'f', -1, bitsize(value)) +} + +// FormatBool turns a boolean into a string. +func FormatBool(value bool) string { + return strconv.FormatBool(value) +} diff --git a/api/vendor/github.com/go-openapi/swag/conv/sizeof.go b/api/vendor/github.com/go-openapi/swag/conv/sizeof.go new file mode 100644 index 000000000000..494346557381 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/conv/sizeof.go @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +import "unsafe" + +// bitsize returns the size in bits of a type. +// +// NOTE: [unsafe.SizeOf] simply returns the size in bytes of the value. +// For primitive types T, the generic stencil is precompiled and this value +// is resolved at compile time, resulting in an immediate call to [strconv.ParseFloat]. +// +// We may leave up to the go compiler to simplify this function into a +// constant value, which happens in practice at least for primitive types +// (e.g. numerical types). +func bitsize[T Numerical](value T) int { + const bitsPerByte = 8 + return int(unsafe.Sizeof(value)) * bitsPerByte +} diff --git a/api/vendor/github.com/go-openapi/swag/conv/type_constraints.go b/api/vendor/github.com/go-openapi/swag/conv/type_constraints.go new file mode 100644 index 000000000000..81135e827e52 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/conv/type_constraints.go @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +type ( + // these type constraints are redefined after golang.org/x/exp/constraints, + // because importing that package causes an undesired go upgrade. + + // Signed integer types, cf. [golang.org/x/exp/constraints.Signed] + Signed interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 + } + + // Unsigned integer types, cf. [golang.org/x/exp/constraints.Unsigned] + Unsigned interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr + } + + // Float numerical types, cf. [golang.org/x/exp/constraints.Float] + Float interface { + ~float32 | ~float64 + } + + // Numerical types + Numerical interface { + Signed | Unsigned | Float + } +) diff --git a/api/vendor/github.com/go-openapi/swag/conv_iface.go b/api/vendor/github.com/go-openapi/swag/conv_iface.go new file mode 100644 index 000000000000..eea7b2e56e33 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/conv_iface.go @@ -0,0 +1,486 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "time" + + "github.com/go-openapi/swag/conv" +) + +// IsFloat64AJSONInteger allows for integers [-2^53, 2^53-1] inclusive. +// +// Deprecated: use [conv.IsFloat64AJSONInteger] instead. +func IsFloat64AJSONInteger(f float64) bool { return conv.IsFloat64AJSONInteger(f) } + +// ConvertBool turns a string into a boolean. +// +// Deprecated: use [conv.ConvertBool] instead. +func ConvertBool(str string) (bool, error) { return conv.ConvertBool(str) } + +// ConvertFloat32 turns a string into a float32. +// +// Deprecated: use [conv.ConvertFloat32] instead. Alternatively, you may use the generic version [conv.ConvertFloat]. +func ConvertFloat32(str string) (float32, error) { return conv.ConvertFloat[float32](str) } + +// ConvertFloat64 turns a string into a float64. +// +// Deprecated: use [conv.ConvertFloat64] instead. Alternatively, you may use the generic version [conv.ConvertFloat]. +func ConvertFloat64(str string) (float64, error) { return conv.ConvertFloat[float64](str) } + +// ConvertInt8 turns a string into an int8. +// +// Deprecated: use [conv.ConvertInt8] instead. Alternatively, you may use the generic version [conv.ConvertInteger]. +func ConvertInt8(str string) (int8, error) { return conv.ConvertInteger[int8](str) } + +// ConvertInt16 turns a string into an int16. +// +// Deprecated: use [conv.ConvertInt16] instead. Alternatively, you may use the generic version [conv.ConvertInteger]. +func ConvertInt16(str string) (int16, error) { return conv.ConvertInteger[int16](str) } + +// ConvertInt32 turns a string into an int32. +// +// Deprecated: use [conv.ConvertInt32] instead. Alternatively, you may use the generic version [conv.ConvertInteger]. +func ConvertInt32(str string) (int32, error) { return conv.ConvertInteger[int32](str) } + +// ConvertInt64 turns a string into an int64. +// +// Deprecated: use [conv.ConvertInt64] instead. Alternatively, you may use the generic version [conv.ConvertInteger]. +func ConvertInt64(str string) (int64, error) { return conv.ConvertInteger[int64](str) } + +// ConvertUint8 turns a string into an uint8. +// +// Deprecated: use [conv.ConvertUint8] instead. Alternatively, you may use the generic version [conv.ConvertUinteger]. +func ConvertUint8(str string) (uint8, error) { return conv.ConvertUinteger[uint8](str) } + +// ConvertUint16 turns a string into an uint16. +// +// Deprecated: use [conv.ConvertUint16] instead. Alternatively, you may use the generic version [conv.ConvertUinteger]. +func ConvertUint16(str string) (uint16, error) { return conv.ConvertUinteger[uint16](str) } + +// ConvertUint32 turns a string into an uint32. +// +// Deprecated: use [conv.ConvertUint32] instead. Alternatively, you may use the generic version [conv.ConvertUinteger]. +func ConvertUint32(str string) (uint32, error) { return conv.ConvertUinteger[uint32](str) } + +// ConvertUint64 turns a string into an uint64. +// +// Deprecated: use [conv.ConvertUint64] instead. Alternatively, you may use the generic version [conv.ConvertUinteger]. +func ConvertUint64(str string) (uint64, error) { return conv.ConvertUinteger[uint64](str) } + +// FormatBool turns a boolean into a string. +// +// Deprecated: use [conv.FormatBool] instead. +func FormatBool(value bool) string { return conv.FormatBool(value) } + +// FormatFloat32 turns a float32 into a string. +// +// Deprecated: use [conv.FormatFloat] instead. +func FormatFloat32(value float32) string { return conv.FormatFloat(value) } + +// FormatFloat64 turns a float64 into a string. +// +// Deprecated: use [conv.FormatFloat] instead. +func FormatFloat64(value float64) string { return conv.FormatFloat(value) } + +// FormatInt8 turns an int8 into a string. +// +// Deprecated: use [conv.FormatInteger] instead. +func FormatInt8(value int8) string { return conv.FormatInteger(value) } + +// FormatInt16 turns an int16 into a string. +// +// Deprecated: use [conv.FormatInteger] instead. +func FormatInt16(value int16) string { return conv.FormatInteger(value) } + +// FormatInt32 turns an int32 into a string +// +// Deprecated: use [conv.FormatInteger] instead. +func FormatInt32(value int32) string { return conv.FormatInteger(value) } + +// FormatInt64 turns an int64 into a string. +// +// Deprecated: use [conv.FormatInteger] instead. +func FormatInt64(value int64) string { return conv.FormatInteger(value) } + +// FormatUint8 turns an uint8 into a string. +// +// Deprecated: use [conv.FormatUinteger] instead. +func FormatUint8(value uint8) string { return conv.FormatUinteger(value) } + +// FormatUint16 turns an uint16 into a string. +// +// Deprecated: use [conv.FormatUinteger] instead. +func FormatUint16(value uint16) string { return conv.FormatUinteger(value) } + +// FormatUint32 turns an uint32 into a string. +// +// Deprecated: use [conv.FormatUinteger] instead. +func FormatUint32(value uint32) string { return conv.FormatUinteger(value) } + +// FormatUint64 turns an uint64 into a string. +// +// Deprecated: use [conv.FormatUinteger] instead. +func FormatUint64(value uint64) string { return conv.FormatUinteger(value) } + +// String turn a pointer to of the string value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func String(v string) *string { return conv.Pointer(v) } + +// StringValue turn the value of the string pointer passed in or +// "" if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func StringValue(v *string) string { return conv.Value(v) } + +// StringSlice converts a slice of string values into a slice of string pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func StringSlice(src []string) []*string { return conv.PointerSlice(src) } + +// StringValueSlice converts a slice of string pointers into a slice of string values. +// +// Deprecated: use [conv.ValueSlice] instead. +func StringValueSlice(src []*string) []string { return conv.ValueSlice(src) } + +// StringMap converts a string map of string values into a string map of string pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func StringMap(src map[string]string) map[string]*string { return conv.PointerMap(src) } + +// StringValueMap converts a string map of string pointers into a string map of string values. +// +// Deprecated: use [conv.ValueMap] instead. +func StringValueMap(src map[string]*string) map[string]string { return conv.ValueMap(src) } + +// Bool turn a pointer to of the bool value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Bool(v bool) *bool { return conv.Pointer(v) } + +// BoolValue turn the value of the bool pointer passed in or false if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func BoolValue(v *bool) bool { return conv.Value(v) } + +// BoolSlice converts a slice of bool values into a slice of bool pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func BoolSlice(src []bool) []*bool { return conv.PointerSlice(src) } + +// BoolValueSlice converts a slice of bool pointers into a slice of bool values. +// +// Deprecated: use [conv.ValueSlice] instead. +func BoolValueSlice(src []*bool) []bool { return conv.ValueSlice(src) } + +// BoolMap converts a string map of bool values into a string map of bool pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func BoolMap(src map[string]bool) map[string]*bool { return conv.PointerMap(src) } + +// BoolValueMap converts a string map of bool pointers into a string map of bool values. +// +// Deprecated: use [conv.ValueMap] instead. +func BoolValueMap(src map[string]*bool) map[string]bool { return conv.ValueMap(src) } + +// Int turn a pointer to of the int value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Int(v int) *int { return conv.Pointer(v) } + +// IntValue turn the value of the int pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func IntValue(v *int) int { return conv.Value(v) } + +// IntSlice converts a slice of int values into a slice of int pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func IntSlice(src []int) []*int { return conv.PointerSlice(src) } + +// IntValueSlice converts a slice of int pointers into a slice of int values. +// +// Deprecated: use [conv.ValueSlice] instead. +func IntValueSlice(src []*int) []int { return conv.ValueSlice(src) } + +// IntMap converts a string map of int values into a string map of int pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func IntMap(src map[string]int) map[string]*int { return conv.PointerMap(src) } + +// IntValueMap converts a string map of int pointers into a string map of int values. +// +// Deprecated: use [conv.ValueMap] instead. +func IntValueMap(src map[string]*int) map[string]int { return conv.ValueMap(src) } + +// Int32 turn a pointer to of the int32 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Int32(v int32) *int32 { return conv.Pointer(v) } + +// Int32Value turn the value of the int32 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Int32Value(v *int32) int32 { return conv.Value(v) } + +// Int32Slice converts a slice of int32 values into a slice of int32 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Int32Slice(src []int32) []*int32 { return conv.PointerSlice(src) } + +// Int32ValueSlice converts a slice of int32 pointers into a slice of int32 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Int32ValueSlice(src []*int32) []int32 { return conv.ValueSlice(src) } + +// Int32Map converts a string map of int32 values into a string map of int32 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Int32Map(src map[string]int32) map[string]*int32 { return conv.PointerMap(src) } + +// Int32ValueMap converts a string map of int32 pointers into a string map of int32 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Int32ValueMap(src map[string]*int32) map[string]int32 { return conv.ValueMap(src) } + +// Int64 turn a pointer to of the int64 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Int64(v int64) *int64 { return conv.Pointer(v) } + +// Int64Value turn the value of the int64 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Int64Value(v *int64) int64 { return conv.Value(v) } + +// Int64Slice converts a slice of int64 values into a slice of int64 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Int64Slice(src []int64) []*int64 { return conv.PointerSlice(src) } + +// Int64ValueSlice converts a slice of int64 pointers into a slice of int64 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Int64ValueSlice(src []*int64) []int64 { return conv.ValueSlice(src) } + +// Int64Map converts a string map of int64 values into a string map of int64 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Int64Map(src map[string]int64) map[string]*int64 { return conv.PointerMap(src) } + +// Int64ValueMap converts a string map of int64 pointers into a string map of int64 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Int64ValueMap(src map[string]*int64) map[string]int64 { return conv.ValueMap(src) } + +// Uint16 turn a pointer to of the uint16 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Uint16(v uint16) *uint16 { return conv.Pointer(v) } + +// Uint16Value turn the value of the uint16 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Uint16Value(v *uint16) uint16 { return conv.Value(v) } + +// Uint16Slice converts a slice of uint16 values into a slice of uint16 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Uint16Slice(src []uint16) []*uint16 { return conv.PointerSlice(src) } + +// Uint16ValueSlice converts a slice of uint16 pointers into a slice of uint16 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Uint16ValueSlice(src []*uint16) []uint16 { return conv.ValueSlice(src) } + +// Uint16Map converts a string map of uint16 values into a string map of uint16 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Uint16Map(src map[string]uint16) map[string]*uint16 { return conv.PointerMap(src) } + +// Uint16ValueMap converts a string map of uint16 pointers into a string map of uint16 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { return conv.ValueMap(src) } + +// Uint turn a pointer to of the uint value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Uint(v uint) *uint { return conv.Pointer(v) } + +// UintValue turn the value of the uint pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func UintValue(v *uint) uint { return conv.Value(v) } + +// UintSlice converts a slice of uint values into a slice of uint pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func UintSlice(src []uint) []*uint { return conv.PointerSlice(src) } + +// UintValueSlice converts a slice of uint pointers into a slice of uint values. +// +// Deprecated: use [conv.ValueSlice] instead. +func UintValueSlice(src []*uint) []uint { return conv.ValueSlice(src) } + +// UintMap converts a string map of uint values into a string map of uint pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func UintMap(src map[string]uint) map[string]*uint { return conv.PointerMap(src) } + +// UintValueMap converts a string map of uint pointers into a string map of uint values. +// +// Deprecated: use [conv.ValueMap] instead. +func UintValueMap(src map[string]*uint) map[string]uint { return conv.ValueMap(src) } + +// Uint32 turn a pointer to of the uint32 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Uint32(v uint32) *uint32 { return conv.Pointer(v) } + +// Uint32Value turn the value of the uint32 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Uint32Value(v *uint32) uint32 { return conv.Value(v) } + +// Uint32Slice converts a slice of uint32 values into a slice of uint32 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Uint32Slice(src []uint32) []*uint32 { return conv.PointerSlice(src) } + +// Uint32ValueSlice converts a slice of uint32 pointers into a slice of uint32 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Uint32ValueSlice(src []*uint32) []uint32 { return conv.ValueSlice(src) } + +// Uint32Map converts a string map of uint32 values into a string map of uint32 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Uint32Map(src map[string]uint32) map[string]*uint32 { return conv.PointerMap(src) } + +// Uint32ValueMap converts a string map of uint32 pointers into a string map of uint32 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { return conv.ValueMap(src) } + +// Uint64 turn a pointer to of the uint64 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Uint64(v uint64) *uint64 { return conv.Pointer(v) } + +// Uint64Value turn the value of the uint64 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Uint64Value(v *uint64) uint64 { return conv.Value(v) } + +// Uint64Slice converts a slice of uint64 values into a slice of uint64 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Uint64Slice(src []uint64) []*uint64 { return conv.PointerSlice(src) } + +// Uint64ValueSlice converts a slice of uint64 pointers into a slice of uint64 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Uint64ValueSlice(src []*uint64) []uint64 { return conv.ValueSlice(src) } + +// Uint64Map converts a string map of uint64 values into a string map of uint64 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Uint64Map(src map[string]uint64) map[string]*uint64 { return conv.PointerMap(src) } + +// Uint64ValueMap converts a string map of uint64 pointers into a string map of uint64 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { return conv.ValueMap(src) } + +// Float32 turn a pointer to of the float32 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Float32(v float32) *float32 { return conv.Pointer(v) } + +// Float32Value turn the value of the float32 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Float32Value(v *float32) float32 { return conv.Value(v) } + +// Float32Slice converts a slice of float32 values into a slice of float32 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Float32Slice(src []float32) []*float32 { return conv.PointerSlice(src) } + +// Float32ValueSlice converts a slice of float32 pointers into a slice of float32 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Float32ValueSlice(src []*float32) []float32 { return conv.ValueSlice(src) } + +// Float32Map converts a string map of float32 values into a string map of float32 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Float32Map(src map[string]float32) map[string]*float32 { return conv.PointerMap(src) } + +// Float32ValueMap converts a string map of float32 pointers into a string map of float32 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Float32ValueMap(src map[string]*float32) map[string]float32 { return conv.ValueMap(src) } + +// Float64 turn a pointer to of the float64 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Float64(v float64) *float64 { return conv.Pointer(v) } + +// Float64Value turn the value of the float64 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Float64Value(v *float64) float64 { return conv.Value(v) } + +// Float64Slice converts a slice of float64 values into a slice of float64 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Float64Slice(src []float64) []*float64 { return conv.PointerSlice(src) } + +// Float64ValueSlice converts a slice of float64 pointers into a slice of float64 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Float64ValueSlice(src []*float64) []float64 { return conv.ValueSlice(src) } + +// Float64Map converts a string map of float64 values into a string map of float64 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Float64Map(src map[string]float64) map[string]*float64 { return conv.PointerMap(src) } + +// Float64ValueMap converts a string map of float64 pointers into a string map of float64 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Float64ValueMap(src map[string]*float64) map[string]float64 { return conv.ValueMap(src) } + +// Time turn a pointer to of the time.Time value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Time(v time.Time) *time.Time { return conv.Pointer(v) } + +// TimeValue turn the value of the time.Time pointer passed in or time.Time{} if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func TimeValue(v *time.Time) time.Time { return conv.Value(v) } + +// TimeSlice converts a slice of time.Time values into a slice of time.Time pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func TimeSlice(src []time.Time) []*time.Time { return conv.PointerSlice(src) } + +// TimeValueSlice converts a slice of time.Time pointers into a slice of time.Time values +// +// Deprecated: use [conv.ValueSlice] instead. +func TimeValueSlice(src []*time.Time) []time.Time { return conv.ValueSlice(src) } + +// TimeMap converts a string map of time.Time values into a string map of time.Time pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func TimeMap(src map[string]time.Time) map[string]*time.Time { return conv.PointerMap(src) } + +// TimeValueMap converts a string map of time.Time pointers into a string map of time.Time values. +// +// Deprecated: use [conv.ValueMap] instead. +func TimeValueMap(src map[string]*time.Time) map[string]time.Time { return conv.ValueMap(src) } diff --git a/api/vendor/github.com/go-openapi/swag/convert.go b/api/vendor/github.com/go-openapi/swag/convert.go deleted file mode 100644 index fc085aeb8ea5..000000000000 --- a/api/vendor/github.com/go-openapi/swag/convert.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "math" - "strconv" - "strings" -) - -// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER -const ( - maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 - minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 - epsilon float64 = 1e-9 -) - -// IsFloat64AJSONInteger allow for integers [-2^53, 2^53-1] inclusive -func IsFloat64AJSONInteger(f float64) bool { - if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { - return false - } - fa := math.Abs(f) - g := float64(uint64(f)) - ga := math.Abs(g) - - diff := math.Abs(f - g) - - // more info: https://floating-point-gui.de/errors/comparison/#look-out-for-edge-cases - switch { - case f == g: // best case - return true - case f == float64(int64(f)) || f == float64(uint64(f)): // optimistic case - return true - case f == 0 || g == 0 || diff < math.SmallestNonzeroFloat64: // very close to 0 values - return diff < (epsilon * math.SmallestNonzeroFloat64) - } - // check the relative error - return diff/math.Min(fa+ga, math.MaxFloat64) < epsilon -} - -var evaluatesAsTrue map[string]struct{} - -func init() { - evaluatesAsTrue = map[string]struct{}{ - "true": {}, - "1": {}, - "yes": {}, - "ok": {}, - "y": {}, - "on": {}, - "selected": {}, - "checked": {}, - "t": {}, - "enabled": {}, - } -} - -// ConvertBool turn a string into a boolean -func ConvertBool(str string) (bool, error) { - _, ok := evaluatesAsTrue[strings.ToLower(str)] - return ok, nil -} - -// ConvertFloat32 turn a string into a float32 -func ConvertFloat32(str string) (float32, error) { - f, err := strconv.ParseFloat(str, 32) - if err != nil { - return 0, err - } - return float32(f), nil -} - -// ConvertFloat64 turn a string into a float64 -func ConvertFloat64(str string) (float64, error) { - return strconv.ParseFloat(str, 64) -} - -// ConvertInt8 turn a string into an int8 -func ConvertInt8(str string) (int8, error) { - i, err := strconv.ParseInt(str, 10, 8) - if err != nil { - return 0, err - } - return int8(i), nil -} - -// ConvertInt16 turn a string into an int16 -func ConvertInt16(str string) (int16, error) { - i, err := strconv.ParseInt(str, 10, 16) - if err != nil { - return 0, err - } - return int16(i), nil -} - -// ConvertInt32 turn a string into an int32 -func ConvertInt32(str string) (int32, error) { - i, err := strconv.ParseInt(str, 10, 32) - if err != nil { - return 0, err - } - return int32(i), nil -} - -// ConvertInt64 turn a string into an int64 -func ConvertInt64(str string) (int64, error) { - return strconv.ParseInt(str, 10, 64) -} - -// ConvertUint8 turn a string into an uint8 -func ConvertUint8(str string) (uint8, error) { - i, err := strconv.ParseUint(str, 10, 8) - if err != nil { - return 0, err - } - return uint8(i), nil -} - -// ConvertUint16 turn a string into an uint16 -func ConvertUint16(str string) (uint16, error) { - i, err := strconv.ParseUint(str, 10, 16) - if err != nil { - return 0, err - } - return uint16(i), nil -} - -// ConvertUint32 turn a string into an uint32 -func ConvertUint32(str string) (uint32, error) { - i, err := strconv.ParseUint(str, 10, 32) - if err != nil { - return 0, err - } - return uint32(i), nil -} - -// ConvertUint64 turn a string into an uint64 -func ConvertUint64(str string) (uint64, error) { - return strconv.ParseUint(str, 10, 64) -} - -// FormatBool turns a boolean into a string -func FormatBool(value bool) string { - return strconv.FormatBool(value) -} - -// FormatFloat32 turns a float32 into a string -func FormatFloat32(value float32) string { - return strconv.FormatFloat(float64(value), 'f', -1, 32) -} - -// FormatFloat64 turns a float64 into a string -func FormatFloat64(value float64) string { - return strconv.FormatFloat(value, 'f', -1, 64) -} - -// FormatInt8 turns an int8 into a string -func FormatInt8(value int8) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt16 turns an int16 into a string -func FormatInt16(value int16) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt32 turns an int32 into a string -func FormatInt32(value int32) string { - return strconv.Itoa(int(value)) -} - -// FormatInt64 turns an int64 into a string -func FormatInt64(value int64) string { - return strconv.FormatInt(value, 10) -} - -// FormatUint8 turns an uint8 into a string -func FormatUint8(value uint8) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint16 turns an uint16 into a string -func FormatUint16(value uint16) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint32 turns an uint32 into a string -func FormatUint32(value uint32) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint64 turns an uint64 into a string -func FormatUint64(value uint64) string { - return strconv.FormatUint(value, 10) -} diff --git a/api/vendor/github.com/go-openapi/swag/convert_types.go b/api/vendor/github.com/go-openapi/swag/convert_types.go deleted file mode 100644 index c49cc473a8c2..000000000000 --- a/api/vendor/github.com/go-openapi/swag/convert_types.go +++ /dev/null @@ -1,730 +0,0 @@ -package swag - -import "time" - -// This file was taken from the aws go sdk - -// String returns a pointer to of the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to of the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to of the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int32 returns a pointer to of the int32 value passed in. -func Int32(v int32) *int32 { - return &v -} - -// Int32Value returns the value of the int32 pointer passed in or -// 0 if the pointer is nil. -func Int32Value(v *int32) int32 { - if v != nil { - return *v - } - return 0 -} - -// Int32Slice converts a slice of int32 values into a slice of -// int32 pointers -func Int32Slice(src []int32) []*int32 { - dst := make([]*int32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int32ValueSlice converts a slice of int32 pointers into a slice of -// int32 values -func Int32ValueSlice(src []*int32) []int32 { - dst := make([]int32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int32Map converts a string map of int32 values into a string -// map of int32 pointers -func Int32Map(src map[string]int32) map[string]*int32 { - dst := make(map[string]*int32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int32ValueMap converts a string map of int32 pointers into a string -// map of int32 values -func Int32ValueMap(src map[string]*int32) map[string]int32 { - dst := make(map[string]int32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to of the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint16 returns a pointer to of the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return &v -} - -// Uint16Value returns the value of the uint16 pointer passed in or -// 0 if the pointer is nil. -func Uint16Value(v *uint16) uint16 { - if v != nil { - return *v - } - - return 0 -} - -// Uint16Slice converts a slice of uint16 values into a slice of -// uint16 pointers -func Uint16Slice(src []uint16) []*uint16 { - dst := make([]*uint16, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - - return dst -} - -// Uint16ValueSlice converts a slice of uint16 pointers into a slice of -// uint16 values -func Uint16ValueSlice(src []*uint16) []uint16 { - dst := make([]uint16, len(src)) - - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - - return dst -} - -// Uint16Map converts a string map of uint16 values into a string -// map of uint16 pointers -func Uint16Map(src map[string]uint16) map[string]*uint16 { - dst := make(map[string]*uint16) - - for k, val := range src { - v := val - dst[k] = &v - } - - return dst -} - -// Uint16ValueMap converts a string map of uint16 pointers into a string -// map of uint16 values -func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { - dst := make(map[string]uint16) - - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - - return dst -} - -// Uint returns a pointer to of the uint value passed in. -func Uint(v uint) *uint { - return &v -} - -// UintValue returns the value of the uint pointer passed in or -// 0 if the pointer is nil. -func UintValue(v *uint) uint { - if v != nil { - return *v - } - return 0 -} - -// UintSlice converts a slice of uint values into a slice of -// uint pointers -func UintSlice(src []uint) []*uint { - dst := make([]*uint, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// UintValueSlice converts a slice of uint pointers into a slice of -// uint values -func UintValueSlice(src []*uint) []uint { - dst := make([]uint, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// UintMap converts a string map of uint values into a string -// map of uint pointers -func UintMap(src map[string]uint) map[string]*uint { - dst := make(map[string]*uint) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// UintValueMap converts a string map of uint pointers into a string -// map of uint values -func UintValueMap(src map[string]*uint) map[string]uint { - dst := make(map[string]uint) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint32 returns a pointer to of the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint32Value returns the value of the uint32 pointer passed in or -// 0 if the pointer is nil. -func Uint32Value(v *uint32) uint32 { - if v != nil { - return *v - } - return 0 -} - -// Uint32Slice converts a slice of uint32 values into a slice of -// uint32 pointers -func Uint32Slice(src []uint32) []*uint32 { - dst := make([]*uint32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint32ValueSlice converts a slice of uint32 pointers into a slice of -// uint32 values -func Uint32ValueSlice(src []*uint32) []uint32 { - dst := make([]uint32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint32Map converts a string map of uint32 values into a string -// map of uint32 pointers -func Uint32Map(src map[string]uint32) map[string]*uint32 { - dst := make(map[string]*uint32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint32ValueMap converts a string map of uint32 pointers into a string -// map of uint32 values -func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { - dst := make(map[string]uint32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint64 returns a pointer to of the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return &v -} - -// Uint64Value returns the value of the uint64 pointer passed in or -// 0 if the pointer is nil. -func Uint64Value(v *uint64) uint64 { - if v != nil { - return *v - } - return 0 -} - -// Uint64Slice converts a slice of uint64 values into a slice of -// uint64 pointers -func Uint64Slice(src []uint64) []*uint64 { - dst := make([]*uint64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint64ValueSlice converts a slice of uint64 pointers into a slice of -// uint64 values -func Uint64ValueSlice(src []*uint64) []uint64 { - dst := make([]uint64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint64Map converts a string map of uint64 values into a string -// map of uint64 pointers -func Uint64Map(src map[string]uint64) map[string]*uint64 { - dst := make(map[string]*uint64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint64ValueMap converts a string map of uint64 pointers into a string -// map of uint64 values -func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { - dst := make(map[string]uint64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float32 returns a pointer to of the float32 value passed in. -func Float32(v float32) *float32 { - return &v -} - -// Float32Value returns the value of the float32 pointer passed in or -// 0 if the pointer is nil. -func Float32Value(v *float32) float32 { - if v != nil { - return *v - } - - return 0 -} - -// Float32Slice converts a slice of float32 values into a slice of -// float32 pointers -func Float32Slice(src []float32) []*float32 { - dst := make([]*float32, len(src)) - - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - - return dst -} - -// Float32ValueSlice converts a slice of float32 pointers into a slice of -// float32 values -func Float32ValueSlice(src []*float32) []float32 { - dst := make([]float32, len(src)) - - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - - return dst -} - -// Float32Map converts a string map of float32 values into a string -// map of float32 pointers -func Float32Map(src map[string]float32) map[string]*float32 { - dst := make(map[string]*float32) - - for k, val := range src { - v := val - dst[k] = &v - } - - return dst -} - -// Float32ValueMap converts a string map of float32 pointers into a string -// map of float32 values -func Float32ValueMap(src map[string]*float32) map[string]float32 { - dst := make(map[string]float32) - - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - - return dst -} - -// Float64 returns a pointer to of the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to of the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/api/vendor/github.com/go-openapi/swag/doc.go b/api/vendor/github.com/go-openapi/swag/doc.go index 55094cb74c4d..b54b57478af6 100644 --- a/api/vendor/github.com/go-openapi/swag/doc.go +++ b/api/vendor/github.com/go-openapi/swag/doc.go @@ -1,31 +1,47 @@ -// Copyright 2015 go-swagger maintainers +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package swag contains a bunch of helper functions for go-openapi and go-swagger projects. // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at +// You may also use it standalone for your projects. // -// http://www.apache.org/licenses/LICENSE-2.0 +// NOTE: all features that used to be exposed as package-level members (constants, variables, +// functions and types) are now deprecated and are superseded by equivalent features in +// more specialized sub-packages. +// Moving forward, no additional feature will be added to the [swag] API directly at the root package level, +// which remains there for backward-compatibility purposes. // -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag contains a bunch of helper functions for go-openapi and go-swagger projects. - -You may also use it standalone for your projects. - - - convert between value and pointers for builtin types - - convert from string to builtin types (wraps strconv) - - fast json concatenation - - search in path - - load from file or http - - name mangling - -This repo has only few dependencies outside of the standard library: - - - YAML utilities depend on gopkg.in/yaml.v2 -*/ +// Child modules will continue to evolve or some new ones may be added in the future. +// +// # Modules +// +// - [cmdutils] utilities to work with CLIs +// +// - [conv] type conversion utilities +// +// - [fileutils] file utilities +// +// - [jsonname] JSON utilities +// +// - [jsonutils] JSON utilities +// +// - [loading] file loading +// +// - [mangling] safe name generation +// +// - [netutils] networking utilities +// +// - [stringutils] `string` utilities +// +// - [typeutils] `go` types utilities +// +// - [yamlutils] YAML utilities +// +// # Dependencies +// +// This repo has a few dependencies outside of the standard library: +// +// - YAML utilities depend on [go.yaml.in/yaml/v3] package swag + +//go:generate mockery diff --git a/api/vendor/github.com/go-openapi/swag/errors.go b/api/vendor/github.com/go-openapi/swag/errors.go deleted file mode 100644 index 6c67fbf92e35..000000000000 --- a/api/vendor/github.com/go-openapi/swag/errors.go +++ /dev/null @@ -1,15 +0,0 @@ -package swag - -type swagError string - -const ( - // ErrYAML is an error raised by YAML utilities - ErrYAML swagError = "yaml error" - - // ErrLoader is an error raised by the file loader utility - ErrLoader swagError = "loader error" -) - -func (e swagError) Error() string { - return string(e) -} diff --git a/api/vendor/github.com/go-openapi/swag/file.go b/api/vendor/github.com/go-openapi/swag/file.go deleted file mode 100644 index 16accc55f82e..000000000000 --- a/api/vendor/github.com/go-openapi/swag/file.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import "mime/multipart" - -// File represents an uploaded file. -type File struct { - Data multipart.File - Header *multipart.FileHeader -} - -// Read bytes from the file -func (f *File) Read(p []byte) (n int, err error) { - return f.Data.Read(p) -} - -// Close the file -func (f *File) Close() error { - return f.Data.Close() -} diff --git a/api/vendor/github.com/go-openapi/swag/fileutils/LICENSE b/api/vendor/github.com/go-openapi/swag/fileutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/fileutils/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/api/vendor/github.com/go-openapi/swag/fileutils/doc.go b/api/vendor/github.com/go-openapi/swag/fileutils/doc.go new file mode 100644 index 000000000000..859a200d8413 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/fileutils/doc.go @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package fileutils exposes utilities to deal with files and paths. +// +// Currently, there is: +// - [File] to represent an abstraction of an uploaded file. +// For instance, this is used by [github.com/go-openapi/runtime.File]. +// - path search utilities (e.g. finding packages in the GO search path) +package fileutils diff --git a/api/vendor/github.com/go-openapi/swag/fileutils/file.go b/api/vendor/github.com/go-openapi/swag/fileutils/file.go new file mode 100644 index 000000000000..5ad4cfaeafa4 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/fileutils/file.go @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package fileutils + +import "mime/multipart" + +// File represents an uploaded file. +type File struct { + Data multipart.File + Header *multipart.FileHeader +} + +// Read bytes from the file +func (f *File) Read(p []byte) (n int, err error) { + return f.Data.Read(p) +} + +// Close the file +func (f *File) Close() error { + return f.Data.Close() +} diff --git a/api/vendor/github.com/go-openapi/swag/path.go b/api/vendor/github.com/go-openapi/swag/fileutils/path.go similarity index 58% rename from api/vendor/github.com/go-openapi/swag/path.go rename to api/vendor/github.com/go-openapi/swag/fileutils/path.go index 941bd0176b05..dd09f690bf81 100644 --- a/api/vendor/github.com/go-openapi/swag/path.go +++ b/api/vendor/github.com/go-openapi/swag/fileutils/path.go @@ -1,18 +1,7 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 -package swag +package fileutils import ( "os" @@ -21,10 +10,8 @@ import ( "strings" ) -const ( - // GOPATHKey represents the env key for gopath - GOPATHKey = "GOPATH" -) +// GOPATHKey represents the env key for gopath +const GOPATHKey = "GOPATH" // FindInSearchPath finds a package in a provided lists of paths func FindInSearchPath(searchPath, pkg string) string { @@ -40,11 +27,17 @@ func FindInSearchPath(searchPath, pkg string) string { } // FindInGoSearchPath finds a package in the $GOPATH:$GOROOT +// +// Deprecated: this function is no longer relevant with modern go. +// It uses [runtime.GOROOT] under the hood, which is deprecated as of go1.24. func FindInGoSearchPath(pkg string) string { return FindInSearchPath(FullGoSearchPath(), pkg) } // FullGoSearchPath gets the search paths for finding packages +// +// Deprecated: this function is no longer relevant with modern go. +// It uses [runtime.GOROOT] under the hood, which is deprecated as of go1.24. func FullGoSearchPath() string { allPaths := os.Getenv(GOPATHKey) if allPaths == "" { diff --git a/api/vendor/github.com/go-openapi/swag/fileutils_iface.go b/api/vendor/github.com/go-openapi/swag/fileutils_iface.go new file mode 100644 index 000000000000..f3e79a0e4bce --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/fileutils_iface.go @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/fileutils" + +// GOPATHKey represents the env key for gopath +// +// Deprecated: use [fileutils.GOPATHKey] instead. +const GOPATHKey = fileutils.GOPATHKey + +// File represents an uploaded file. +// +// Deprecated: use [fileutils.File] instead. +type File = fileutils.File + +// FindInSearchPath finds a package in a provided lists of paths. +// +// Deprecated: use [fileutils.FindInSearchPath] instead. +func FindInSearchPath(searchPath, pkg string) string { + return fileutils.FindInSearchPath(searchPath, pkg) +} + +// FindInGoSearchPath finds a package in the $GOPATH:$GOROOT +// +// Deprecated: use [fileutils.FindInGoSearchPath] instead. +func FindInGoSearchPath(pkg string) string { return fileutils.FindInGoSearchPath(pkg) } + +// FullGoSearchPath gets the search paths for finding packages +// +// Deprecated: use [fileutils.FullGoSearchPath] instead. +func FullGoSearchPath() string { return fileutils.FullGoSearchPath() } diff --git a/api/vendor/github.com/go-openapi/swag/go.work b/api/vendor/github.com/go-openapi/swag/go.work new file mode 100644 index 000000000000..1e537f0749b0 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/go.work @@ -0,0 +1,20 @@ +use ( + . + ./cmdutils + ./conv + ./fileutils + ./jsonname + ./jsonutils + ./jsonutils/adapters/easyjson + ./jsonutils/adapters/testintegration + ./jsonutils/adapters/testintegration/benchmarks + ./jsonutils/fixtures_test + ./loading + ./mangling + ./netutils + ./stringutils + ./typeutils + ./yamlutils +) + +go 1.24.0 diff --git a/api/vendor/github.com/go-openapi/swag/go.work.sum b/api/vendor/github.com/go-openapi/swag/go.work.sum new file mode 100644 index 000000000000..c1308cafa672 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/go.work.sum @@ -0,0 +1,7 @@ +github.com/go-openapi/testify/v2 v2.0.1/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= +golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= +golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= +golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= diff --git a/api/vendor/github.com/go-openapi/swag/initialism_index.go b/api/vendor/github.com/go-openapi/swag/initialism_index.go deleted file mode 100644 index 20a359bb60a2..000000000000 --- a/api/vendor/github.com/go-openapi/swag/initialism_index.go +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "sort" - "strings" - "sync" -) - -var ( - // commonInitialisms are common acronyms that are kept as whole uppercased words. - commonInitialisms *indexOfInitialisms - - // initialisms is a slice of sorted initialisms - initialisms []string - - // a copy of initialisms pre-baked as []rune - initialismsRunes [][]rune - initialismsUpperCased [][]rune - - isInitialism func(string) bool - - maxAllocMatches int -) - -func init() { - // Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769 - configuredInitialisms := map[string]bool{ - "ACL": true, - "API": true, - "ASCII": true, - "CPU": true, - "CSS": true, - "DNS": true, - "EOF": true, - "GUID": true, - "HTML": true, - "HTTPS": true, - "HTTP": true, - "ID": true, - "IP": true, - "IPv4": true, - "IPv6": true, - "JSON": true, - "LHS": true, - "OAI": true, - "QPS": true, - "RAM": true, - "RHS": true, - "RPC": true, - "SLA": true, - "SMTP": true, - "SQL": true, - "SSH": true, - "TCP": true, - "TLS": true, - "TTL": true, - "UDP": true, - "UI": true, - "UID": true, - "UUID": true, - "URI": true, - "URL": true, - "UTF8": true, - "VM": true, - "XML": true, - "XMPP": true, - "XSRF": true, - "XSS": true, - } - - // a thread-safe index of initialisms - commonInitialisms = newIndexOfInitialisms().load(configuredInitialisms) - initialisms = commonInitialisms.sorted() - initialismsRunes = asRunes(initialisms) - initialismsUpperCased = asUpperCased(initialisms) - maxAllocMatches = maxAllocHeuristic(initialismsRunes) - - // a test function - isInitialism = commonInitialisms.isInitialism -} - -func asRunes(in []string) [][]rune { - out := make([][]rune, len(in)) - for i, initialism := range in { - out[i] = []rune(initialism) - } - - return out -} - -func asUpperCased(in []string) [][]rune { - out := make([][]rune, len(in)) - - for i, initialism := range in { - out[i] = []rune(upper(trim(initialism))) - } - - return out -} - -func maxAllocHeuristic(in [][]rune) int { - heuristic := make(map[rune]int) - for _, initialism := range in { - heuristic[initialism[0]]++ - } - - var maxAlloc int - for _, val := range heuristic { - if val > maxAlloc { - maxAlloc = val - } - } - - return maxAlloc -} - -// AddInitialisms add additional initialisms -func AddInitialisms(words ...string) { - for _, word := range words { - // commonInitialisms[upper(word)] = true - commonInitialisms.add(upper(word)) - } - // sort again - initialisms = commonInitialisms.sorted() - initialismsRunes = asRunes(initialisms) - initialismsUpperCased = asUpperCased(initialisms) -} - -// indexOfInitialisms is a thread-safe implementation of the sorted index of initialisms. -// Since go1.9, this may be implemented with sync.Map. -type indexOfInitialisms struct { - sortMutex *sync.Mutex - index *sync.Map -} - -func newIndexOfInitialisms() *indexOfInitialisms { - return &indexOfInitialisms{ - sortMutex: new(sync.Mutex), - index: new(sync.Map), - } -} - -func (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms { - m.sortMutex.Lock() - defer m.sortMutex.Unlock() - for k, v := range initial { - m.index.Store(k, v) - } - return m -} - -func (m *indexOfInitialisms) isInitialism(key string) bool { - _, ok := m.index.Load(key) - return ok -} - -func (m *indexOfInitialisms) add(key string) *indexOfInitialisms { - m.index.Store(key, true) - return m -} - -func (m *indexOfInitialisms) sorted() (result []string) { - m.sortMutex.Lock() - defer m.sortMutex.Unlock() - m.index.Range(func(key, _ interface{}) bool { - k := key.(string) - result = append(result, k) - return true - }) - sort.Sort(sort.Reverse(byInitialism(result))) - return -} - -type byInitialism []string - -func (s byInitialism) Len() int { - return len(s) -} -func (s byInitialism) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s byInitialism) Less(i, j int) bool { - if len(s[i]) != len(s[j]) { - return len(s[i]) < len(s[j]) - } - - return strings.Compare(s[i], s[j]) > 0 -} diff --git a/api/vendor/github.com/go-openapi/swag/json.go b/api/vendor/github.com/go-openapi/swag/json.go deleted file mode 100644 index c7caa9908fea..000000000000 --- a/api/vendor/github.com/go-openapi/swag/json.go +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "bytes" - "encoding/json" - "log" - "reflect" - "strings" - "sync" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" -) - -// nullJSON represents a JSON object with null type -var nullJSON = []byte("null") - -// DefaultJSONNameProvider the default cache for types -var DefaultJSONNameProvider = NewNameProvider() - -const comma = byte(',') - -var closers map[byte]byte - -func init() { - closers = map[byte]byte{ - '{': '}', - '[': ']', - } -} - -type ejMarshaler interface { - MarshalEasyJSON(w *jwriter.Writer) -} - -type ejUnmarshaler interface { - UnmarshalEasyJSON(w *jlexer.Lexer) -} - -// WriteJSON writes json data, prefers finding an appropriate interface to short-circuit the marshaler -// so it takes the fastest option available. -func WriteJSON(data interface{}) ([]byte, error) { - if d, ok := data.(ejMarshaler); ok { - jw := new(jwriter.Writer) - d.MarshalEasyJSON(jw) - return jw.BuildBytes() - } - if d, ok := data.(json.Marshaler); ok { - return d.MarshalJSON() - } - return json.Marshal(data) -} - -// ReadJSON reads json data, prefers finding an appropriate interface to short-circuit the unmarshaler -// so it takes the fastest option available -func ReadJSON(data []byte, value interface{}) error { - trimmedData := bytes.Trim(data, "\x00") - if d, ok := value.(ejUnmarshaler); ok { - jl := &jlexer.Lexer{Data: trimmedData} - d.UnmarshalEasyJSON(jl) - return jl.Error() - } - if d, ok := value.(json.Unmarshaler); ok { - return d.UnmarshalJSON(trimmedData) - } - return json.Unmarshal(trimmedData, value) -} - -// DynamicJSONToStruct converts an untyped json structure into a struct -func DynamicJSONToStruct(data interface{}, target interface{}) error { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := WriteJSON(data) - if err != nil { - return err - } - return ReadJSON(b, target) -} - -// ConcatJSON concatenates multiple json objects efficiently -func ConcatJSON(blobs ...[]byte) []byte { - if len(blobs) == 0 { - return nil - } - - last := len(blobs) - 1 - for blobs[last] == nil || bytes.Equal(blobs[last], nullJSON) { - // strips trailing null objects - last-- - if last < 0 { - // there was nothing but "null"s or nil... - return nil - } - } - if last == 0 { - return blobs[0] - } - - var opening, closing byte - var idx, a int - buf := bytes.NewBuffer(nil) - - for i, b := range blobs[:last+1] { - if b == nil || bytes.Equal(b, nullJSON) { - // a null object is in the list: skip it - continue - } - if len(b) > 0 && opening == 0 { // is this an array or an object? - opening, closing = b[0], closers[b[0]] - } - - if opening != '{' && opening != '[' { - continue // don't know how to concatenate non container objects - } - - const minLengthIfNotEmpty = 3 - if len(b) < minLengthIfNotEmpty { // yep empty but also the last one, so closing this thing - if i == last && a > 0 { - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - continue - } - - idx = 0 - if a > 0 { // we need to join with a comma for everything beyond the first non-empty item - if err := buf.WriteByte(comma); err != nil { - log.Println(err) - } - idx = 1 // this is not the first or the last so we want to drop the leading bracket - } - - if i != last { // not the last one, strip brackets - if _, err := buf.Write(b[idx : len(b)-1]); err != nil { - log.Println(err) - } - } else { // last one, strip only the leading bracket - if _, err := buf.Write(b[idx:]); err != nil { - log.Println(err) - } - } - a++ - } - // somehow it ended up being empty, so provide a default value - if buf.Len() == 0 { - if err := buf.WriteByte(opening); err != nil { - log.Println(err) - } - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - return buf.Bytes() -} - -// ToDynamicJSON turns an object into a properly JSON typed structure -func ToDynamicJSON(data interface{}) interface{} { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - var res interface{} - if err := json.Unmarshal(b, &res); err != nil { - log.Println(err) - } - return res -} - -// FromDynamicJSON turns an object into a properly JSON typed structure -func FromDynamicJSON(data, target interface{}) error { - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - return json.Unmarshal(b, target) -} - -// NameProvider represents an object capable of translating from go property names -// to json property names -// This type is thread-safe. -type NameProvider struct { - lock *sync.Mutex - index map[reflect.Type]nameIndex -} - -type nameIndex struct { - jsonNames map[string]string - goNames map[string]string -} - -// NewNameProvider creates a new name provider -func NewNameProvider() *NameProvider { - return &NameProvider{ - lock: &sync.Mutex{}, - index: make(map[reflect.Type]nameIndex), - } -} - -func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { - for i := 0; i < tpe.NumField(); i++ { - targetDes := tpe.Field(i) - - if targetDes.PkgPath != "" { // unexported - continue - } - - if targetDes.Anonymous { // walk embedded structures tree down first - buildnameIndex(targetDes.Type, idx, reverseIdx) - continue - } - - if tag := targetDes.Tag.Get("json"); tag != "" { - - parts := strings.Split(tag, ",") - if len(parts) == 0 { - continue - } - - nm := parts[0] - if nm == "-" { - continue - } - if nm == "" { // empty string means we want to use the Go name - nm = targetDes.Name - } - - idx[nm] = targetDes.Name - reverseIdx[targetDes.Name] = nm - } - } -} - -func newNameIndex(tpe reflect.Type) nameIndex { - var idx = make(map[string]string, tpe.NumField()) - var reverseIdx = make(map[string]string, tpe.NumField()) - - buildnameIndex(tpe, idx, reverseIdx) - return nameIndex{jsonNames: idx, goNames: reverseIdx} -} - -// GetJSONNames gets all the json property names for a type -func (n *NameProvider) GetJSONNames(subject interface{}) []string { - n.lock.Lock() - defer n.lock.Unlock() - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - - res := make([]string, 0, len(names.jsonNames)) - for k := range names.jsonNames { - res = append(res, k) - } - return res -} - -// GetJSONName gets the json name for a go property name -func (n *NameProvider) GetJSONName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetJSONNameForType(tpe, name) -} - -// GetJSONNameForType gets the json name for a go property name on a given type -func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.goNames[name] - return nme, ok -} - -func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { - names := newNameIndex(tpe) - n.index[tpe] = names - return names -} - -// GetGoName gets the go name for a json property name -func (n *NameProvider) GetGoName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetGoNameForType(tpe, name) -} - -// GetGoNameForType gets the go name for a given type for a json property name -func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.jsonNames[name] - return nme, ok -} diff --git a/api/vendor/github.com/go-openapi/swag/jsonname/LICENSE b/api/vendor/github.com/go-openapi/swag/jsonname/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonname/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/api/vendor/github.com/go-openapi/swag/jsonname/doc.go b/api/vendor/github.com/go-openapi/swag/jsonname/doc.go new file mode 100644 index 000000000000..79232eaca476 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonname/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package jsonname is a provider of json property names from go properties. +package jsonname diff --git a/api/vendor/github.com/go-openapi/swag/jsonname/name_provider.go b/api/vendor/github.com/go-openapi/swag/jsonname/name_provider.go new file mode 100644 index 000000000000..8eaf1bece8d6 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonname/name_provider.go @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonname + +import ( + "reflect" + "strings" + "sync" +) + +// DefaultJSONNameProvider is the default cache for types. +var DefaultJSONNameProvider = NewNameProvider() + +// NameProvider represents an object capable of translating from go property names +// to json property names. +// +// This type is thread-safe. +// +// See [github.com/go-openapi/jsonpointer.Pointer] for an example. +type NameProvider struct { + lock *sync.Mutex + index map[reflect.Type]nameIndex +} + +type nameIndex struct { + jsonNames map[string]string + goNames map[string]string +} + +// NewNameProvider creates a new name provider +func NewNameProvider() *NameProvider { + return &NameProvider{ + lock: &sync.Mutex{}, + index: make(map[reflect.Type]nameIndex), + } +} + +func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { + for i := 0; i < tpe.NumField(); i++ { + targetDes := tpe.Field(i) + + if targetDes.PkgPath != "" { // unexported + continue + } + + if targetDes.Anonymous { // walk embedded structures tree down first + buildnameIndex(targetDes.Type, idx, reverseIdx) + continue + } + + if tag := targetDes.Tag.Get("json"); tag != "" { + + parts := strings.Split(tag, ",") + if len(parts) == 0 { + continue + } + + nm := parts[0] + if nm == "-" { + continue + } + if nm == "" { // empty string means we want to use the Go name + nm = targetDes.Name + } + + idx[nm] = targetDes.Name + reverseIdx[targetDes.Name] = nm + } + } +} + +func newNameIndex(tpe reflect.Type) nameIndex { + var idx = make(map[string]string, tpe.NumField()) + var reverseIdx = make(map[string]string, tpe.NumField()) + + buildnameIndex(tpe, idx, reverseIdx) + return nameIndex{jsonNames: idx, goNames: reverseIdx} +} + +// GetJSONNames gets all the json property names for a type +func (n *NameProvider) GetJSONNames(subject any) []string { + n.lock.Lock() + defer n.lock.Unlock() + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + + res := make([]string, 0, len(names.jsonNames)) + for k := range names.jsonNames { + res = append(res, k) + } + return res +} + +// GetJSONName gets the json name for a go property name +func (n *NameProvider) GetJSONName(subject any, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetJSONNameForType(tpe, name) +} + +// GetJSONNameForType gets the json name for a go property name on a given type +func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.goNames[name] + return nme, ok +} + +// GetGoName gets the go name for a json property name +func (n *NameProvider) GetGoName(subject any, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetGoNameForType(tpe, name) +} + +// GetGoNameForType gets the go name for a given type for a json property name +func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.jsonNames[name] + return nme, ok +} + +func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { + names := newNameIndex(tpe) + n.index[tpe] = names + return names +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonname_iface.go b/api/vendor/github.com/go-openapi/swag/jsonname_iface.go new file mode 100644 index 000000000000..303a007f6f4c --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonname_iface.go @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "github.com/go-openapi/swag/jsonname" +) + +// DefaultJSONNameProvider is the default cache for types +// +// Deprecated: use [jsonname.DefaultJSONNameProvider] instead. +var DefaultJSONNameProvider = jsonname.DefaultJSONNameProvider + +// NameProvider represents an object capable of translating from go property names +// to json property names. +// +// Deprecated: use [jsonname.NameProvider] instead. +type NameProvider = jsonname.NameProvider + +// NewNameProvider creates a new name provider +// +// Deprecated: use [jsonname.NewNameProvider] instead. +func NewNameProvider() *NameProvider { return jsonname.NewNameProvider() } diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/LICENSE b/api/vendor/github.com/go-openapi/swag/jsonutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/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/api/vendor/github.com/go-openapi/swag/jsonutils/README.md b/api/vendor/github.com/go-openapi/swag/jsonutils/README.md new file mode 100644 index 000000000000..d745cdb466e2 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/README.md @@ -0,0 +1,108 @@ + # jsonutils + +`jsonutils` exposes a few tools to work with JSON: + +- a fast, simple `Concat` to concatenate (not merge) JSON objects and arrays +- `FromDynamicJSON` to convert a data structure into a "dynamic JSON" data structure +- `ReadJSON` and `WriteJSON` behave like `json.Unmarshal` and `json.Marshal`, + with the ability to use another underlying serialization library through an `Adapter` + configured at runtime +- a `JSONMapSlice` structure that may be used to store JSON objects with the order of keys maintained + +## Dynamic JSON + +We call "dynamic JSON" the go data structure that results from unmarshaling JSON like this: + +```go + var value any + jsonBytes := `{"a": 1, ... }` + _ = json.Unmarshal(jsonBytes, &value) +``` + +In this configuration, the standard library mappings are as follows: + +| JSON | go | +|-----------|------------------| +| `number` | `float64` | +| `string` | `string` | +| `boolean` | `bool` | +| `null` | `nil` | +| `object` | `map[string]any` | +| `array` | `[]any` | + +## Map slices + +When using `JSONMapSlice`, the ordering of keys is ensured by replacing +mappings to `map[string]any` by a `JSONMapSlice` which is an (ordered) +slice of `JSONMapItem`s. + +Notice that a similar feature is available for YAML (see [`yamlutils`](../yamlutils)), +with a `YAMLMapSlice` type based on the `JSONMapSlice`. + +`JSONMapSlice` is similar to an ordered map, but the keys are not retrieved +in constant time. + +Another difference with the the above standard mappings is that numbers don't always map +to a `float64`: if the value is a JSON integer, it unmarshals to `int64`. + +See also [some examples](https://pkg.go.dev/github.com/go-openapi/swag/jsonutils#pkg-examples) + +## Adapters + +`ReadJSON`, `WriteJSON` and `FromDynamicJSON` (which is a combination of the latter two) +are wrappers on top of `json.Unmarshal` and `json.Marshal`. + +By default, the adapter merely wraps the standard library. + +The adapter may be used to register other JSON serialization libraries, +possibly several ones at the same time. + +If the value passed is identified as an "ordered map" (i.e. implements `ifaces.Ordered` +or `ifaces.SetOrdered`, the adapter favors the "ordered" JSON behavior and tries to +find a registered implementation that support ordered keys in objects. + +Our standard library implementation supports this. + +As of `v0.25.0`, we support through such an adapter the popular `mailru/easyjson` +library, which kicks in when the passed values support the `easyjson.Unmarshaler` +or `easyjson.Marshaler` interfaces. + +In the future, we plan to add more similar libraries that compete on the go JSON +serializers scene. + +## Registering an adapter + +In package `github.com/go-openapi/swag/easyjson/adapters`, several adapters are available. + +Each adapter is an independent go module. Hence you'll pick its dependencies only if you import it. + +At this moment we provide: +* `stdlib`: JSON adapter based on the standard library +* `easyjson`: JSON adapter based on the `github.com/mailru/easyjson` + +The adapters provide the basic `Marshal` and `Unmarshal` capabilities, plus an implementation +of the `MapSlice` pattern. + +You may also build your own adapter based on your specific use-case. An adapter is not required to implement +all capabilities. + +Every adapter comes with a `Register` function, possibly with some options, to register the adapter +to a global registry. + +For example, to enable `easyjson` to be used in `ReadJSON` and `WriteJSON`, you would write something like: + +```go + import ( + "github.com/go-openapi/swag/jsonutils/adapters" + easyjson "github.com/go-openapi/swag/jsonutils/adapters/easyjson/json" + ) + + func init() { + easyjson.Register(adapters.Registry) + } +``` + +You may register several adapters. In this case, capability matching is evaluated from the last registered +adapters (LIFO). + +## [Benchmarks](./adapters/testintegration/benchmarks/README.md) diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go new file mode 100644 index 000000000000..76d3898fca5e --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go @@ -0,0 +1,8 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package adapters exposes a registry of adapters to multiple +// JSON serialization libraries. +// +// All interfaces are defined in package [ifaces.Adapter]. +package adapters diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go new file mode 100644 index 000000000000..1fd43a1fad51 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package ifaces exposes all interfaces to work with adapters. +package ifaces diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go new file mode 100644 index 000000000000..7805e5e5e398 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package ifaces + +import ( + _ "encoding/json" // for documentation purpose + "iter" +) + +// Ordered knows how to iterate over the (key,value) pairs of a JSON object. +type Ordered interface { + OrderedItems() iter.Seq2[string, any] +} + +// SetOrdered knows how to append or update the keys of a JSON object, +// given an iterator over (key,value) pairs. +// +// If the provided iterator is nil then the receiver should be set to nil. +type SetOrdered interface { + SetOrderedItems(iter.Seq2[string, any]) +} + +// OrderedMap represent a JSON object (i.e. like a map[string,any]), +// and knows how to serialize and deserialize JSON with the order of keys maintained. +type OrderedMap interface { + Ordered + SetOrdered + + OrderedMarshalJSON() ([]byte, error) + OrderedUnmarshalJSON([]byte) error +} + +// MarshalAdapter behaves likes the standard library [json.Marshal]. +type MarshalAdapter interface { + Poolable + + Marshal(any) ([]byte, error) +} + +// OrderedMarshalAdapter behaves likes the standard library [json.Marshal], preserving the order of keys in objects. +type OrderedMarshalAdapter interface { + Poolable + + OrderedMarshal(Ordered) ([]byte, error) +} + +// UnmarshalAdapter behaves likes the standard library [json.Unmarshal]. +type UnmarshalAdapter interface { + Poolable + + Unmarshal([]byte, any) error +} + +// OrderedUnmarshalAdapter behaves likes the standard library [json.Unmarshal], preserving the order of keys in objects. +type OrderedUnmarshalAdapter interface { + Poolable + + OrderedUnmarshal([]byte, SetOrdered) error +} + +// Adapter exposes an interface like the standard [json] library. +type Adapter interface { + MarshalAdapter + UnmarshalAdapter + + OrderedAdapter +} + +// OrderedAdapter exposes interfaces to process JSON and keep the order of object keys. +type OrderedAdapter interface { + OrderedMarshalAdapter + OrderedUnmarshalAdapter + NewOrderedMap(capacity int) OrderedMap +} + +type Poolable interface { + // Self-redeem: for [Adapter] s that are allocated from a pool. + // The [Adapter] must not be used after calling [Redeem]. + Redeem() + + // Reset the state of the [Adapter], if any. + Reset() +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go new file mode 100644 index 000000000000..2d6c69f4e602 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package ifaces + +import ( + "strings" +) + +// Capability indicates what a JSON adapter is capable of. +type Capability uint8 + +const ( + CapabilityMarshalJSON Capability = 1 << iota + CapabilityUnmarshalJSON + CapabilityOrderedMarshalJSON + CapabilityOrderedUnmarshalJSON + CapabilityOrderedMap +) + +func (c Capability) String() string { + switch c { + case CapabilityMarshalJSON: + return "MarshalJSON" + case CapabilityUnmarshalJSON: + return "UnmarshalJSON" + case CapabilityOrderedMarshalJSON: + return "OrderedMarshalJSON" + case CapabilityOrderedUnmarshalJSON: + return "OrderedUnmarshalJSON" + case CapabilityOrderedMap: + return "OrderedMap" + default: + return "" + } +} + +// Capabilities holds several unitary capability flags +type Capabilities uint8 + +// Has some capability flag enabled. +func (c Capabilities) Has(capability Capability) bool { + return Capability(c)&capability > 0 +} + +func (c Capabilities) String() string { + var w strings.Builder + + first := true + for _, capability := range []Capability{ + CapabilityMarshalJSON, + CapabilityUnmarshalJSON, + CapabilityOrderedMarshalJSON, + CapabilityOrderedUnmarshalJSON, + CapabilityOrderedMap, + } { + if c.Has(capability) { + if !first { + w.WriteByte('|') + } else { + first = false + } + w.WriteString(capability.String()) + } + } + + return w.String() +} + +const ( + AllCapabilities Capabilities = Capabilities(uint8(CapabilityMarshalJSON) | + uint8(CapabilityUnmarshalJSON) | + uint8(CapabilityOrderedMarshalJSON) | + uint8(CapabilityOrderedUnmarshalJSON) | + uint8(CapabilityOrderedMap)) + + AllUnorderedCapabilities Capabilities = Capabilities(uint8(CapabilityMarshalJSON) | uint8(CapabilityUnmarshalJSON)) +) + +// RegistryEntry describes how any given adapter registers its capabilities to the [Registrar]. +type RegistryEntry struct { + Who string + What Capabilities + Constructor func() Adapter + Support func(what Capability, value any) bool +} + +// Registrar is a type that knows how to keep registration calls from adapters. +type Registrar interface { + RegisterFor(RegistryEntry) +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go new file mode 100644 index 000000000000..3062acaff261 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package adapters + +import ( + "fmt" + "reflect" + "slices" + "sync" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" + stdlib "github.com/go-openapi/swag/jsonutils/adapters/stdlib/json" +) + +// Registry holds the global registry for registered adapters. +var Registry = NewRegistrar() + +var ( + defaultRegistered = stdlib.Register + + _ ifaces.Registrar = &Registrar{} +) + +type registryError string + +func (e registryError) Error() string { + return string(e) +} + +// ErrRegistry indicates an error returned by the [Registrar]. +var ErrRegistry registryError = "JSON adapters registry error" + +type registry []*ifaces.RegistryEntry + +// Registrar holds registered [ifaces.Adapters] for different serialization capabilities. +// +// Internally, it maintains a cache for data types that favor a given adapter. +type Registrar struct { + marshalerRegistry registry + unmarshalerRegistry registry + orderedMarshalerRegistry registry + orderedUnmarshalerRegistry registry + orderedMapRegistry registry + + gmx sync.RWMutex + + // cache indexed by value type, so we don't have to lookup + marshalerCache map[reflect.Type]*ifaces.RegistryEntry + unmarshalerCache map[reflect.Type]*ifaces.RegistryEntry + orderedMarshalerCache map[reflect.Type]*ifaces.RegistryEntry + orderedUnmarshalerCache map[reflect.Type]*ifaces.RegistryEntry + orderedMapCache map[reflect.Type]*ifaces.RegistryEntry +} + +func NewRegistrar() *Registrar { + r := &Registrar{} + + r.marshalerRegistry = make(registry, 0, 1) + r.unmarshalerRegistry = make(registry, 0, 1) + r.orderedMarshalerRegistry = make(registry, 0, 1) + r.orderedUnmarshalerRegistry = make(registry, 0, 1) + r.orderedMapRegistry = make(registry, 0, 1) + + r.marshalerCache = make(map[reflect.Type]*ifaces.RegistryEntry) + r.unmarshalerCache = make(map[reflect.Type]*ifaces.RegistryEntry) + r.orderedMarshalerCache = make(map[reflect.Type]*ifaces.RegistryEntry) + r.orderedUnmarshalerCache = make(map[reflect.Type]*ifaces.RegistryEntry) + r.orderedMapCache = make(map[reflect.Type]*ifaces.RegistryEntry) + + defaultRegistered(r) + + return r +} + +// ClearCache resets the internal type cache. +func (r *Registrar) ClearCache() { + r.gmx.Lock() + r.clearCache() + r.gmx.Unlock() +} + +// Reset the [Registrar] to its defaults. +func (r *Registrar) Reset() { + r.gmx.Lock() + r.clearCache() + r.marshalerRegistry = r.marshalerRegistry[:0] + r.unmarshalerRegistry = r.unmarshalerRegistry[:0] + r.orderedMarshalerRegistry = r.orderedMarshalerRegistry[:0] + r.orderedUnmarshalerRegistry = r.orderedUnmarshalerRegistry[:0] + r.orderedMapRegistry = r.orderedMapRegistry[:0] + r.gmx.Unlock() + + defaultRegistered(r) +} + +// RegisterFor registers an adapter for some JSON capabilities. +func (r *Registrar) RegisterFor(entry ifaces.RegistryEntry) { + r.gmx.Lock() + if entry.What.Has(ifaces.CapabilityMarshalJSON) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityMarshalJSON) + r.marshalerRegistry = slices.Insert(r.marshalerRegistry, 0, &e) + } + if entry.What.Has(ifaces.CapabilityUnmarshalJSON) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityUnmarshalJSON) + r.unmarshalerRegistry = slices.Insert(r.unmarshalerRegistry, 0, &e) + } + if entry.What.Has(ifaces.CapabilityOrderedMarshalJSON) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityOrderedMarshalJSON) + r.orderedMarshalerRegistry = slices.Insert(r.orderedMarshalerRegistry, 0, &e) + } + if entry.What.Has(ifaces.CapabilityOrderedUnmarshalJSON) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityOrderedUnmarshalJSON) + r.orderedUnmarshalerRegistry = slices.Insert(r.orderedUnmarshalerRegistry, 0, &e) + } + if entry.What.Has(ifaces.CapabilityOrderedMap) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityOrderedMap) + r.orderedMapRegistry = slices.Insert(r.orderedMapRegistry, 0, &e) + } + r.gmx.Unlock() +} + +// AdapterFor returns an [ifaces.Adapter] that supports this capability for this type of value. +// +// The [ifaces.Adapter] may be redeemed to its pool using its Redeem() method, for adapters that support global +// pooling. When this is not the case, the redeem function is just a no-operation. +func (r *Registrar) AdapterFor(capability ifaces.Capability, value any) ifaces.Adapter { + entry := r.findFirstFor(capability, value) + if entry == nil { + return nil + } + + return entry.Constructor() +} + +func (r *Registrar) clearCache() { + clear(r.marshalerCache) + clear(r.unmarshalerCache) + clear(r.orderedMarshalerCache) + clear(r.orderedUnmarshalerCache) + clear(r.orderedMapCache) +} + +func (r *Registrar) findFirstFor(capability ifaces.Capability, value any) *ifaces.RegistryEntry { + switch capability { + case ifaces.CapabilityMarshalJSON: + return r.findFirstInRegistryFor(r.marshalerRegistry, r.marshalerCache, capability, value) + case ifaces.CapabilityUnmarshalJSON: + return r.findFirstInRegistryFor(r.unmarshalerRegistry, r.unmarshalerCache, capability, value) + case ifaces.CapabilityOrderedMarshalJSON: + return r.findFirstInRegistryFor(r.orderedMarshalerRegistry, r.orderedMarshalerCache, capability, value) + case ifaces.CapabilityOrderedUnmarshalJSON: + return r.findFirstInRegistryFor(r.orderedUnmarshalerRegistry, r.orderedUnmarshalerCache, capability, value) + case ifaces.CapabilityOrderedMap: + return r.findFirstInRegistryFor(r.orderedMapRegistry, r.orderedMapCache, capability, value) + default: + panic(fmt.Errorf("unsupported capability %d: %w", capability, ErrRegistry)) + } +} + +func (r *Registrar) findFirstInRegistryFor(reg registry, cache map[reflect.Type]*ifaces.RegistryEntry, capability ifaces.Capability, value any) *ifaces.RegistryEntry { + r.gmx.RLock() + if len(reg) > 1 { + if entry, ok := cache[reflect.TypeOf(value)]; ok { + // cache hit + r.gmx.RUnlock() + return entry + } + } + + for _, entry := range reg { + if !entry.Support(capability, value) { + continue + } + + r.gmx.RUnlock() + + // update the internal cache + r.gmx.Lock() + cache[reflect.TypeOf(value)] = entry + r.gmx.Unlock() + + return entry + } + + // no adapter found + r.gmx.RUnlock() + + return nil +} + +// MarshalAdapterFor returns the first adapter that knows how to Marshal this type of value. +func MarshalAdapterFor(value any) ifaces.MarshalAdapter { + return Registry.AdapterFor(ifaces.CapabilityMarshalJSON, value) +} + +// OrderedMarshalAdapterFor returns the first adapter that knows how to OrderedMarshal this type of value. +func OrderedMarshalAdapterFor(value ifaces.Ordered) ifaces.OrderedMarshalAdapter { + return Registry.AdapterFor(ifaces.CapabilityOrderedMarshalJSON, value) +} + +// UnmarshalAdapterFor returns the first adapter that knows how to Unmarshal this type of value. +func UnmarshalAdapterFor(value any) ifaces.UnmarshalAdapter { + return Registry.AdapterFor(ifaces.CapabilityUnmarshalJSON, value) +} + +// OrderedUnmarshalAdapterFor provides the first adapter that knows how to OrderedUnmarshal this type of value. +func OrderedUnmarshalAdapterFor(value ifaces.SetOrdered) ifaces.OrderedUnmarshalAdapter { + return Registry.AdapterFor(ifaces.CapabilityOrderedUnmarshalJSON, value) +} + +// NewOrderedMap provides the "ordered map" implementation provided by the registry. +func NewOrderedMap(capacity int) ifaces.OrderedMap { + var v any + adapter := Registry.AdapterFor(ifaces.CapabilityOrderedUnmarshalJSON, v) + if adapter == nil { + return nil + } + + defer adapter.Redeem() + return adapter.NewOrderedMap(capacity) +} + +func noopRedeemer() {} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go new file mode 100644 index 000000000000..0213ff5c29f1 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + stdjson "encoding/json" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" + "github.com/go-openapi/swag/typeutils" +) + +const sensibleBufferSize = 8192 + +type jsonError string + +func (e jsonError) Error() string { + return string(e) +} + +// ErrStdlib indicates that an error comes from the stdlib JSON adapter +var ErrStdlib jsonError = "error from the JSON adapter stdlib" + +var _ ifaces.Adapter = &Adapter{} + +type Adapter struct { +} + +// NewAdapter yields an [ifaces.Adapter] using the standard library. +func NewAdapter() *Adapter { + return &Adapter{} +} + +func (a *Adapter) Marshal(value any) ([]byte, error) { + return stdjson.Marshal(value) +} + +func (a *Adapter) Unmarshal(data []byte, value any) error { + return stdjson.Unmarshal(data, value) +} + +func (a *Adapter) OrderedMarshal(value ifaces.Ordered) ([]byte, error) { + w := poolOfWriters.Borrow() + defer func() { + poolOfWriters.Redeem(w) + }() + + if typeutils.IsNil(value) { + w.RawString("null") + + return w.BuildBytes() + } + + w.RawByte('{') + first := true + for k, v := range value.OrderedItems() { + if first { + first = false + } else { + w.RawByte(',') + } + + w.String(k) + w.RawByte(':') + + switch val := v.(type) { + case ifaces.Ordered: + w.Raw(a.OrderedMarshal(val)) + default: + w.Raw(stdjson.Marshal(v)) + } + } + + w.RawByte('}') + + return w.BuildBytes() +} + +func (a *Adapter) OrderedUnmarshal(data []byte, value ifaces.SetOrdered) error { + var m MapSlice + if err := m.OrderedUnmarshalJSON(data); err != nil { + return err + } + + if typeutils.IsNil(m) { + // force input value to nil + value.SetOrderedItems(nil) + + return nil + } + + value.SetOrderedItems(m.OrderedItems()) + + return nil +} + +func (a *Adapter) NewOrderedMap(capacity int) ifaces.OrderedMap { + m := make(MapSlice, 0, capacity) + + return &m +} + +// Redeem the [Adapter] when it comes from a pool. +// +// The adapter becomes immediately unusable once redeemed. +func (a *Adapter) Redeem() { + if a == nil { + return + } + + RedeemAdapter(a) +} + +func (a *Adapter) Reset() { +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go new file mode 100644 index 000000000000..5ea1b4404252 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package json implements an [ifaces.Adapter] using the standard library. +package json diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go new file mode 100644 index 000000000000..b5aa1c7972e7 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go @@ -0,0 +1,320 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + stdjson "encoding/json" + "errors" + "fmt" + "io" + "math" + "strconv" + + "github.com/go-openapi/swag/conv" +) + +type token struct { + stdjson.Token +} + +func (t token) String() string { + if t == invalidToken { + return "invalid token" + } + if t == eofToken { + return "EOF" + } + + return fmt.Sprintf("%v", t.Token) +} + +func (t token) Kind() tokenKind { + switch t.Token.(type) { + case nil: + return tokenNull + case stdjson.Delim: + return tokenDelim + case bool: + return tokenBool + case float64: + return tokenFloat + case stdjson.Number: + return tokenNumber + case string: + return tokenString + default: + return tokenUndef + } +} + +func (t token) Delim() byte { + r, ok := t.Token.(stdjson.Delim) + if !ok { + return 0 + } + + return byte(r) +} + +type tokenKind uint8 + +const ( + tokenUndef tokenKind = iota + tokenString + tokenNumber + tokenFloat + tokenBool + tokenNull + tokenDelim +) + +var ( + invalidToken = token{ + Token: stdjson.Token(struct{}{}), + } + + eofToken = token{ + Token: stdjson.Token(&struct{}{}), + } + + undefToken = token{ + Token: stdjson.Token(uint8(0)), + } +) + +// jlexer apes easyjson's jlexer, but uses the standard library decoder under the hood. +type jlexer struct { + buf *bytesReader + dec *stdjson.Decoder + err error + // current token + next token + // started bool +} + +type bytesReader struct { + buf []byte + offset int +} + +func (b *bytesReader) Reset() { + b.buf = nil + b.offset = 0 +} + +func (b *bytesReader) Read(p []byte) (int, error) { + if b.offset >= len(b.buf) { + return 0, io.EOF + } + + n := len(p) + buf := b.buf[b.offset:] + m := len(buf) + + if n >= m { + copy(p, buf) + b.offset += m + + return m, nil + } + + copy(p, buf[:n]) + b.offset += n + + return n, nil +} + +var _ io.Reader = &bytesReader{} + +func newLexer(data []byte) *jlexer { + l := &jlexer{ + // current: undefToken, + next: undefToken, + } + l.buf = &bytesReader{ + buf: data, + } + l.dec = stdjson.NewDecoder(l.buf) // unfortunately, cannot pool this + + return l +} + +func (l *jlexer) Reset() { + l.err = nil + l.next = undefToken + // leave l.dec and l.buf alone, since they are replaced at every Borrow +} + +func (l *jlexer) Error() error { + return l.err +} + +func (l *jlexer) SetErr(err error) { + l.err = err +} + +func (l *jlexer) Ok() bool { + return l.err == nil +} + +// NextToken consumes a token +func (l *jlexer) NextToken() token { + if !l.Ok() { + return invalidToken + } + + if l.next != undefToken { + next := l.next + l.next = undefToken + + return next + } + + return l.fetchToken() +} + +// PeekToken returns the next token without consuming it +func (l *jlexer) PeekToken() token { + if l.next == undefToken { + l.next = l.fetchToken() + } + + return l.next +} + +func (l *jlexer) Skip() { + _ = l.NextToken() +} + +func (l *jlexer) IsDelim(c byte) bool { + if !l.Ok() { + return false + } + + next := l.PeekToken() + if next.Kind() != tokenDelim { + return false + } + + if next.Delim() != c { + return false + } + + return true +} + +func (l *jlexer) IsNull() bool { + if !l.Ok() { + return false + } + + next := l.PeekToken() + + return next.Kind() == tokenNull +} + +func (l *jlexer) Delim(c byte) { + if !l.Ok() { + return + } + + tok := l.NextToken() + if tok.Kind() != tokenDelim { + l.err = fmt.Errorf("expected a delimiter token but got '%v': %w", tok, ErrStdlib) + + return + } + + if tok.Delim() != c { + l.err = fmt.Errorf("expected delimiter '%q' but got '%q': %w", c, tok.Delim(), ErrStdlib) + } +} + +func (l *jlexer) Null() { + if !l.Ok() { + return + } + + tok := l.NextToken() + if tok.Kind() != tokenNull { + l.err = fmt.Errorf("expected a null token but got '%v': %w", tok, ErrStdlib) + } +} + +func (l *jlexer) Number() any { + if !l.Ok() { + return 0 + } + + tok := l.NextToken() + + switch tok.Kind() { //nolint:exhaustive + case tokenNumber: + n := tok.Token.(stdjson.Number).String() + f, _ := strconv.ParseFloat(n, 64) + if conv.IsFloat64AJSONInteger(f) { + return int64(math.Trunc(f)) + } + + return f + + case tokenFloat: + f := tok.Token.(float64) + if conv.IsFloat64AJSONInteger(f) { + return int64(math.Trunc(f)) + } + + return f + + default: + l.err = fmt.Errorf("expected a number token but got '%v': %w", tok, ErrStdlib) + + return 0 + } +} + +func (l *jlexer) Bool() bool { + if !l.Ok() { + return false + } + + tok := l.NextToken() + if tok.Kind() != tokenBool { + l.err = fmt.Errorf("expected a bool token but got '%v': %w", tok, ErrStdlib) + + return false + } + + return tok.Token.(bool) +} + +func (l *jlexer) String() string { + if !l.Ok() { + return "" + } + + tok := l.NextToken() + if tok.Kind() != tokenString { + l.err = fmt.Errorf("expected a string token but got '%v': %w", tok, ErrStdlib) + + return "" + } + + return tok.Token.(string) +} + +// Commas and colons are elided. +func (l *jlexer) fetchToken() token { + jtok, err := l.dec.Token() + if err != nil { + if errors.Is(err, io.EOF) { + return eofToken + } + + l.err = errors.Join(err, ErrStdlib) + return invalidToken + } + + return token{Token: jtok} +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go new file mode 100644 index 000000000000..54deef406f33 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go @@ -0,0 +1,266 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + stdjson "encoding/json" + "fmt" + "iter" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" +) + +var _ ifaces.OrderedMap = &MapSlice{} + +// MapSlice represents a JSON object, with the order of keys maintained. +type MapSlice []MapItem + +func (s MapSlice) OrderedItems() iter.Seq2[string, any] { + return func(yield func(string, any) bool) { + for _, item := range s { + if !yield(item.Key, item.Value) { + return + } + } + } +} + +func (s *MapSlice) SetOrderedItems(items iter.Seq2[string, any]) { + if items == nil { + *s = nil + + return + } + + m := *s + if len(m) > 0 { + // update mode + idx := make(map[string]int, len(m)) + + for i, item := range m { + idx[item.Key] = i + } + + for k, v := range items { + idx, ok := idx[k] + if ok { + m[idx].Value = v + + continue + } + m = append(m, MapItem{Key: k, Value: v}) + } + + *s = m + + return + } + + for k, v := range items { + m = append(m, MapItem{Key: k, Value: v}) + } + + *s = m +} + +// MarshalJSON renders a [MapSlice] as JSON bytes, preserving the order of keys. +func (s MapSlice) MarshalJSON() ([]byte, error) { + return s.OrderedMarshalJSON() +} + +func (s MapSlice) OrderedMarshalJSON() ([]byte, error) { + w := poolOfWriters.Borrow() + defer func() { + poolOfWriters.Redeem(w) + }() + + s.marshalObject(w) + + return w.BuildBytes() // this clones data, so it's okay to redeem the writer and its buffer +} + +// UnmarshalJSON builds a [MapSlice] from JSON bytes, preserving the order of keys. +// +// Inner objects are unmarshaled as [MapSlice] slices and not map[string]any. +func (s *MapSlice) UnmarshalJSON(data []byte) error { + return s.OrderedUnmarshalJSON(data) +} + +func (s *MapSlice) OrderedUnmarshalJSON(data []byte) error { + l := poolOfLexers.Borrow(data) + defer func() { + poolOfLexers.Redeem(l) + }() + + s.unmarshalObject(l) + + return l.Error() +} + +func (s MapSlice) marshalObject(w *jwriter) { + if s == nil { + w.RawString("null") + + return + } + + w.RawByte('{') + + if len(s) == 0 { + w.RawByte('}') + + return + } + + s[0].marshalJSON(w) + + for i := 1; i < len(s); i++ { + w.RawByte(',') + s[i].marshalJSON(w) + } + + w.RawByte('}') +} + +func (s *MapSlice) unmarshalObject(in *jlexer) { + if in.IsNull() { + in.Skip() + + return + } + + in.Delim('{') // consume token + if !in.Ok() { + return + } + + result := make(MapSlice, 0) + + for in.Ok() && !in.IsDelim('}') { + var mi MapItem + + mi.unmarshalKeyValue(in) + result = append(result, mi) + } + + in.Delim('}') + + if !in.Ok() { + return + } + + *s = result +} + +// MapItem represents the value of a key in a JSON object held by [MapSlice]. +// +// Notice that [MapItem] should not be marshaled to or unmarshaled from JSON directly, +// use this type as part of a [MapSlice] when dealing with JSON bytes. +type MapItem struct { + Key string + Value any +} + +func (s MapItem) marshalJSON(w *jwriter) { + w.String(s.Key) + w.RawByte(':') + w.Raw(stdjson.Marshal(s.Value)) +} + +func (s *MapItem) unmarshalKeyValue(in *jlexer) { + key := in.String() // consume string + value := s.asInterface(in) // consume any value, including termination tokens '}' or ']' + + if !in.Ok() { + return + } + + s.Key = key + s.Value = value +} + +func (s *MapItem) unmarshalArray(in *jlexer) []any { + if in.IsNull() { + in.Skip() + + return nil + } + + in.Delim('[') // consume token + if !in.Ok() { + return nil + } + + ret := make([]any, 0) + + for in.Ok() && !in.IsDelim(']') { + ret = append(ret, s.asInterface(in)) + } + + in.Delim(']') + if !in.Ok() { + return nil + } + + return ret +} + +// asInterface is very much like [jlexer.Lexer.Interface], but unmarshals an object +// into a [MapSlice], not a map[string]any. +// +// We have to force parsing errors somehow, since [jlexer.Lexer] doesn't let us +// set a parsing error directly. +func (s *MapItem) asInterface(in *jlexer) any { + if !in.Ok() { + return nil + } + + tok := in.PeekToken() // look-ahead what the next token looks like + kind := tok.Kind() + + switch kind { + case tokenString: + return in.String() // consume string + + case tokenNumber, tokenFloat: + return in.Number() + + case tokenBool: + return in.Bool() + + case tokenNull: + in.Null() + + return nil + + case tokenDelim: + switch tok.Delim() { + case '{': // not consumed yet + ret := make(MapSlice, 0) + ret.unmarshalObject(in) // consumes the terminating '}' + + if in.Ok() { + return ret + } + + // lexer is in an error state: will exhaust + return nil + + case '[': // not consumed yet + return s.unmarshalArray(in) // consumes the terminating ']' + default: + in.SetErr(fmt.Errorf("unexpected delimiter: %v: %w", tok, ErrStdlib)) // force error + return nil + } + + case tokenUndef: + fallthrough + default: + if in.Ok() { + in.SetErr(fmt.Errorf("unexpected token: %v: %w", tok, ErrStdlib)) // force error + } + + return nil + } +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go new file mode 100644 index 000000000000..709b97c3046b --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + "encoding/json" + "sync" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" +) + +type adaptersPool struct { + sync.Pool +} + +func (p *adaptersPool) Borrow() *Adapter { + return p.Get().(*Adapter) +} + +func (p *adaptersPool) BorrowIface() ifaces.Adapter { + return p.Get().(*Adapter) +} + +func (p *adaptersPool) Redeem(a *Adapter) { + p.Put(a) +} + +type writersPool struct { + sync.Pool +} + +func (p *writersPool) Borrow() *jwriter { + ptr := p.Get() + + jw := ptr.(*jwriter) + jw.Reset() + + return jw +} + +func (p *writersPool) Redeem(w *jwriter) { + p.Put(w) +} + +type lexersPool struct { + sync.Pool +} + +func (p *lexersPool) Borrow(data []byte) *jlexer { + ptr := p.Get() + + l := ptr.(*jlexer) + l.buf = poolOfReaders.Borrow(data) + l.dec = json.NewDecoder(l.buf) // cannot pool, not exposed by the encoding/json API + l.Reset() + + return l +} + +func (p *lexersPool) Redeem(l *jlexer) { + l.dec = nil + discard := l.buf + l.buf = nil + poolOfReaders.Redeem(discard) + p.Put(l) +} + +type readersPool struct { + sync.Pool +} + +func (p *readersPool) Borrow(data []byte) *bytesReader { + ptr := p.Get() + + b := ptr.(*bytesReader) + b.Reset() + b.buf = data + + return b +} + +func (p *readersPool) Redeem(b *bytesReader) { + p.Put(b) +} + +var ( + poolOfAdapters = &adaptersPool{ + Pool: sync.Pool{ + New: func() any { + return NewAdapter() + }, + }, + } + + poolOfWriters = &writersPool{ + Pool: sync.Pool{ + New: func() any { + return newJWriter() + }, + }, + } + + poolOfLexers = &lexersPool{ + Pool: sync.Pool{ + New: func() any { + return newLexer(nil) + }, + }, + } + + poolOfReaders = &readersPool{ + Pool: sync.Pool{ + New: func() any { + return &bytesReader{} + }, + }, + } +) + +// BorrowAdapter borrows an [Adapter] from the pool, recycling already allocated instances. +func BorrowAdapter() *Adapter { + return poolOfAdapters.Borrow() +} + +// BorrowAdapterIface borrows a stdlib [Adapter] and converts it directly +// to [ifaces.Adapter]. This is useful to avoid further allocations when +// translating the concrete type into an interface. +func BorrowAdapterIface() ifaces.Adapter { + return poolOfAdapters.BorrowIface() +} + +// RedeemAdapter redeems an [Adapter] to the pool, so it may be recycled. +func RedeemAdapter(a *Adapter) { + poolOfAdapters.Redeem(a) +} + +func RedeemAdapterIface(a ifaces.Adapter) { + concrete, ok := a.(*Adapter) + if ok { + poolOfAdapters.Redeem(concrete) + } +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go new file mode 100644 index 000000000000..fc8818694eae --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + "fmt" + "reflect" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" +) + +func Register(dispatcher ifaces.Registrar) { + t := reflect.TypeOf(Adapter{}) + dispatcher.RegisterFor( + ifaces.RegistryEntry{ + Who: fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()), + What: ifaces.AllCapabilities, + Constructor: BorrowAdapterIface, + Support: support, + }) +} + +func support(_ ifaces.Capability, _ any) bool { + return true +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go new file mode 100644 index 000000000000..dc2325c1a30f --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + "bytes" + "encoding/json" + "strings" +) + +type jwriter struct { + buf *bytes.Buffer + err error +} + +func newJWriter() *jwriter { + buf := make([]byte, 0, sensibleBufferSize) + + return &jwriter{buf: bytes.NewBuffer(buf)} +} + +func (w *jwriter) Reset() { + w.buf.Reset() + w.err = nil +} + +func (w *jwriter) RawString(s string) { + if w.err != nil { + return + } + w.buf.WriteString(s) +} + +func (w *jwriter) Raw(b []byte, err error) { + if w.err != nil { + return + } + if err != nil { + w.err = err + return + } + + _, _ = w.buf.Write(b) +} + +func (w *jwriter) RawByte(c byte) { + if w.err != nil { + return + } + w.buf.WriteByte(c) +} + +var quoteReplacer = strings.NewReplacer(`"`, `\"`, `\`, `\\`) + +func (w *jwriter) String(s string) { + if w.err != nil { + return + } + // escape quotes and \ + s = quoteReplacer.Replace(s) + + _ = w.buf.WriteByte('"') + json.HTMLEscape(w.buf, []byte(s)) + _ = w.buf.WriteByte('"') +} + +// BuildBytes returns a clone of the internal buffer. +func (w *jwriter) BuildBytes() ([]byte, error) { + if w.err != nil { + return nil, w.err + } + + return bytes.Clone(w.buf.Bytes()), nil +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/concat.go b/api/vendor/github.com/go-openapi/swag/jsonutils/concat.go new file mode 100644 index 000000000000..2068503af05b --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/concat.go @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonutils + +import ( + "bytes" +) + +// nullJSON represents a JSON object with null type +var nullJSON = []byte("null") + +const comma = byte(',') + +var closers map[byte]byte + +func init() { + closers = map[byte]byte{ + '{': '}', + '[': ']', + } +} + +// ConcatJSON concatenates multiple json objects or arrays efficiently. +// +// Note that [ConcatJSON] performs a very simple (and fast) concatenation +// operation: it does not attempt to merge objects. +func ConcatJSON(blobs ...[]byte) []byte { + if len(blobs) == 0 { + return nil + } + + last := len(blobs) - 1 + for blobs[last] == nil || bytes.Equal(blobs[last], nullJSON) { + // strips trailing null objects + last-- + if last < 0 { + // there was nothing but "null"s or nil... + return nil + } + } + if last == 0 { + return blobs[0] + } + + var opening, closing byte + var idx, a int + buf := bytes.NewBuffer(nil) + + for i, b := range blobs[:last+1] { + if b == nil || bytes.Equal(b, nullJSON) { + // a null object is in the list: skip it + continue + } + if len(b) > 0 && opening == 0 { // is this an array or an object? + opening, closing = b[0], closers[b[0]] + } + + if opening != '{' && opening != '[' { + continue // don't know how to concatenate non container objects + } + + const minLengthIfNotEmpty = 3 + if len(b) < minLengthIfNotEmpty { // yep empty but also the last one, so closing this thing + if i == last && a > 0 { + _ = buf.WriteByte(closing) // never returns err != nil + } + continue + } + + idx = 0 + if a > 0 { // we need to join with a comma for everything beyond the first non-empty item + _ = buf.WriteByte(comma) // never returns err != nil + idx = 1 // this is not the first or the last so we want to drop the leading bracket + } + + if i != last { // not the last one, strip brackets + _, _ = buf.Write(b[idx : len(b)-1]) // never returns err != nil + } else { // last one, strip only the leading bracket + _, _ = buf.Write(b[idx:]) + } + a++ + } + + // somehow it ended up being empty, so provide a default value + if buf.Len() == 0 && (opening == '{' || opening == '[') { + _ = buf.WriteByte(opening) // never returns err != nil + _ = buf.WriteByte(closing) + } + + return buf.Bytes() +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/doc.go b/api/vendor/github.com/go-openapi/swag/jsonutils/doc.go new file mode 100644 index 000000000000..3926cc58d1bc --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/doc.go @@ -0,0 +1,7 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package jsonutils provides helpers to work with JSON. +// +// These utilities work with dynamic go structures to and from JSON. +package jsonutils diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/json.go b/api/vendor/github.com/go-openapi/swag/jsonutils/json.go new file mode 100644 index 000000000000..40753ce03fde --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/json.go @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonutils + +import ( + "bytes" + "encoding/json" + + "github.com/go-openapi/swag/jsonutils/adapters" + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" +) + +// WriteJSON marshals a data structure as JSON. +// +// The difference with [json.Marshal] is that it may check among several alternatives +// to do so. +// +// See [adapters.Registrar] for more details about how to configure +// multiple serialization alternatives. +// +// NOTE: to allow types that are [easyjson.Marshaler] s to use that route to process JSON, +// you now need to register the adapter for easyjson at runtime. +func WriteJSON(value any) ([]byte, error) { + if orderedMap, isOrdered := value.(ifaces.Ordered); isOrdered { + orderedMarshaler := adapters.OrderedMarshalAdapterFor(orderedMap) + + if orderedMarshaler != nil { + defer orderedMarshaler.Redeem() + + return orderedMarshaler.OrderedMarshal(orderedMap) + } + + // no support found in registered adapters, fallback to the default (unordered) case + } + + marshaler := adapters.MarshalAdapterFor(value) + if marshaler != nil { + defer marshaler.Redeem() + + return marshaler.Marshal(value) + } + + // no support found in registered adapters, fallback to the default standard library. + // + // This only happens when tinkering with the global registry of adapters, since the default handles all the above cases. + return json.Marshal(value) // Codecov ignore // this is a safeguard not easily simulated in tests +} + +// ReadJSON unmarshals JSON data into a data structure. +// +// The difference with [json.Unmarshal] is that it may check among several alternatives +// to do so. +// +// See [adapters.Registrar] for more details about how to configure +// multiple serialization alternatives. +// +// NOTE: value must be a pointer. +// +// If the provided value implements [ifaces.SetOrdered], it is a considered an "ordered map" and [ReadJSON] +// will favor an adapter that supports the [ifaces.OrderedUnmarshal] feature, or fallback to +// an unordered behavior if none is found. +// +// NOTE: to allow types that are [easyjson.Unmarshaler] s to use that route to process JSON, +// you now need to register the adapter for easyjson at runtime. +func ReadJSON(data []byte, value any) error { + trimmedData := bytes.Trim(data, "\x00") + + if orderedMap, isOrdered := value.(ifaces.SetOrdered); isOrdered { + // if the value is an ordered map, favors support for OrderedUnmarshal. + + orderedUnmarshaler := adapters.OrderedUnmarshalAdapterFor(orderedMap) + + if orderedUnmarshaler != nil { + defer orderedUnmarshaler.Redeem() + + return orderedUnmarshaler.OrderedUnmarshal(trimmedData, orderedMap) + } + + // no support found in registered adapters, fallback to the default (unordered) case + } + + unmarshaler := adapters.UnmarshalAdapterFor(value) + if unmarshaler != nil { + defer unmarshaler.Redeem() + + return unmarshaler.Unmarshal(trimmedData, value) + } + + // no support found in registered adapters, fallback to the default standard library. + // + // This only happens when tinkering with the global registry of adapters, since the default handles all the above cases. + return json.Unmarshal(trimmedData, value) // Codecov ignore // this is a safeguard not easily simulated in tests +} + +// FromDynamicJSON turns a go value into a properly JSON typed structure. +// +// "Dynamic JSON" refers to what you get when unmarshaling JSON into an untyped any, +// i.e. objects are represented by map[string]any, arrays by []any, and +// all numbers are represented as float64. +// +// NOTE: target must be a pointer. +// +// # Maintaining the order of keys in objects +// +// If source and target implement [ifaces.Ordered] and [ifaces.SetOrdered] respectively, +// they are considered "ordered maps" and the order of keys is maintained in the +// "jsonification" process. In that case, map[string]any values are replaced by (ordered) [JSONMapSlice] ones. +func FromDynamicJSON(source, target any) error { + b, err := WriteJSON(source) + if err != nil { + return err + } + + return ReadJSON(b, target) +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go b/api/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go new file mode 100644 index 000000000000..38dd3e244426 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonutils + +import ( + "iter" + + "github.com/go-openapi/swag/jsonutils/adapters" + "github.com/go-openapi/swag/typeutils" +) + +// JSONMapSlice represents a JSON object, with the order of keys maintained. +// +// It behaves like an ordered map, but keys can't be accessed in constant time. +type JSONMapSlice []JSONMapItem + +// OrderedItems iterates over all (key,value) pairs with the order of keys maintained. +// +// This implements the [ifaces.Ordered] interface, so that [ifaces.Adapter] s know how to marshal +// keys in the desired order. +func (s JSONMapSlice) OrderedItems() iter.Seq2[string, any] { + return func(yield func(string, any) bool) { + for _, item := range s { + if !yield(item.Key, item.Value) { + return + } + } + } +} + +// SetOrderedItems sets keys in the [JSONMapSlice] objects, as presented by +// the provided iterator. +// +// As a special case, if items is nil, this sets to receiver to a nil slice. +// +// This implements the [ifaces.SetOrdered] interface, so that [ifaces.Adapter] s know how to unmarshal +// keys in the desired order. +func (s *JSONMapSlice) SetOrderedItems(items iter.Seq2[string, any]) { + if items == nil { + // force receiver to be a nil slice + *s = nil + + return + } + + m := *s + if len(m) > 0 { + // update mode: short-circuited when unmarshaling fresh data structures + idx := make(map[string]int, len(m)) + + for i, item := range m { + idx[item.Key] = i + } + + for k, v := range items { + idx, ok := idx[k] + if ok { + m[idx].Value = v + + continue + } + + m = append(m, JSONMapItem{Key: k, Value: v}) + } + + *s = m + + return + } + + for k, v := range items { + m = append(m, JSONMapItem{Key: k, Value: v}) + } + + *s = m +} + +// MarshalJSON renders a [JSONMapSlice] as JSON bytes, preserving the order of keys. +// +// It will pick the JSON library currently configured by the [adapters.Registry] (defaults to the standard library). +func (s JSONMapSlice) MarshalJSON() ([]byte, error) { + orderedMarshaler := adapters.OrderedMarshalAdapterFor(s) + defer orderedMarshaler.Redeem() + + return orderedMarshaler.OrderedMarshal(s) +} + +// UnmarshalJSON builds a [JSONMapSlice] from JSON bytes, preserving the order of keys. +// +// Inner objects are unmarshaled as ordered [JSONMapSlice] slices and not map[string]any. +// +// It will pick the JSON library currently configured by the [adapters.Registry] (defaults to the standard library). +func (s *JSONMapSlice) UnmarshalJSON(data []byte) error { + if typeutils.IsNil(*s) { + // allow to unmarshal with a simple var declaration (nil slice) + *s = JSONMapSlice{} + } + + orderedUnmarshaler := adapters.OrderedUnmarshalAdapterFor(s) + defer orderedUnmarshaler.Redeem() + + return orderedUnmarshaler.OrderedUnmarshal(data, s) +} + +// JSONMapItem represents the value of a key in a JSON object held by [JSONMapSlice]. +// +// Notice that JSONMapItem should not be marshaled to or unmarshaled from JSON directly. +// +// Use this type as part of a [JSONMapSlice] when dealing with JSON bytes. +type JSONMapItem struct { + Key string + Value any +} diff --git a/api/vendor/github.com/go-openapi/swag/jsonutils_iface.go b/api/vendor/github.com/go-openapi/swag/jsonutils_iface.go new file mode 100644 index 000000000000..7bd4105fa51a --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/jsonutils_iface.go @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "log" + + "github.com/go-openapi/swag/jsonutils" +) + +// JSONMapSlice represents a JSON object, with the order of keys maintained +// +// Deprecated: use [jsonutils.JSONMapSlice] instead, or [yamlutils.YAMLMapSlice] if you marshal YAML. +type JSONMapSlice = jsonutils.JSONMapSlice + +// JSONMapItem represents a JSON object, with the order of keys maintained +// +// Deprecated: use [jsonutils.JSONMapItem] instead. +type JSONMapItem = jsonutils.JSONMapItem + +// WriteJSON writes json data. +// +// Deprecated: use [jsonutils.WriteJSON] instead. +func WriteJSON(data any) ([]byte, error) { return jsonutils.WriteJSON(data) } + +// ReadJSON reads json data. +// +// Deprecated: use [jsonutils.ReadJSON] instead. +func ReadJSON(data []byte, value any) error { return jsonutils.ReadJSON(data, value) } + +// DynamicJSONToStruct converts an untyped JSON structure into a target data type. +// +// Deprecated: use [jsonutils.FromDynamicJSON] instead. +func DynamicJSONToStruct(data any, target any) error { + return jsonutils.FromDynamicJSON(data, target) +} + +// ConcatJSON concatenates multiple JSON objects efficiently. +// +// Deprecated: use [jsonutils.ConcatJSON] instead. +func ConcatJSON(blobs ...[]byte) []byte { return jsonutils.ConcatJSON(blobs...) } + +// ToDynamicJSON turns a go value into a properly JSON untyped structure. +// +// It is the same as [FromDynamicJSON], but doesn't check for errors. +// +// Deprecated: this function is a misnomer and is unsafe. Use [jsonutils.FromDynamicJSON] instead. +func ToDynamicJSON(value any) any { + var res any + if err := FromDynamicJSON(value, &res); err != nil { + log.Println(err) + } + + return res +} + +// FromDynamicJSON turns a go value into a properly JSON typed structure. +// +// "Dynamic JSON" refers to what you get when unmarshaling JSON into an untyped any, +// i.e. objects are represented by map[string]any, arrays by []any, and all +// scalar values are any. +// +// Deprecated: use [jsonutils.FromDynamicJSON] instead. +func FromDynamicJSON(data, target any) error { return jsonutils.FromDynamicJSON(data, target) } diff --git a/api/vendor/github.com/go-openapi/swag/loading/LICENSE b/api/vendor/github.com/go-openapi/swag/loading/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/loading/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/api/vendor/github.com/go-openapi/swag/loading/doc.go b/api/vendor/github.com/go-openapi/swag/loading/doc.go new file mode 100644 index 000000000000..8cf7bcb8b9d4 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/loading/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package loading provides tools to load a file from http or from a local file system. +package loading diff --git a/api/vendor/github.com/go-openapi/swag/loading/errors.go b/api/vendor/github.com/go-openapi/swag/loading/errors.go new file mode 100644 index 000000000000..b3964289c742 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/loading/errors.go @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +type loadingError string + +const ( + // ErrLoader is an error raised by the file loader utility + ErrLoader loadingError = "loader error" +) + +func (e loadingError) Error() string { + return string(e) +} diff --git a/api/vendor/github.com/go-openapi/swag/loading/json.go b/api/vendor/github.com/go-openapi/swag/loading/json.go new file mode 100644 index 000000000000..59db12f5cfdb --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/loading/json.go @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +import ( + "encoding/json" + "errors" + "path/filepath" +) + +// JSONMatcher matches json for a file loader. +func JSONMatcher(path string) bool { + ext := filepath.Ext(path) + return ext == ".json" || ext == ".jsn" || ext == ".jso" +} + +// JSONDoc loads a json document from either a file or a remote url. +func JSONDoc(path string, opts ...Option) (json.RawMessage, error) { + data, err := LoadFromFileOrHTTP(path, opts...) + if err != nil { + return nil, errors.Join(err, ErrLoader) + } + return json.RawMessage(data), nil +} diff --git a/vendor/github.com/go-openapi/swag/loading.go b/api/vendor/github.com/go-openapi/swag/loading/loading.go similarity index 61% rename from vendor/github.com/go-openapi/swag/loading.go rename to api/vendor/github.com/go-openapi/swag/loading/loading.go index 658a24b789b5..269fb74d1675 100644 --- a/vendor/github.com/go-openapi/swag/loading.go +++ b/api/vendor/github.com/go-openapi/swag/loading/loading.go @@ -1,54 +1,26 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 -package swag +package loading import ( + "context" + "embed" "fmt" "io" "log" "net/http" "net/url" - "os" "path" "path/filepath" "runtime" "strings" - "time" ) -// LoadHTTPTimeout the default timeout for load requests -var LoadHTTPTimeout = 30 * time.Second - -// LoadHTTPBasicAuthUsername the username to use when load requests require basic auth -var LoadHTTPBasicAuthUsername = "" - -// LoadHTTPBasicAuthPassword the password to use when load requests require basic auth -var LoadHTTPBasicAuthPassword = "" - -// LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests -var LoadHTTPCustomHeaders = map[string]string{} - // LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in -func LoadFromFileOrHTTP(pth string) ([]byte, error) { - return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(pth) -} - -// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in -// timeout arg allows for per request overriding of the request timeout -func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration) ([]byte, error) { - return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(timeout))(pth) +func LoadFromFileOrHTTP(pth string, opts ...Option) ([]byte, error) { + o := optionsWithDefaults(opts) + return LoadStrategy(pth, o.ReadFileFunc(), loadHTTPBytes(opts...), opts...)(pth) } // LoadStrategy returns a loader function for a given path or URI. @@ -81,10 +53,12 @@ func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration) ([]byte, e // - `file://host/folder/file` becomes an UNC path like `\\host\folder\file` (no port specification is supported) // - `file:///c:/folder/file` becomes `C:\folder\file` // - `file://c:/folder/file` is tolerated (without leading `/`) and becomes `c:\folder\file` -func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) { +func LoadStrategy(pth string, local, remote func(string) ([]byte, error), opts ...Option) func(string) ([]byte, error) { if strings.HasPrefix(pth, "http") { return remote } + o := optionsWithDefaults(opts) + _, isEmbedFS := o.fs.(embed.FS) return func(p string) ([]byte, error) { upth, err := url.PathUnescape(p) @@ -92,19 +66,19 @@ func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(s return nil, err } - if !strings.HasPrefix(p, `file://`) { + cpth, hasPrefix := strings.CutPrefix(upth, "file://") + if !hasPrefix || isEmbedFS || runtime.GOOS != "windows" { + // crude processing: trim the file:// prefix. This leaves full URIs with a host with a (mostly) unexpected result // regular file path provided: just normalize slashes - return local(filepath.FromSlash(upth)) - } - - if runtime.GOOS != "windows" { - // crude processing: this leaves full URIs with a host with a (mostly) unexpected result - upth = strings.TrimPrefix(upth, `file://`) + if isEmbedFS { + // on windows, we need to slash the path if FS is an embed FS. + return local(strings.TrimLeft(filepath.ToSlash(cpth), "./")) // remove invalid leading characters for embed FS + } - return local(filepath.FromSlash(upth)) + return local(filepath.FromSlash(cpth)) } - // windows-only pre-processing of file://... URIs + // windows-only pre-processing of file://... URIs, excluding embed.FS // support for canonical file URIs on windows. u, err := url.Parse(filepath.ToSlash(upth)) @@ -139,19 +113,29 @@ func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(s } } -func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { +func loadHTTPBytes(opts ...Option) func(path string) ([]byte, error) { + o := optionsWithDefaults(opts) + return func(path string) ([]byte, error) { - client := &http.Client{Timeout: timeout} - req, err := http.NewRequest(http.MethodGet, path, nil) //nolint:noctx + client := o.client + timeoutCtx := context.Background() + var cancel func() + + if o.httpTimeout > 0 { + timeoutCtx, cancel = context.WithTimeout(timeoutCtx, o.httpTimeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(timeoutCtx, http.MethodGet, path, nil) if err != nil { return nil, err } - if LoadHTTPBasicAuthUsername != "" && LoadHTTPBasicAuthPassword != "" { - req.SetBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword) + if o.basicAuthUsername != "" && o.basicAuthPassword != "" { + req.SetBasicAuth(o.basicAuthUsername, o.basicAuthPassword) } - for key, val := range LoadHTTPCustomHeaders { + for key, val := range o.customHeaders { req.Header.Set(key, val) } diff --git a/api/vendor/github.com/go-openapi/swag/loading/options.go b/api/vendor/github.com/go-openapi/swag/loading/options.go new file mode 100644 index 000000000000..6674ac69e628 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/loading/options.go @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +import ( + "io/fs" + "net/http" + "os" + "time" +) + +type ( + // Option provides options for loading a file over HTTP or from a file. + Option func(*options) + + httpOptions struct { + httpTimeout time.Duration + basicAuthUsername string + basicAuthPassword string + customHeaders map[string]string + client *http.Client + } + + fileOptions struct { + fs fs.ReadFileFS + } + + options struct { + httpOptions + fileOptions + } +) + +func (fo fileOptions) ReadFileFunc() func(string) ([]byte, error) { + if fo.fs == nil { + return os.ReadFile + } + + return fo.fs.ReadFile +} + +// WithTimeout sets a timeout for the remote file loader. +// +// The default timeout is 30s. +func WithTimeout(timeout time.Duration) Option { + return func(o *options) { + o.httpTimeout = timeout + } +} + +// WithBasicAuth sets a basic authentication scheme for the remote file loader. +func WithBasicAuth(username, password string) Option { + return func(o *options) { + o.basicAuthUsername = username + o.basicAuthPassword = password + } +} + +// WithCustomHeaders sets custom headers for the remote file loader. +func WithCustomHeaders(headers map[string]string) Option { + return func(o *options) { + if o.customHeaders == nil { + o.customHeaders = make(map[string]string, len(headers)) + } + + for header, value := range headers { + o.customHeaders[header] = value + } + } +} + +// WithHTTPClient overrides the default HTTP client used to fetch a remote file. +// +// By default, [http.DefaultClient] is used. +func WithHTTPClient(client *http.Client) Option { + return func(o *options) { + o.client = client + } +} + +// WithFS sets a file system for the local file loader. +// +// If the provided file system is a [fs.ReadFileFS], the ReadFile function is used. +// Otherwise, ReadFile is wrapped using [fs.ReadFile]. +// +// By default, the file system is the one provided by the os package. +// +// For example, this may be set to consume from an embedded file system, or a rooted FS. +func WithFS(filesystem fs.FS) Option { + return func(o *options) { + if rfs, ok := filesystem.(fs.ReadFileFS); ok { + o.fs = rfs + + return + } + o.fs = readFileFS{FS: filesystem} + } +} + +type readFileFS struct { + fs.FS +} + +func (r readFileFS) ReadFile(name string) ([]byte, error) { + return fs.ReadFile(r.FS, name) +} + +func optionsWithDefaults(opts []Option) options { + const defaultTimeout = 30 * time.Second + + o := options{ + // package level defaults + httpOptions: httpOptions{ + httpTimeout: defaultTimeout, + client: http.DefaultClient, + }, + } + + for _, apply := range opts { + apply(&o) + } + + return o +} diff --git a/api/vendor/github.com/go-openapi/swag/loading/yaml.go b/api/vendor/github.com/go-openapi/swag/loading/yaml.go new file mode 100644 index 000000000000..3ebb53668c47 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/loading/yaml.go @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +import ( + "encoding/json" + "path/filepath" + + "github.com/go-openapi/swag/yamlutils" +) + +// YAMLMatcher matches yaml for a file loader. +func YAMLMatcher(path string) bool { + ext := filepath.Ext(path) + return ext == ".yaml" || ext == ".yml" +} + +// YAMLDoc loads a yaml document from either http or a file and converts it to json. +func YAMLDoc(path string, opts ...Option) (json.RawMessage, error) { + yamlDoc, err := YAMLData(path, opts...) + if err != nil { + return nil, err + } + + return yamlutils.YAMLToJSON(yamlDoc) +} + +// YAMLData loads a yaml document from either http or a file. +func YAMLData(path string, opts ...Option) (any, error) { + data, err := LoadFromFileOrHTTP(path, opts...) + if err != nil { + return nil, err + } + + return yamlutils.BytesToYAMLDoc(data) +} diff --git a/api/vendor/github.com/go-openapi/swag/loading_iface.go b/api/vendor/github.com/go-openapi/swag/loading_iface.go new file mode 100644 index 000000000000..27ec3fb8c37a --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/loading_iface.go @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "encoding/json" + "time" + + "github.com/go-openapi/swag/loading" +) + +var ( + // Package-level defaults for the file loading utilities (deprecated). + + // LoadHTTPTimeout the default timeout for load requests. + // + // Deprecated: use [loading.WithTimeout] instead. + LoadHTTPTimeout = 30 * time.Second + + // LoadHTTPBasicAuthUsername the username to use when load requests require basic auth. + // + // Deprecated: use [loading.WithBasicAuth] instead. + LoadHTTPBasicAuthUsername = "" + + // LoadHTTPBasicAuthPassword the password to use when load requests require basic auth. + // + // Deprecated: use [loading.WithBasicAuth] instead. + LoadHTTPBasicAuthPassword = "" + + // LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests. + // + // Deprecated: use [loading.WithCustomHeaders] instead. + LoadHTTPCustomHeaders = map[string]string{} +) + +// LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the provided path. +// +// Deprecated: use [loading.LoadFromFileOrHTTP] instead. +func LoadFromFileOrHTTP(pth string, opts ...loading.Option) ([]byte, error) { + return loading.LoadFromFileOrHTTP(pth, loadingOptionsWithDefaults(opts)...) +} + +// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in +// timeout arg allows for per request overriding of the request timeout. +// +// Deprecated: use [loading.LoadFileOrHTTP] with the [loading.WithTimeout] option instead. +func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration, opts ...loading.Option) ([]byte, error) { + opts = append(opts, loading.WithTimeout(timeout)) + + return LoadFromFileOrHTTP(pth, opts...) +} + +// LoadStrategy returns a loader function for a given path or URL. +// +// Deprecated: use [loading.LoadStrategy] instead. +func LoadStrategy(pth string, local, remote func(string) ([]byte, error), opts ...loading.Option) func(string) ([]byte, error) { + return loading.LoadStrategy(pth, local, remote, loadingOptionsWithDefaults(opts)...) +} + +// YAMLMatcher matches yaml for a file loader. +// +// Deprecated: use [loading.YAMLMatcher] instead. +func YAMLMatcher(path string) bool { return loading.YAMLMatcher(path) } + +// YAMLDoc loads a yaml document from either http or a file and converts it to json. +// +// Deprecated: use [loading.YAMLDoc] instead. +func YAMLDoc(path string) (json.RawMessage, error) { + return loading.YAMLDoc(path) +} + +// YAMLData loads a yaml document from either http or a file. +// +// Deprecated: use [loading.YAMLData] instead. +func YAMLData(path string) (any, error) { + return loading.YAMLData(path) +} + +// loadingOptionsWithDefaults bridges deprecated default settings that use package-level variables, +// with the recommended use of loading.Option. +func loadingOptionsWithDefaults(opts []loading.Option) []loading.Option { + o := []loading.Option{ + loading.WithTimeout(LoadHTTPTimeout), + loading.WithBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword), + loading.WithCustomHeaders(LoadHTTPCustomHeaders), + } + o = append(o, opts...) + + return o +} diff --git a/vendor/github.com/go-openapi/swag/BENCHMARK.md b/api/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md similarity index 53% rename from vendor/github.com/go-openapi/swag/BENCHMARK.md rename to api/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md index e7f28ed6b789..6674c63b7294 100644 --- a/vendor/github.com/go-openapi/swag/BENCHMARK.md +++ b/api/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md @@ -1,12 +1,10 @@ -# Benchmarks - -## Name mangling utilities +# Benchmarking name mangling utilities ```bash go test -bench XXX -run XXX -benchtime 30s ``` -### Benchmarks at b3e7a5386f996177e4808f11acb2aa93a0f660df +## Benchmarks at b3e7a5386f996177e4808f11acb2aa93a0f660df ``` goos: linux @@ -21,7 +19,7 @@ BenchmarkToXXXName/ToHumanNameLower-4 895334 40354 ns/op 10472 B/op BenchmarkToXXXName/ToHumanNameTitle-4 882441 40678 ns/op 10566 B/op 749 allocs/op ``` -### Benchmarks after PR #79 +## Benchmarks after PR #79 ~ x10 performance improvement and ~ /100 memory allocations. @@ -50,3 +48,43 @@ BenchmarkToXXXName/ToCommandName-16 32256634 1137 ns/op 147 B/op BenchmarkToXXXName/ToHumanNameLower-16 18599661 1946 ns/op 92 B/op 6 allocs/op BenchmarkToXXXName/ToHumanNameTitle-16 17581353 2054 ns/op 105 B/op 6 allocs/op ``` + +## Benchmarks at d7d2d1b895f5b6747afaff312dd2a402e69e818b + +go1.24 + +``` +goos: linux +goarch: amd64 +pkg: github.com/go-openapi/swag +cpu: AMD Ryzen 7 5800X 8-Core Processor +BenchmarkToXXXName/ToGoName-16 19757858 1881 ns/op 42 B/op 5 allocs/op +BenchmarkToXXXName/ToVarName-16 17494111 2094 ns/op 74 B/op 7 allocs/op +BenchmarkToXXXName/ToFileName-16 28161226 1492 ns/op 158 B/op 7 allocs/op +BenchmarkToXXXName/ToCommandName-16 23787333 1489 ns/op 158 B/op 7 allocs/op +BenchmarkToXXXName/ToHumanNameLower-16 17537257 2030 ns/op 103 B/op 6 allocs/op +BenchmarkToXXXName/ToHumanNameTitle-16 16977453 2156 ns/op 105 B/op 6 allocs/op +``` + +## Benchmarks after PR #106 + +Moving the scope of everything down to a struct allowed to reduce a bit garbage and pooling. + +On top of that, ToGoName (and thus ToVarName) have been subject to a minor optimization, removing a few allocations. + +Overall timings improve by ~ -10%. + +go1.24 + +``` +goos: linux +goarch: amd64 +pkg: github.com/go-openapi/swag/mangling +cpu: AMD Ryzen 7 5800X 8-Core Processor +BenchmarkToXXXName/ToGoName-16 22496130 1618 ns/op 31 B/op 3 allocs/op +BenchmarkToXXXName/ToVarName-16 22538068 1618 ns/op 33 B/op 3 allocs/op +BenchmarkToXXXName/ToFileName-16 27722977 1236 ns/op 105 B/op 6 allocs/op +BenchmarkToXXXName/ToCommandName-16 27967395 1258 ns/op 105 B/op 6 allocs/op +BenchmarkToXXXName/ToHumanNameLower-16 18587901 1917 ns/op 103 B/op 6 allocs/op +BenchmarkToXXXName/ToHumanNameTitle-16 17193208 2019 ns/op 108 B/op 7 allocs/op +``` diff --git a/api/vendor/github.com/go-openapi/swag/mangling/LICENSE b/api/vendor/github.com/go-openapi/swag/mangling/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/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/api/vendor/github.com/go-openapi/swag/mangling/doc.go b/api/vendor/github.com/go-openapi/swag/mangling/doc.go new file mode 100644 index 000000000000..ce0d8904857a --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/doc.go @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package mangling provides name mangling capabilities. +// +// Name mangling is an important stage when generating code: +// it helps construct safe program identifiers that abide by the language rules +// and play along with linters. +// +// Examples: +// +// Suppose we get an object name taken from an API spec: "json_object", +// +// We may generate a legit go type name using [NameMangler.ToGoName]: "JsonObject". +// +// We may then locate this type in a source file named using [NameMangler.ToFileName]: "json_object.go". +// +// The methods exposed by the NameMangler are used to generate code in many different contexts, such as: +// +// - generating exported or unexported go identifiers from a JSON schema or an API spec +// - generating file names +// - generating human-readable comments for types and variables +// - generating JSON-like API identifiers from go code +// - ... +package mangling diff --git a/api/vendor/github.com/go-openapi/swag/mangling/initialism_index.go b/api/vendor/github.com/go-openapi/swag/mangling/initialism_index.go new file mode 100644 index 000000000000..e5b70c149388 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/initialism_index.go @@ -0,0 +1,270 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "sort" + "strings" + "unicode" + "unicode/utf8" +) + +// DefaultInitialisms returns all the initialisms configured by default for this package. +// +// # Motivation +// +// Common initialisms are acronyms for which the ordinary camel-casing rules are altered and +// for which we retain the original case. +// +// This is largely specific to the go naming conventions enforced by golint (now revive). +// +// # Example +// +// In go, "id" is a good-looking identifier, but "Id" is not and "ID" is preferred +// (notice that this stems only from conventions: the go compiler accepts all of these). +// +// Similarly, we may use "http", but not "Http". In this case, "HTTP" is preferred. +// +// # Reference and customization +// +// The default list of these casing-style exceptions is taken from the [github.com/mgechev/revive] linter for go: +// https://github.com/mgechev/revive/blob/master/lint/name.go#L93 +// +// There are a few additions to the original list, such as IPv4, IPv6 and OAI ("OpenAPI"). +// +// For these additions, "IPv4" would be preferred to "Ipv4" or "IPV4", and "OAI" to "Oai" +// +// You may redefine this list entirely using the mangler option [WithInitialisms], or simply add extra definitions +// using [WithAdditionalInitialisms]. +// +// # Mixed-case and plurals +// +// Notice that initialisms are not necessarily fully upper-cased: a mixed-case initialism indicates the preferred casing. +// +// Obviously, lower-case only initialisms do not make a lot of sense: if lower-case only initialisms are added, +// they will be considered fully capitalized. +// +// Plural forms use mixed case like "IDs". And so do values like "IPv4" or "IPv6". +// +// The [NameMangler] automatically detects simple plurals for words such as "IDs" or "APIs", +// so you don't need to configure these variants. +// +// At this moment, it doesn't support pluralization of terms that ends with an 's' (or 'S'), since there is +// no clear consensus on whether a word like DNS should be pluralized as DNSes or remain invariant. +// The [NameMangler] consider those invariant. Therefore DNSs or DNSes are not recognized as plurals for DNS. +// +// Besids, we don't want to support pluralization of terms which would otherwise conflict with another one, +// like "HTTPs" vs "HTTPS". All these should be considered invariant. Hence: "Https" matches "HTTPS" and +// "HTTPSS" is "HTTPS" followed by "S". +func DefaultInitialisms() []string { + return []string{ + "ACL", + "API", + "ASCII", + "CPU", + "CSS", + "DNS", + "EOF", + "GUID", + "HTML", + "HTTPS", + "HTTP", + "ID", + "IP", + "IPv4", // prefer the mixed case outcome IPv4 over the capitalized IPV4 + "IPv6", // prefer the mixed case outcome IPv6 over the capitalized IPV6 + "JSON", + "LHS", + "OAI", + "QPS", + "RAM", + "RHS", + "RPC", + "SLA", + "SMTP", + "SQL", + "SSH", + "TCP", + "TLS", + "TTL", + "UDP", + "UI", + "UID", + "UUID", + "URI", + "URL", + "UTF8", + "VM", + "XML", + "XMPP", + "XSRF", + "XSS", + } +} + +type indexOfInitialisms struct { + initialismsCache + + index map[string]struct{} +} + +func newIndexOfInitialisms() *indexOfInitialisms { + return &indexOfInitialisms{ + index: make(map[string]struct{}), + } +} + +func (m *indexOfInitialisms) add(words ...string) *indexOfInitialisms { + for _, word := range words { + // sanitization of injected words: trimmed from blanks, and must start with a letter + trimmed := strings.TrimSpace(word) + + firstRune, _ := utf8.DecodeRuneInString(trimmed) + if !unicode.IsLetter(firstRune) { + continue + } + + // Initialisms are case-sensitive. This means that we support mixed-case words. + // However, if specified as a lower-case string, the initialism should be fully capitalized. + if trimmed == strings.ToLower(trimmed) { + m.index[strings.ToUpper(trimmed)] = struct{}{} + + continue + } + + m.index[trimmed] = struct{}{} + } + return m +} + +func (m *indexOfInitialisms) sorted() []string { + result := make([]string, 0, len(m.index)) + for k := range m.index { + result = append(result, k) + } + sort.Sort(sort.Reverse(byInitialism(result))) + return result +} + +func (m *indexOfInitialisms) buildCache() { + m.build(m.sorted(), m.pluralForm) +} + +// initialismsCache caches all needed pre-computed and converted initialism entries, +// in the desired resolution order. +type initialismsCache struct { + initialisms []string + initialismsRunes [][]rune + initialismsUpperCased [][]rune // initialisms cached in their trimmed, upper-cased version + initialismsPluralForm []pluralForm +} + +func (c *initialismsCache) build(in []string, pluralfunc func(string) pluralForm) { + c.initialisms = in + c.initialismsRunes = asRunes(c.initialisms) + c.initialismsUpperCased = asUpperCased(c.initialisms) + c.initialismsPluralForm = asPluralForms(c.initialisms, pluralfunc) +} + +// pluralForm denotes the kind of pluralization to be used for initialisms. +// +// At this moment, initialisms are either invariant or follow a simple plural form with an +// extra (lower case) "s". +type pluralForm uint8 + +const ( + notPlural pluralForm = iota + invariantPlural + simplePlural +) + +func (f pluralForm) String() string { + switch f { + case notPlural: + return "notPlural" + case invariantPlural: + return "invariantPlural" + case simplePlural: + return "simplePlural" + default: + return "" + } +} + +// pluralForm indicates how we want to pluralize a given initialism. +// +// Besides configured invariant forms (like HTTP and HTTPS), +// an initialism is normally pluralized by adding a single 's', like in IDs. +// +// Initialisms ending with an 'S' or an 's' are configured as invariant (we don't +// support plural forms like CSSes or DNSes, however the mechanism could be extended to +// do just that). +func (m *indexOfInitialisms) pluralForm(key string) pluralForm { + if _, ok := m.index[key]; !ok { + return notPlural + } + + if strings.HasSuffix(strings.ToUpper(key), "S") { + return invariantPlural + } + + if _, ok := m.index[key+"s"]; ok { + return invariantPlural + } + + if _, ok := m.index[key+"S"]; ok { + return invariantPlural + } + + return simplePlural +} + +type byInitialism []string + +func (s byInitialism) Len() int { + return len(s) +} +func (s byInitialism) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} + +// Less specifies the order in which initialisms are prioritized: +// 1. match longest first +// 2. when equal length, match in reverse lexicographical order, lower case match comes first +func (s byInitialism) Less(i, j int) bool { + if len(s[i]) != len(s[j]) { + return len(s[i]) < len(s[j]) + } + + return s[i] < s[j] +} + +func asRunes(in []string) [][]rune { + out := make([][]rune, len(in)) + for i, initialism := range in { + out[i] = []rune(initialism) + } + + return out +} + +func asUpperCased(in []string) [][]rune { + out := make([][]rune, len(in)) + + for i, initialism := range in { + out[i] = []rune(upper(trim(initialism))) + } + + return out +} + +// asPluralForms bakes an index of pluralization support. +func asPluralForms(in []string, pluralFunc func(string) pluralForm) []pluralForm { + out := make([]pluralForm, len(in)) + for i, initialism := range in { + out[i] = pluralFunc(initialism) + } + + return out +} diff --git a/api/vendor/github.com/go-openapi/swag/mangling/name_lexem.go b/api/vendor/github.com/go-openapi/swag/mangling/name_lexem.go new file mode 100644 index 000000000000..bc837e3b9f5d --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/name_lexem.go @@ -0,0 +1,186 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "bytes" + "strings" + "unicode" + "unicode/utf8" +) + +type ( + lexemKind uint8 + + nameLexem struct { + original string + matchedInitialism string + kind lexemKind + } +) + +const ( + lexemKindCasualName lexemKind = iota + lexemKindInitialismName +) + +func newInitialismNameLexem(original, matchedInitialism string) nameLexem { + return nameLexem{ + kind: lexemKindInitialismName, + original: original, + matchedInitialism: matchedInitialism, + } +} + +func newCasualNameLexem(original string) nameLexem { + return nameLexem{ + kind: lexemKindCasualName, + original: trim(original), // TODO: save on calls to trim + } +} + +// WriteTitleized writes the titleized lexeme to a bytes.Buffer. +// +// If the first letter cannot be capitalized, it doesn't write anything and return false, +// so the caller may attempt some workaround strategy. +func (l nameLexem) WriteTitleized(w *bytes.Buffer, alwaysUpper bool) bool { + if l.kind == lexemKindInitialismName { + w.WriteString(l.matchedInitialism) + + return true + } + + if len(l.original) == 0 { + return true + } + + if len(l.original) == 1 { + // identifier is too short: casing will depend on the context + firstByte := l.original[0] + switch { + case 'A' <= firstByte && firstByte <= 'Z': + // safe + w.WriteByte(firstByte) + + return true + case alwaysUpper && 'a' <= firstByte && firstByte <= 'z': + w.WriteByte(firstByte - 'a' + 'A') + + return true + default: + + // not a letter: skip and let the caller decide + return false + } + } + + if firstByte := l.original[0]; firstByte < utf8.RuneSelf { + // ASCII + switch { + case 'A' <= firstByte && firstByte <= 'Z': + // already an upper case letter + w.WriteString(l.original) + + return true + case 'a' <= firstByte && firstByte <= 'z': + w.WriteByte(firstByte - 'a' + 'A') + w.WriteString(l.original[1:]) + + return true + default: + // not a good candidate: doesn't start with a letter + return false + } + } + + // unicode + firstRune, idx := utf8.DecodeRuneInString(l.original) + if !unicode.IsLetter(firstRune) || !unicode.IsUpper(unicode.ToUpper(firstRune)) { + // not a good candidate: doesn't start with a letter + // or a rune for which case doesn't make sense (e.g. East-Asian runes etc) + return false + } + + rest := l.original[idx:] + w.WriteRune(unicode.ToUpper(firstRune)) + w.WriteString(strings.ToLower(rest)) + + return true +} + +// WriteLower is like write titleized but it writes a lower-case version of the lexeme. +// +// Similarly, there is no writing if the casing of the first rune doesn't make sense. +func (l nameLexem) WriteLower(w *bytes.Buffer, alwaysLower bool) bool { + if l.kind == lexemKindInitialismName { + w.WriteString(lower(l.matchedInitialism)) + + return true + } + + if len(l.original) == 0 { + return true + } + + if len(l.original) == 1 { + // identifier is too short: casing will depend on the context + firstByte := l.original[0] + switch { + case 'a' <= firstByte && firstByte <= 'z': + // safe + w.WriteByte(firstByte) + + return true + case alwaysLower && 'A' <= firstByte && firstByte <= 'Z': + w.WriteByte(firstByte - 'A' + 'a') + + return true + default: + + // not a letter: skip and let the caller decide + return false + } + } + + if firstByte := l.original[0]; firstByte < utf8.RuneSelf { + // ASCII + switch { + case 'a' <= firstByte && firstByte <= 'z': + // already a lower case letter + w.WriteString(l.original) + + return true + case 'A' <= firstByte && firstByte <= 'Z': + w.WriteByte(firstByte - 'A' + 'a') + w.WriteString(l.original[1:]) + + return true + default: + // not a good candidate: doesn't start with a letter + return false + } + } + + // unicode + firstRune, idx := utf8.DecodeRuneInString(l.original) + if !unicode.IsLetter(firstRune) || !unicode.IsLower(unicode.ToLower(firstRune)) { + // not a good candidate: doesn't start with a letter + // or a rune for which case doesn't make sense (e.g. East-Asian runes etc) + return false + } + + rest := l.original[idx:] + w.WriteRune(unicode.ToLower(firstRune)) + w.WriteString(rest) + + return true +} + +func (l nameLexem) GetOriginal() string { + return l.original +} + +func (l nameLexem) IsInitialism() bool { + return l.kind == lexemKindInitialismName +} diff --git a/api/vendor/github.com/go-openapi/swag/mangling/name_mangler.go b/api/vendor/github.com/go-openapi/swag/mangling/name_mangler.go new file mode 100644 index 000000000000..da685681d08c --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/name_mangler.go @@ -0,0 +1,370 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "strings" + "unicode" +) + +// NameMangler knows how to transform sentences or words into +// identifiers that are a better fit in contexts such as: +// +// - unexported or exported go variable identifiers +// - file names +// - camel cased identifiers +// - ... +// +// The [NameMangler] is safe for concurrent use, save for its [NameMangler.AddInitialisms] method, +// which is not. +// +// # Known limitations +// +// At this moment, the [NameMangler] doesn't play well with "all caps" text: +// +// unless every single upper-cased word is declared as an initialism, capitalized words would generally +// not be transformed with the expected result, e.g. +// +// ToFileName("THIS_IS_ALL_CAPS") +// +// yields the weird outcome +// +// "t_h_i_s_i_s_a_l_l_c_a_p_s" +type NameMangler struct { + options + + index *indexOfInitialisms + + splitter splitter + splitterWithPostSplit splitter + + _ struct{} +} + +// NewNameMangler builds a name mangler ready to convert strings. +// +// The default name mangler is configured with default common initialisms and all default options. +func NewNameMangler(opts ...Option) NameMangler { + m := NameMangler{ + options: optionsWithDefaults(opts), + index: newIndexOfInitialisms(), + } + m.addInitialisms(m.commonInitialisms...) + + // a splitter that returns matches lexemes as ready-to-assemble strings: + // details of the lexemes are redeemed. + m.splitter = newSplitter( + withInitialismsCache(&m.index.initialismsCache), + withReplaceFunc(m.replaceFunc), + ) + + // a splitter that returns matches lexemes ready for post-processing + m.splitterWithPostSplit = newSplitter( + withInitialismsCache(&m.index.initialismsCache), + withReplaceFunc(m.replaceFunc), + withPostSplitInitialismCheck, + ) + + return m +} + +// AddInitialisms declares extra initialisms to the mangler. +// +// It declares extra words as "initialisms" (i.e. words that won't be camel cased or titled cased), +// on top of the existing list of common initialisms (such as ID, HTTP...). +// +// Added words must start with a (unicode) letter. If some don't, they are ignored. +// Added words are either fully capitalized or mixed-cased. Lower-case only words are considered capitalized. +// +// It is typically used just after initializing the [NameMangler]. +// +// When all initialisms are known at the time the mangler is initialized, it is preferable to +// use [NewNameMangler] with the option [WithAdditionalInitialisms]. +// +// Adding initialisms mutates the mangler and should not be carried out concurrently with other calls to the mangler. +func (m *NameMangler) AddInitialisms(words ...string) { + m.addInitialisms(words...) +} + +// Initialisms renders the list of initialisms supported by this mangler. +func (m *NameMangler) Initialisms() []string { + return m.index.initialisms +} + +// Camelize a single word. +// +// Example: +// +// - "HELLO" and "hello" become "Hello". +func (m NameMangler) Camelize(word string) string { + ru := []rune(word) + + switch len(ru) { + case 0: + return "" + case 1: + return string(unicode.ToUpper(ru[0])) + default: + camelized := poolOfBuffers.BorrowBuffer(len(word)) + camelized.Grow(len(word)) + defer func() { + poolOfBuffers.RedeemBuffer(camelized) + }() + + camelized.WriteRune(unicode.ToUpper(ru[0])) + for _, ru := range ru[1:] { + camelized.WriteRune(unicode.ToLower(ru)) + } + + return camelized.String() + } +} + +// ToFileName generates a suitable snake-case file name from a sentence. +// +// It lower-cases everything with underscore (_) as a word separator. +// +// Examples: +// +// - "Hello, Swagger" becomes "hello_swagger" +// - "HelloSwagger" becomes "hello_swagger" +func (m NameMangler) ToFileName(name string) string { + inptr := m.split(name) + in := *inptr + out := make([]string, 0, len(in)) + + for _, w := range in { + out = append(out, lower(w)) + } + poolOfStrings.RedeemStrings(inptr) + + return strings.Join(out, "_") +} + +// ToCommandName generates a suitable CLI command name from a sentence. +// +// It lower-cases everything with dash (-) as a word separator. +// +// Examples: +// +// - "Hello, Swagger" becomes "hello-swagger" +// - "HelloSwagger" becomes "hello-swagger" +func (m NameMangler) ToCommandName(name string) string { + inptr := m.split(name) + in := *inptr + out := make([]string, 0, len(in)) + + for _, w := range in { + out = append(out, lower(w)) + } + poolOfStrings.RedeemStrings(inptr) + + return strings.Join(out, "-") +} + +// ToHumanNameLower represents a code name as a human-readable series of words. +// +// It lower-cases everything with blank space as a word separator. +// +// NOTE: parts recognized as initialisms just keep their original casing. +// +// Examples: +// +// - "Hello, Swagger" becomes "hello swagger" +// - "HelloSwagger" or "Hello-Swagger" become "hello swagger" +func (m NameMangler) ToHumanNameLower(name string) string { + s := m.splitterWithPostSplit + in := s.split(name) + out := make([]string, 0, len(*in)) + + for _, w := range *in { + if !w.IsInitialism() { + out = append(out, lower(w.GetOriginal())) + } else { + out = append(out, trim(w.GetOriginal())) + } + } + + poolOfLexems.RedeemLexems(in) + + return strings.Join(out, " ") +} + +// ToHumanNameTitle represents a code name as a human-readable series of titleized words. +// +// It titleizes every word with blank space as a word separator. +// +// Examples: +// +// - "hello, Swagger" becomes "Hello Swagger" +// - "helloSwagger" becomes "Hello Swagger" +func (m NameMangler) ToHumanNameTitle(name string) string { + s := m.splitterWithPostSplit + in := s.split(name) + + out := make([]string, 0, len(*in)) + for _, w := range *in { + original := trim(w.GetOriginal()) + if !w.IsInitialism() { + out = append(out, m.Camelize(original)) + } else { + out = append(out, original) + } + } + poolOfLexems.RedeemLexems(in) + + return strings.Join(out, " ") +} + +// ToJSONName generates a camelized single-word version of a sentence. +// +// The output assembles every camelized word, but for the first word, which +// is lower-cased. +// +// Example: +// +// - "Hello_swagger" becomes "helloSwagger" +func (m NameMangler) ToJSONName(name string) string { + inptr := m.split(name) + in := *inptr + out := make([]string, 0, len(in)) + + for i, w := range in { + if i == 0 { + out = append(out, lower(w)) + continue + } + out = append(out, m.Camelize(trim(w))) + } + + poolOfStrings.RedeemStrings(inptr) + + return strings.Join(out, "") +} + +// ToVarName generates a legit unexported go variable name from a sentence. +// +// The generated name plays well with linters (see also [NameMangler.ToGoName]). +// +// Examples: +// +// - "Hello_swagger" becomes "helloSwagger" +// - "Http_server" becomes "httpServer" +// +// This name applies the same rules as [NameMangler.ToGoName] (legit exported variable), save the +// capitalization of the initial rune. +// +// Special case: when the initial part is a recognized as an initialism (like in the example above), +// the full part is lower-cased. +func (m NameMangler) ToVarName(name string) string { + return m.goIdentifier(name, false) +} + +// ToGoName generates a legit exported go variable name from a sentence. +// +// The generated name plays well with most linters. +// +// ToGoName abides by the go "exported" symbol rule starting with an upper-case letter. +// +// Examples: +// +// - "hello_swagger" becomes "HelloSwagger" +// - "Http_server" becomes "HTTPServer" +// +// # Edge cases +// +// Whenever the first rune is not eligible to upper case, a special prefix is prepended to the resulting name. +// By default this is simply "X" and you may customize this behavior using the [WithGoNamePrefixFunc] option. +// +// This happens when the first rune is not a letter, e.g. a digit, or a symbol that has no word transliteration +// (see also [WithReplaceFunc] about symbol transliterations), +// as well as for most East Asian or Devanagari runes, for which there is no such concept as upper-case. +// +// # Linting +// +// [revive], the successor of golint is the reference linter. +// +// This means that [NameMangler.ToGoName] supports the initialisms that revive checks (see also [DefaultInitialisms]). +// +// At this moment, there is no attempt to transliterate unicode into ascii, meaning that some linters +// (e.g. asciicheck, gosmopolitan) may croak on go identifiers generated from unicode input. +// +// [revive]: https://github.com/mgechev/revive +func (m NameMangler) ToGoName(name string) string { + return m.goIdentifier(name, true) +} + +func (m NameMangler) goIdentifier(name string, exported bool) string { + s := m.splitterWithPostSplit + lexems := s.split(name) + defer func() { + poolOfLexems.RedeemLexems(lexems) + }() + lexemes := *lexems + + if len(lexemes) == 0 { + return "" + } + + result := poolOfBuffers.BorrowBuffer(len(name)) + defer func() { + poolOfBuffers.RedeemBuffer(result) + }() + + firstPart := lexemes[0] + if !exported { + if ok := firstPart.WriteLower(result, true); !ok { + // NOTE: an initialism as the first part is lower-cased: no longer generates stuff like hTTPxyz. + // + // same prefixing rule applied to unexported variable as to an exported one, so that we have consistent + // names, whether the generated identifier is exported or not. + result.WriteString(strings.ToLower(m.prefixFunc()(name))) + result.WriteString(lexemes[0].GetOriginal()) + } + } else { + if ok := firstPart.WriteTitleized(result, true); !ok { + // "repairs" a lexeme that doesn't start with a letter to become + // the start a legit go name. The current strategy is very crude and simply adds a fixed prefix, + // e.g. "X". + // For instance "1_sesame_street" would be split into lexemes ["1", "sesame", "street"] and + // the first one ("1") would result in something like "X1" (with the default prefix function). + // + // NOTE: no longer forcing the first part to be fully upper-cased + result.WriteString(m.prefixFunc()(name)) + result.WriteString(lexemes[0].GetOriginal()) + } + } + + for _, lexem := range lexemes[1:] { + // NOTE: no longer forcing initialism parts to be fully upper-cased: + // * pluralized initialism preserve their trailing "s" + // * mixed-cased initialisms, such as IPv4, are preserved + if ok := lexem.WriteTitleized(result, false); !ok { + // it's not titleized: perhaps it's too short, perhaps the first rune is not a letter. + // write anyway + result.WriteString(lexem.GetOriginal()) + } + } + + return result.String() +} + +func (m *NameMangler) addInitialisms(words ...string) { + m.index.add(words...) + m.index.buildCache() +} + +// split calls the inner splitter. +func (m NameMangler) split(str string) *[]string { + s := m.splitter + lexems := s.split(str) + result := poolOfStrings.BorrowStrings() + + for _, lexem := range *lexems { + *result = append(*result, lexem.GetOriginal()) + } + poolOfLexems.RedeemLexems(lexems) + + return result +} diff --git a/api/vendor/github.com/go-openapi/swag/mangling/options.go b/api/vendor/github.com/go-openapi/swag/mangling/options.go new file mode 100644 index 000000000000..3c92b2f18bf1 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/options.go @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +type ( + // PrefixFunc defines a safeguard rule (that may depend on the input string), to prefix + // a generated go name (in [NameMangler.ToGoName] and [NameMangler.ToVarName]). + // + // See [NameMangler.ToGoName] for more about which edge cases the prefix function covers. + PrefixFunc func(string) string + + // ReplaceFunc is a transliteration function to replace special runes by a word. + ReplaceFunc func(r rune) (string, bool) + + // Option to configure a [NameMangler]. + Option func(*options) + + options struct { + commonInitialisms []string + + goNamePrefixFunc PrefixFunc + goNamePrefixFuncPtr *PrefixFunc + replaceFunc func(r rune) (string, bool) + } +) + +func (o *options) prefixFunc() PrefixFunc { + if o.goNamePrefixFuncPtr != nil && *o.goNamePrefixFuncPtr != nil { + return *o.goNamePrefixFuncPtr + } + + return o.goNamePrefixFunc +} + +// WithGoNamePrefixFunc overrides the default prefix rule to safeguard generated go names. +// +// Example: +// +// This helps convert "123" into "{prefix}123" (a very crude strategy indeed, but it works). +// +// See [github.com/go-swagger/go-swagger/generator.DefaultFuncMap] for an example. +// +// The prefix function is assumed to return a string that starts with an upper case letter. +// +// The default is to prefix with "X". +// +// See [NameMangler.ToGoName] for more about which edge cases the prefix function covers. +func WithGoNamePrefixFunc(fn PrefixFunc) Option { + return func(o *options) { + o.goNamePrefixFunc = fn + } +} + +// WithGoNamePrefixFuncPtr is like [WithGoNamePrefixFunc] but it specifies a pointer to a function. +// +// [WithGoNamePrefixFunc] should be preferred in most situations. This option should only serve the +// purpose of handling special situations where the prefix function is not an internal variable +// (e.g. an exported package global). +// +// [WithGoNamePrefixFuncPtr] supersedes [WithGoNamePrefixFunc] if it also specified. +// +// If the provided pointer is nil or points to a nil value, this option has no effect. +// +// The caller should ensure that no undesirable concurrent changes are applied to the function pointed to. +func WithGoNamePrefixFuncPtr(ptr *PrefixFunc) Option { + return func(o *options) { + o.goNamePrefixFuncPtr = ptr + } +} + +// WithInitialisms declares the initialisms this mangler supports. +// +// This supersedes any pre-loaded defaults (see [DefaultInitialisms] for more about what initialisms are). +// +// It declares words to be recognized as "initialisms" (i.e. words that won't be camel cased or titled cased). +// +// Words must start with a (unicode) letter. If some don't, they are ignored. +// Words are either fully capitalized or mixed-cased. Lower-case only words are considered capitalized. +func WithInitialisms(words ...string) Option { + return func(o *options) { + o.commonInitialisms = words + } +} + +// WithAdditionalInitialisms adds new initialisms to the currently supported list (see [DefaultInitialisms]). +// +// The same sanitization rules apply as those described for [WithInitialisms]. +func WithAdditionalInitialisms(words ...string) Option { + return func(o *options) { + o.commonInitialisms = append(o.commonInitialisms, words...) + } +} + +// WithReplaceFunc specifies a custom transliteration function instead of the default. +// +// The default translates the following characters into words as follows: +// +// - '@' -> 'At' +// - '&' -> 'And' +// - '|' -> 'Pipe' +// - '$' -> 'Dollar' +// - '!' -> 'Bang' +// +// Notice that the outcome of a transliteration should always be titleized. +func WithReplaceFunc(fn ReplaceFunc) Option { + return func(o *options) { + o.replaceFunc = fn + } +} + +func defaultPrefixFunc(_ string) string { + return "X" +} + +// defaultReplaceTable finds a word representation for special characters. +func defaultReplaceTable(r rune) (string, bool) { + switch r { + case '@': + return "At ", true + case '&': + return "And ", true + case '|': + return "Pipe ", true + case '$': + return "Dollar ", true + case '!': + return "Bang ", true + case '-': + return "", true + case '_': + return "", true + default: + return "", false + } +} + +func optionsWithDefaults(opts []Option) options { + o := options{ + commonInitialisms: DefaultInitialisms(), + goNamePrefixFunc: defaultPrefixFunc, + replaceFunc: defaultReplaceTable, + } + + for _, apply := range opts { + apply(&o) + } + + return o +} diff --git a/api/vendor/github.com/go-openapi/swag/mangling/pools.go b/api/vendor/github.com/go-openapi/swag/mangling/pools.go new file mode 100644 index 000000000000..f8104351445d --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/pools.go @@ -0,0 +1,123 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "bytes" + "sync" +) + +const maxAllocMatches = 8 + +type ( + // memory pools of temporary objects. + // + // These are used to recycle temporarily allocated objects + // and relieve the GC from undue pressure. + + matchesPool struct { + *sync.Pool + } + + buffersPool struct { + *sync.Pool + } + + lexemsPool struct { + *sync.Pool + } + + stringsPool struct { + *sync.Pool + } +) + +var ( + // poolOfMatches holds temporary slices for recycling during the initialism match process + poolOfMatches = matchesPool{ + Pool: &sync.Pool{ + New: func() any { + s := make(initialismMatches, 0, maxAllocMatches) + + return &s + }, + }, + } + + poolOfBuffers = buffersPool{ + Pool: &sync.Pool{ + New: func() any { + return new(bytes.Buffer) + }, + }, + } + + poolOfLexems = lexemsPool{ + Pool: &sync.Pool{ + New: func() any { + s := make([]nameLexem, 0, maxAllocMatches) + + return &s + }, + }, + } + + poolOfStrings = stringsPool{ + Pool: &sync.Pool{ + New: func() any { + s := make([]string, 0, maxAllocMatches) + + return &s + }, + }, + } +) + +func (p matchesPool) BorrowMatches() *initialismMatches { + s := p.Get().(*initialismMatches) + *s = (*s)[:0] // reset slice, keep allocated capacity + + return s +} + +func (p buffersPool) BorrowBuffer(size int) *bytes.Buffer { + s := p.Get().(*bytes.Buffer) + s.Reset() + + if s.Cap() < size { + s.Grow(size) + } + + return s +} + +func (p lexemsPool) BorrowLexems() *[]nameLexem { + s := p.Get().(*[]nameLexem) + *s = (*s)[:0] // reset slice, keep allocated capacity + + return s +} + +func (p stringsPool) BorrowStrings() *[]string { + s := p.Get().(*[]string) + *s = (*s)[:0] // reset slice, keep allocated capacity + + return s +} + +func (p matchesPool) RedeemMatches(s *initialismMatches) { + p.Put(s) +} + +func (p buffersPool) RedeemBuffer(s *bytes.Buffer) { + p.Put(s) +} + +func (p lexemsPool) RedeemLexems(s *[]nameLexem) { + p.Put(s) +} + +func (p stringsPool) RedeemStrings(s *[]string) { + p.Put(s) +} diff --git a/api/vendor/github.com/go-openapi/swag/mangling/split.go b/api/vendor/github.com/go-openapi/swag/mangling/split.go new file mode 100644 index 000000000000..ed12ea256746 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/split.go @@ -0,0 +1,341 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "fmt" + "unicode" +) + +type splitterOption func(*splitter) + +// withPostSplitInitialismCheck allows to catch initialisms after main split process +func withPostSplitInitialismCheck(s *splitter) { + s.postSplitInitialismCheck = true +} + +func withReplaceFunc(fn ReplaceFunc) func(*splitter) { + return func(s *splitter) { + s.replaceFunc = fn + } +} + +func withInitialismsCache(c *initialismsCache) splitterOption { + return func(s *splitter) { + s.initialismsCache = c + } +} + +type ( + initialismMatch struct { + body []rune + start, end int + complete bool + hasPlural pluralForm + } + initialismMatches []initialismMatch +) + +// String representation of a match, e.g. for debugging. +func (m initialismMatch) String() string { + return fmt.Sprintf("{body: %s (%d), start: %d, end; %d, complete: %t, hasPlural: %v}", + string(m.body), len(m.body), m.start, m.end, m.complete, m.hasPlural, + ) +} + +func (m initialismMatch) isZero() bool { + return m.start == 0 && m.end == 0 +} + +type splitter struct { + *initialismsCache + + postSplitInitialismCheck bool + replaceFunc ReplaceFunc +} + +func newSplitter(options ...splitterOption) splitter { + var s splitter + + for _, option := range options { + option(&s) + } + + if s.replaceFunc == nil { + s.replaceFunc = defaultReplaceTable + } + + return s +} + +func (s splitter) split(name string) *[]nameLexem { + nameRunes := []rune(name) + matches := s.gatherInitialismMatches(nameRunes) + if matches == nil { + return poolOfLexems.BorrowLexems() + } + + return s.mapMatchesToNameLexems(nameRunes, matches) +} + +func (s splitter) gatherInitialismMatches(nameRunes []rune) *initialismMatches { + matches := poolOfMatches.BorrowMatches() + const minLenInitialism = 1 + if len(nameRunes) < minLenInitialism+1 { + // can't match initialism with 0 or 1 rune + return matches + } + + // first iteration + s.findMatches(matches, nameRunes, nameRunes[0], 0) + + for i, currentRune := range nameRunes[1:] { + currentRunePosition := i + 1 + // recycle allocations as we loop over runes + // with such recycling, only 2 slices should be allocated per call + // instead of o(n). + // + // BorrowMatches always yields slices with zero length (with some capacity) + newMatches := poolOfMatches.BorrowMatches() + + // check current initialism matches + for _, match := range *matches { + if keepCompleteMatch := match.complete; keepCompleteMatch { + // the match is already complete: keep it then move on to the next match + *newMatches = append(*newMatches, match) + continue + } + + if currentRunePosition-match.start == len(match.body) { + // unmatched: skip + continue + } + + // 1. by construction of the matches, we can't have currentRunePosition - match.start < 0 + // because matches have been computed with their start <= currentRunePosition in the previous + // iterations. + // 2. by construction of the matches, we can't have currentRunePosition - match.start >= len(match.body) + + currentMatchRune := match.body[currentRunePosition-match.start] + if currentMatchRune != currentRune { + // failed match, discard it then move on to the next match + continue + } + + // try to complete the current match + if currentRunePosition-match.start == len(match.body)-1 { + // we are close: the next step is to check the symbol ahead + // if it is a lowercase letter, then it is not the end of match + // but the beginning of the next word. + // + // NOTE(fredbi): this heuristic sometimes leads to counterintuitive splits and + // perhaps (not sure yet) we should check against case _alternance_. + // + // Example: + // + // In the current version, in the sentence "IDS initialism", "ID" is recognized as an initialism, + // leading to a split like "id_s_initialism" (or IDSInitialism), + // whereas in the sentence "IDx initialism", it is not and produces something like + // "i_d_x_initialism" (or IDxInitialism). The generated file name is not great. + // + // Both go identifiers are tolerated by linters. + // + // Notice that the slightly different input "IDs initialism" is correctly detected + // as a pluralized initialism and produces something like "ids_initialism" (or IDsInitialism). + + if currentRunePosition < len(nameRunes)-1 { // when before the last rune + nextRune := nameRunes[currentRunePosition+1] + + // recognize a plural form for this initialism (only simple english pluralization is supported). + if nextRune == 's' && match.hasPlural == simplePlural { + // detected a pluralized initialism + match.body = append(match.body, nextRune) + lookAhead := currentRunePosition + 1 + if lookAhead < len(nameRunes)-1 { + nextRune = nameRunes[lookAhead+1] + if newWord := unicode.IsLower(nextRune); newWord { + // it is the start of a new word. + // Match is only partial and the initialism is not recognized: + // move on to the next match, but do not advance the rune position + continue + } + } + + // this is a pluralized match: keep it + currentRunePosition++ + match.complete = true + match.hasPlural = simplePlural + match.end = currentRunePosition + *newMatches = append(*newMatches, match) + + // match is complete: keep it then move on to the next match + continue + } + + // other cases + // example: invariant plural such as "TLS" + if newWord := unicode.IsLower(nextRune); newWord { + // it is the start of a new word + // Match is only partial and the initialism is not recognized : move on + continue + } + } + + match.complete = true + match.end = currentRunePosition + } + + // append the ongoing matching attempt: it is not necessarily complete, but was successful so far. + // Let's see if it still matches on the next rune. + *newMatches = append(*newMatches, match) + } + + s.findMatches(newMatches, nameRunes, currentRune, currentRunePosition) + + poolOfMatches.RedeemMatches(matches) + matches = newMatches + } + + // it is up to the caller to redeem this last slice + return matches +} + +func (s splitter) findMatches(newMatches *initialismMatches, nameRunes []rune, currentRune rune, currentRunePosition int) { + // check for new initialism matches, based on the first character + for i, r := range s.initialismsRunes { + if r[0] != currentRune { + continue + } + + if currentRunePosition+len(r) > len(nameRunes) { + continue // not eligible: would spilll over the initial string + } + + // possible matches: all initialisms starting with the current rune and that can fit the given string (nameRunes) + *newMatches = append(*newMatches, initialismMatch{ + start: currentRunePosition, + body: r, + complete: false, + hasPlural: s.initialismsPluralForm[i], + }) + } +} + +func (s splitter) mapMatchesToNameLexems(nameRunes []rune, matches *initialismMatches) *[]nameLexem { + nameLexems := poolOfLexems.BorrowLexems() + + var lastAcceptedMatch initialismMatch + for _, match := range *matches { + if !match.complete { + continue + } + + if firstMatch := lastAcceptedMatch.isZero(); firstMatch { + s.appendBrokenDownCasualString(nameLexems, nameRunes[:match.start]) + *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) + + lastAcceptedMatch = match + + continue + } + + if overlappedMatch := match.start <= lastAcceptedMatch.end; overlappedMatch { + continue + } + + middle := nameRunes[lastAcceptedMatch.end+1 : match.start] + s.appendBrokenDownCasualString(nameLexems, middle) + *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) + + lastAcceptedMatch = match + } + + // we have not found any accepted matches + if lastAcceptedMatch.isZero() { + *nameLexems = (*nameLexems)[:0] + s.appendBrokenDownCasualString(nameLexems, nameRunes) + } else if lastAcceptedMatch.end+1 != len(nameRunes) { + rest := nameRunes[lastAcceptedMatch.end+1:] + s.appendBrokenDownCasualString(nameLexems, rest) + } + + poolOfMatches.RedeemMatches(matches) + + return nameLexems +} + +func (s splitter) breakInitialism(original string) nameLexem { + return newInitialismNameLexem(original, original) +} + +func (s splitter) appendBrokenDownCasualString(segments *[]nameLexem, str []rune) { + currentSegment := poolOfBuffers.BorrowBuffer(len(str)) // unlike strings.Builder, bytes.Buffer initial storage can reused + defer func() { + poolOfBuffers.RedeemBuffer(currentSegment) + }() + + addCasualNameLexem := func(original string) { + *segments = append(*segments, newCasualNameLexem(original)) + } + + addInitialismNameLexem := func(original, match string) { + *segments = append(*segments, newInitialismNameLexem(original, match)) + } + + var addNameLexem func(string) + if s.postSplitInitialismCheck { + addNameLexem = func(original string) { + for i := range s.initialisms { + if isEqualFoldIgnoreSpace(s.initialismsUpperCased[i], original) { + addInitialismNameLexem(original, s.initialisms[i]) + + return + } + } + + addCasualNameLexem(original) + } + } else { + addNameLexem = addCasualNameLexem + } + + // NOTE: (performance). The few remaining non-amortized allocations + // lay in the code below: using String() forces + for _, rn := range str { + if replace, found := s.replaceFunc(rn); found { + if currentSegment.Len() > 0 { + addNameLexem(currentSegment.String()) + currentSegment.Reset() + } + + if replace != "" { + addNameLexem(replace) + } + + continue + } + + if !unicode.In(rn, unicode.L, unicode.M, unicode.N, unicode.Pc) { + if currentSegment.Len() > 0 { + addNameLexem(currentSegment.String()) + currentSegment.Reset() + } + + continue + } + + if unicode.IsUpper(rn) { + if currentSegment.Len() > 0 { + addNameLexem(currentSegment.String()) + } + currentSegment.Reset() + } + + currentSegment.WriteRune(rn) + } + + if currentSegment.Len() > 0 { + addNameLexem(currentSegment.String()) + } +} diff --git a/vendor/github.com/go-openapi/swag/string_bytes.go b/api/vendor/github.com/go-openapi/swag/mangling/string_bytes.go similarity index 60% rename from vendor/github.com/go-openapi/swag/string_bytes.go rename to api/vendor/github.com/go-openapi/swag/mangling/string_bytes.go index 90745d5ca9f1..28daaf72b1a1 100644 --- a/vendor/github.com/go-openapi/swag/string_bytes.go +++ b/api/vendor/github.com/go-openapi/swag/mangling/string_bytes.go @@ -1,4 +1,7 @@ -package swag +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling import "unsafe" diff --git a/api/vendor/github.com/go-openapi/swag/mangling/util.go b/api/vendor/github.com/go-openapi/swag/mangling/util.go new file mode 100644 index 000000000000..0636417e360b --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling/util.go @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "strings" + "unicode" + "unicode/utf8" +) + +// Removes leading whitespaces +func trim(str string) string { return strings.TrimSpace(str) } + +// upper is strings.ToUpper() combined with trim +func upper(str string) string { + return strings.ToUpper(trim(str)) +} + +// lower is strings.ToLower() combined with trim +func lower(str string) string { + return strings.ToLower(trim(str)) +} + +// isEqualFoldIgnoreSpace is the same as strings.EqualFold, but +// it ignores leading and trailing blank spaces in the compared +// string. +// +// base is assumed to be composed of upper-cased runes, and be already +// trimmed. +// +// This code is heavily inspired from strings.EqualFold. +func isEqualFoldIgnoreSpace(base []rune, str string) bool { + var i, baseIndex int + // equivalent to b := []byte(str), but without data copy + b := hackStringBytes(str) + + for i < len(b) { + if c := b[i]; c < utf8.RuneSelf { + // fast path for ASCII + if c != ' ' && c != '\t' { + break + } + i++ + + continue + } + + // unicode case + r, size := utf8.DecodeRune(b[i:]) + if !unicode.IsSpace(r) { + break + } + i += size + } + + if i >= len(b) { + return len(base) == 0 + } + + for _, baseRune := range base { + if i >= len(b) { + break + } + + if c := b[i]; c < utf8.RuneSelf { + // single byte rune case (ASCII) + if baseRune >= utf8.RuneSelf { + return false + } + + baseChar := byte(baseRune) + if c != baseChar && ((c < 'a') || (c > 'z') || (c-'a'+'A' != baseChar)) { + return false + } + + baseIndex++ + i++ + + continue + } + + // unicode case + r, size := utf8.DecodeRune(b[i:]) + if unicode.ToUpper(r) != baseRune { + return false + } + baseIndex++ + i += size + } + + if baseIndex != len(base) { + return false + } + + // all passed: now we should only have blanks + for i < len(b) { + if c := b[i]; c < utf8.RuneSelf { + // fast path for ASCII + if c != ' ' && c != '\t' { + return false + } + i++ + + continue + } + + // unicode case + r, size := utf8.DecodeRune(b[i:]) + if !unicode.IsSpace(r) { + return false + } + + i += size + } + + return true +} diff --git a/api/vendor/github.com/go-openapi/swag/mangling_iface.go b/api/vendor/github.com/go-openapi/swag/mangling_iface.go new file mode 100644 index 000000000000..98b9a9992930 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/mangling_iface.go @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/mangling" + +// GoNamePrefixFunc sets an optional rule to prefix go names +// which do not start with a letter. +// +// GoNamePrefixFunc should not be written to while concurrently using the other mangling functions of this package. +// +// Deprecated: use [mangling.WithGoNamePrefixFunc] instead. +var GoNamePrefixFunc mangling.PrefixFunc + +// swagNameMangler is a global instance of the name mangler specifically alloted +// to support deprecated functions. +var swagNameMangler = mangling.NewNameMangler( + mangling.WithGoNamePrefixFuncPtr(&GoNamePrefixFunc), +) + +// AddInitialisms adds additional initialisms to the default list (see [mangling.DefaultInitialisms]). +// +// AddInitialisms is not safe to be called concurrently. +// +// Deprecated: use [mangling.WithAdditionalInitialisms] instead. +func AddInitialisms(words ...string) { + swagNameMangler.AddInitialisms(words...) +} + +// Camelize a single word. +// +// Deprecated: use [mangling.NameMangler.Camelize] instead. +func Camelize(word string) string { return swagNameMangler.Camelize(word) } + +// ToFileName lowercases and underscores a go type name. +// +// Deprecated: use [mangling.NameMangler.ToFileName] instead. +func ToFileName(name string) string { return swagNameMangler.ToFileName(name) } + +// ToCommandName lowercases and underscores a go type name. +// +// Deprecated: use [mangling.NameMangler.ToCommandName] instead. +func ToCommandName(name string) string { return swagNameMangler.ToCommandName(name) } + +// ToHumanNameLower represents a code name as a human series of words. +// +// Deprecated: use [mangling.NameMangler.ToHumanNameLower] instead. +func ToHumanNameLower(name string) string { return swagNameMangler.ToHumanNameLower(name) } + +// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized. +// +// Deprecated: use [mangling.NameMangler.ToHumanNameTitle] instead. +func ToHumanNameTitle(name string) string { return swagNameMangler.ToHumanNameTitle(name) } + +// ToJSONName camel-cases a name which can be underscored or pascal-cased. +// +// Deprecated: use [mangling.NameMangler.ToJSONName] instead. +func ToJSONName(name string) string { return swagNameMangler.ToJSONName(name) } + +// ToVarName camel-cases a name which can be underscored or pascal-cased. +// +// Deprecated: use [mangling.NameMangler.ToVarName] instead. +func ToVarName(name string) string { return swagNameMangler.ToVarName(name) } + +// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes. +// +// Deprecated: use [mangling.NameMangler.ToGoName] instead. +func ToGoName(name string) string { return swagNameMangler.ToGoName(name) } diff --git a/api/vendor/github.com/go-openapi/swag/name_lexem.go b/api/vendor/github.com/go-openapi/swag/name_lexem.go deleted file mode 100644 index 8bb64ac32f90..000000000000 --- a/api/vendor/github.com/go-openapi/swag/name_lexem.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "unicode" - "unicode/utf8" -) - -type ( - lexemKind uint8 - - nameLexem struct { - original string - matchedInitialism string - kind lexemKind - } -) - -const ( - lexemKindCasualName lexemKind = iota - lexemKindInitialismName -) - -func newInitialismNameLexem(original, matchedInitialism string) nameLexem { - return nameLexem{ - kind: lexemKindInitialismName, - original: original, - matchedInitialism: matchedInitialism, - } -} - -func newCasualNameLexem(original string) nameLexem { - return nameLexem{ - kind: lexemKindCasualName, - original: original, - } -} - -func (l nameLexem) GetUnsafeGoName() string { - if l.kind == lexemKindInitialismName { - return l.matchedInitialism - } - - var ( - first rune - rest string - ) - - for i, orig := range l.original { - if i == 0 { - first = orig - continue - } - - if i > 0 { - rest = l.original[i:] - break - } - } - - if len(l.original) > 1 { - b := poolOfBuffers.BorrowBuffer(utf8.UTFMax + len(rest)) - defer func() { - poolOfBuffers.RedeemBuffer(b) - }() - b.WriteRune(unicode.ToUpper(first)) - b.WriteString(lower(rest)) - return b.String() - } - - return l.original -} - -func (l nameLexem) GetOriginal() string { - return l.original -} - -func (l nameLexem) IsInitialism() bool { - return l.kind == lexemKindInitialismName -} diff --git a/api/vendor/github.com/go-openapi/swag/net.go b/api/vendor/github.com/go-openapi/swag/net.go deleted file mode 100644 index 821235f84d4a..000000000000 --- a/api/vendor/github.com/go-openapi/swag/net.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "net" - "strconv" -) - -// SplitHostPort splits a network address into a host and a port. -// The port is -1 when there is no port to be found -func SplitHostPort(addr string) (host string, port int, err error) { - h, p, err := net.SplitHostPort(addr) - if err != nil { - return "", -1, err - } - if p == "" { - return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} - } - - pi, err := strconv.Atoi(p) - if err != nil { - return "", -1, err - } - return h, pi, nil -} diff --git a/api/vendor/github.com/go-openapi/swag/netutils/LICENSE b/api/vendor/github.com/go-openapi/swag/netutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/netutils/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/api/vendor/github.com/go-openapi/swag/netutils/doc.go b/api/vendor/github.com/go-openapi/swag/netutils/doc.go new file mode 100644 index 000000000000..74282f8e51c5 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/netutils/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package netutils provides helpers for network-related tasks. +package netutils diff --git a/api/vendor/github.com/go-openapi/swag/netutils/net.go b/api/vendor/github.com/go-openapi/swag/netutils/net.go new file mode 100644 index 000000000000..82a1544af7bf --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/netutils/net.go @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package netutils + +import ( + "net" + "strconv" +) + +// SplitHostPort splits a network address into a host and a port. +// +// The difference with the standard net.SplitHostPort is that the port is converted to an int. +// +// The port is -1 when there is no port to be found. +func SplitHostPort(addr string) (host string, port int, err error) { + h, p, err := net.SplitHostPort(addr) + if err != nil { + return "", -1, err + } + if p == "" { + return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} + } + + pi, err := strconv.Atoi(p) + if err != nil { + return "", -1, err + } + + return h, pi, nil +} diff --git a/api/vendor/github.com/go-openapi/swag/netutils_iface.go b/api/vendor/github.com/go-openapi/swag/netutils_iface.go new file mode 100644 index 000000000000..d658de25b3f3 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/netutils_iface.go @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/netutils" + +// SplitHostPort splits a network address into a host and a port. +// +// Deprecated: use [netutils.SplitHostPort] instead. +func SplitHostPort(addr string) (host string, port int, err error) { + return netutils.SplitHostPort(addr) +} diff --git a/api/vendor/github.com/go-openapi/swag/split.go b/api/vendor/github.com/go-openapi/swag/split.go deleted file mode 100644 index 274727a866c4..000000000000 --- a/api/vendor/github.com/go-openapi/swag/split.go +++ /dev/null @@ -1,508 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "bytes" - "sync" - "unicode" - "unicode/utf8" -) - -type ( - splitter struct { - initialisms []string - initialismsRunes [][]rune - initialismsUpperCased [][]rune // initialisms cached in their trimmed, upper-cased version - postSplitInitialismCheck bool - } - - splitterOption func(*splitter) - - initialismMatch struct { - body []rune - start, end int - complete bool - } - initialismMatches []initialismMatch -) - -type ( - // memory pools of temporary objects. - // - // These are used to recycle temporarily allocated objects - // and relieve the GC from undue pressure. - - matchesPool struct { - *sync.Pool - } - - buffersPool struct { - *sync.Pool - } - - lexemsPool struct { - *sync.Pool - } - - splittersPool struct { - *sync.Pool - } -) - -var ( - // poolOfMatches holds temporary slices for recycling during the initialism match process - poolOfMatches = matchesPool{ - Pool: &sync.Pool{ - New: func() any { - s := make(initialismMatches, 0, maxAllocMatches) - - return &s - }, - }, - } - - poolOfBuffers = buffersPool{ - Pool: &sync.Pool{ - New: func() any { - return new(bytes.Buffer) - }, - }, - } - - poolOfLexems = lexemsPool{ - Pool: &sync.Pool{ - New: func() any { - s := make([]nameLexem, 0, maxAllocMatches) - - return &s - }, - }, - } - - poolOfSplitters = splittersPool{ - Pool: &sync.Pool{ - New: func() any { - s := newSplitter() - - return &s - }, - }, - } -) - -// nameReplaceTable finds a word representation for special characters. -func nameReplaceTable(r rune) (string, bool) { - switch r { - case '@': - return "At ", true - case '&': - return "And ", true - case '|': - return "Pipe ", true - case '$': - return "Dollar ", true - case '!': - return "Bang ", true - case '-': - return "", true - case '_': - return "", true - default: - return "", false - } -} - -// split calls the splitter. -// -// Use newSplitter for more control and options -func split(str string) []string { - s := poolOfSplitters.BorrowSplitter() - lexems := s.split(str) - result := make([]string, 0, len(*lexems)) - - for _, lexem := range *lexems { - result = append(result, lexem.GetOriginal()) - } - poolOfLexems.RedeemLexems(lexems) - poolOfSplitters.RedeemSplitter(s) - - return result - -} - -func newSplitter(options ...splitterOption) splitter { - s := splitter{ - postSplitInitialismCheck: false, - initialisms: initialisms, - initialismsRunes: initialismsRunes, - initialismsUpperCased: initialismsUpperCased, - } - - for _, option := range options { - option(&s) - } - - return s -} - -// withPostSplitInitialismCheck allows to catch initialisms after main split process -func withPostSplitInitialismCheck(s *splitter) { - s.postSplitInitialismCheck = true -} - -func (p matchesPool) BorrowMatches() *initialismMatches { - s := p.Get().(*initialismMatches) - *s = (*s)[:0] // reset slice, keep allocated capacity - - return s -} - -func (p buffersPool) BorrowBuffer(size int) *bytes.Buffer { - s := p.Get().(*bytes.Buffer) - s.Reset() - - if s.Cap() < size { - s.Grow(size) - } - - return s -} - -func (p lexemsPool) BorrowLexems() *[]nameLexem { - s := p.Get().(*[]nameLexem) - *s = (*s)[:0] // reset slice, keep allocated capacity - - return s -} - -func (p splittersPool) BorrowSplitter(options ...splitterOption) *splitter { - s := p.Get().(*splitter) - s.postSplitInitialismCheck = false // reset options - for _, apply := range options { - apply(s) - } - - return s -} - -func (p matchesPool) RedeemMatches(s *initialismMatches) { - p.Put(s) -} - -func (p buffersPool) RedeemBuffer(s *bytes.Buffer) { - p.Put(s) -} - -func (p lexemsPool) RedeemLexems(s *[]nameLexem) { - p.Put(s) -} - -func (p splittersPool) RedeemSplitter(s *splitter) { - p.Put(s) -} - -func (m initialismMatch) isZero() bool { - return m.start == 0 && m.end == 0 -} - -func (s splitter) split(name string) *[]nameLexem { - nameRunes := []rune(name) - matches := s.gatherInitialismMatches(nameRunes) - if matches == nil { - return poolOfLexems.BorrowLexems() - } - - return s.mapMatchesToNameLexems(nameRunes, matches) -} - -func (s splitter) gatherInitialismMatches(nameRunes []rune) *initialismMatches { - var matches *initialismMatches - - for currentRunePosition, currentRune := range nameRunes { - // recycle these allocations as we loop over runes - // with such recycling, only 2 slices should be allocated per call - // instead of o(n). - newMatches := poolOfMatches.BorrowMatches() - - // check current initialism matches - if matches != nil { // skip first iteration - for _, match := range *matches { - if keepCompleteMatch := match.complete; keepCompleteMatch { - *newMatches = append(*newMatches, match) - continue - } - - // drop failed match - currentMatchRune := match.body[currentRunePosition-match.start] - if currentMatchRune != currentRune { - continue - } - - // try to complete ongoing match - if currentRunePosition-match.start == len(match.body)-1 { - // we are close; the next step is to check the symbol ahead - // if it is a small letter, then it is not the end of match - // but beginning of the next word - - if currentRunePosition < len(nameRunes)-1 { - nextRune := nameRunes[currentRunePosition+1] - if newWord := unicode.IsLower(nextRune); newWord { - // oh ok, it was the start of a new word - continue - } - } - - match.complete = true - match.end = currentRunePosition - } - - *newMatches = append(*newMatches, match) - } - } - - // check for new initialism matches - for i := range s.initialisms { - initialismRunes := s.initialismsRunes[i] - if initialismRunes[0] == currentRune { - *newMatches = append(*newMatches, initialismMatch{ - start: currentRunePosition, - body: initialismRunes, - complete: false, - }) - } - } - - if matches != nil { - poolOfMatches.RedeemMatches(matches) - } - matches = newMatches - } - - // up to the caller to redeem this last slice - return matches -} - -func (s splitter) mapMatchesToNameLexems(nameRunes []rune, matches *initialismMatches) *[]nameLexem { - nameLexems := poolOfLexems.BorrowLexems() - - var lastAcceptedMatch initialismMatch - for _, match := range *matches { - if !match.complete { - continue - } - - if firstMatch := lastAcceptedMatch.isZero(); firstMatch { - s.appendBrokenDownCasualString(nameLexems, nameRunes[:match.start]) - *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) - - lastAcceptedMatch = match - - continue - } - - if overlappedMatch := match.start <= lastAcceptedMatch.end; overlappedMatch { - continue - } - - middle := nameRunes[lastAcceptedMatch.end+1 : match.start] - s.appendBrokenDownCasualString(nameLexems, middle) - *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) - - lastAcceptedMatch = match - } - - // we have not found any accepted matches - if lastAcceptedMatch.isZero() { - *nameLexems = (*nameLexems)[:0] - s.appendBrokenDownCasualString(nameLexems, nameRunes) - } else if lastAcceptedMatch.end+1 != len(nameRunes) { - rest := nameRunes[lastAcceptedMatch.end+1:] - s.appendBrokenDownCasualString(nameLexems, rest) - } - - poolOfMatches.RedeemMatches(matches) - - return nameLexems -} - -func (s splitter) breakInitialism(original string) nameLexem { - return newInitialismNameLexem(original, original) -} - -func (s splitter) appendBrokenDownCasualString(segments *[]nameLexem, str []rune) { - currentSegment := poolOfBuffers.BorrowBuffer(len(str)) // unlike strings.Builder, bytes.Buffer initial storage can reused - defer func() { - poolOfBuffers.RedeemBuffer(currentSegment) - }() - - addCasualNameLexem := func(original string) { - *segments = append(*segments, newCasualNameLexem(original)) - } - - addInitialismNameLexem := func(original, match string) { - *segments = append(*segments, newInitialismNameLexem(original, match)) - } - - var addNameLexem func(string) - if s.postSplitInitialismCheck { - addNameLexem = func(original string) { - for i := range s.initialisms { - if isEqualFoldIgnoreSpace(s.initialismsUpperCased[i], original) { - addInitialismNameLexem(original, s.initialisms[i]) - - return - } - } - - addCasualNameLexem(original) - } - } else { - addNameLexem = addCasualNameLexem - } - - for _, rn := range str { - if replace, found := nameReplaceTable(rn); found { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - currentSegment.Reset() - } - - if replace != "" { - addNameLexem(replace) - } - - continue - } - - if !unicode.In(rn, unicode.L, unicode.M, unicode.N, unicode.Pc) { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - currentSegment.Reset() - } - - continue - } - - if unicode.IsUpper(rn) { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - } - currentSegment.Reset() - } - - currentSegment.WriteRune(rn) - } - - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - } -} - -// isEqualFoldIgnoreSpace is the same as strings.EqualFold, but -// it ignores leading and trailing blank spaces in the compared -// string. -// -// base is assumed to be composed of upper-cased runes, and be already -// trimmed. -// -// This code is heavily inspired from strings.EqualFold. -func isEqualFoldIgnoreSpace(base []rune, str string) bool { - var i, baseIndex int - // equivalent to b := []byte(str), but without data copy - b := hackStringBytes(str) - - for i < len(b) { - if c := b[i]; c < utf8.RuneSelf { - // fast path for ASCII - if c != ' ' && c != '\t' { - break - } - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if !unicode.IsSpace(r) { - break - } - i += size - } - - if i >= len(b) { - return len(base) == 0 - } - - for _, baseRune := range base { - if i >= len(b) { - break - } - - if c := b[i]; c < utf8.RuneSelf { - // single byte rune case (ASCII) - if baseRune >= utf8.RuneSelf { - return false - } - - baseChar := byte(baseRune) - if c != baseChar && - !('a' <= c && c <= 'z' && c-'a'+'A' == baseChar) { - return false - } - - baseIndex++ - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if unicode.ToUpper(r) != baseRune { - return false - } - baseIndex++ - i += size - } - - if baseIndex != len(base) { - return false - } - - // all passed: now we should only have blanks - for i < len(b) { - if c := b[i]; c < utf8.RuneSelf { - // fast path for ASCII - if c != ' ' && c != '\t' { - return false - } - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if !unicode.IsSpace(r) { - return false - } - - i += size - } - - return true -} diff --git a/api/vendor/github.com/go-openapi/swag/stringutils/LICENSE b/api/vendor/github.com/go-openapi/swag/stringutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/stringutils/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/api/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go b/api/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go new file mode 100644 index 000000000000..28056ad25c38 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package stringutils + +import "strings" + +const ( + // collectionFormatComma = "csv" + collectionFormatSpace = "ssv" + collectionFormatTab = "tsv" + collectionFormatPipe = "pipes" + collectionFormatMulti = "multi" + + collectionFormatDefaultSep = "," +) + +// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute): +// +// ssv: space separated value +// tsv: tab separated value +// pipes: pipe (|) separated value +// csv: comma separated value (default) +func JoinByFormat(data []string, format string) []string { + if len(data) == 0 { + return data + } + var sep string + switch format { + case collectionFormatSpace: + sep = " " + case collectionFormatTab: + sep = "\t" + case collectionFormatPipe: + sep = "|" + case collectionFormatMulti: + return data + default: + sep = collectionFormatDefaultSep + } + return []string{strings.Join(data, sep)} +} + +// SplitByFormat splits a string by a known format: +// +// ssv: space separated value +// tsv: tab separated value +// pipes: pipe (|) separated value +// csv: comma separated value (default) +func SplitByFormat(data, format string) []string { + if data == "" { + return nil + } + var sep string + switch format { + case collectionFormatSpace: + sep = " " + case collectionFormatTab: + sep = "\t" + case collectionFormatPipe: + sep = "|" + case collectionFormatMulti: + return nil + default: + sep = collectionFormatDefaultSep + } + var result []string + for _, s := range strings.Split(data, sep) { + if ts := strings.TrimSpace(s); ts != "" { + result = append(result, ts) + } + } + return result +} diff --git a/api/vendor/github.com/go-openapi/swag/stringutils/doc.go b/api/vendor/github.com/go-openapi/swag/stringutils/doc.go new file mode 100644 index 000000000000..c6d17a1160bd --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/stringutils/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package stringutils exposes helpers to search and process strings. +package stringutils diff --git a/api/vendor/github.com/go-openapi/swag/stringutils/strings.go b/api/vendor/github.com/go-openapi/swag/stringutils/strings.go new file mode 100644 index 000000000000..cd792b7d0834 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/stringutils/strings.go @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package stringutils + +import ( + "slices" + "strings" +) + +// ContainsStrings searches a slice of strings for a case-sensitive match +// +// Now equivalent to the standard library [slice.Contains]. +func ContainsStrings(coll []string, item string) bool { + return slices.Contains(coll, item) +} + +// ContainsStringsCI searches a slice of strings for a case-insensitive match +func ContainsStringsCI(coll []string, item string) bool { + return slices.ContainsFunc(coll, func(e string) bool { + return strings.EqualFold(e, item) + }) +} diff --git a/api/vendor/github.com/go-openapi/swag/stringutils_iface.go b/api/vendor/github.com/go-openapi/swag/stringutils_iface.go new file mode 100644 index 000000000000..dbfa48484306 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/stringutils_iface.go @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/stringutils" + +// ContainsStrings searches a slice of strings for a case-sensitive match. +// +// Deprecated: use [slices.Contains] or [stringutils.ContainsStrings] instead. +func ContainsStrings(coll []string, item string) bool { + return stringutils.ContainsStrings(coll, item) +} + +// ContainsStringsCI searches a slice of strings for a case-insensitive match. +// +// Deprecated: use [stringutils.ContainsStringsCI] instead. +func ContainsStringsCI(coll []string, item string) bool { + return stringutils.ContainsStringsCI(coll, item) +} + +// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute). +// +// Deprecated: use [stringutils.JoinByFormat] instead. +func JoinByFormat(data []string, format string) []string { + return stringutils.JoinByFormat(data, format) +} + +// SplitByFormat splits a string by a known format. +// +// Deprecated: use [stringutils.SplitByFormat] instead. +func SplitByFormat(data, format string) []string { + return stringutils.SplitByFormat(data, format) +} diff --git a/api/vendor/github.com/go-openapi/swag/typeutils/LICENSE b/api/vendor/github.com/go-openapi/swag/typeutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/typeutils/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/api/vendor/github.com/go-openapi/swag/typeutils/doc.go b/api/vendor/github.com/go-openapi/swag/typeutils/doc.go new file mode 100644 index 000000000000..66bed20dff0e --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/typeutils/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package typeutils exposes utilities to inspect generic types. +package typeutils diff --git a/api/vendor/github.com/go-openapi/swag/typeutils/types.go b/api/vendor/github.com/go-openapi/swag/typeutils/types.go new file mode 100644 index 000000000000..55487a673c4b --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/typeutils/types.go @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package typeutils + +import "reflect" + +type zeroable interface { + IsZero() bool +} + +// 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 any) bool { + v := reflect.ValueOf(data) + // check for nil data + switch v.Kind() { //nolint:exhaustive + case + reflect.Interface, + reflect.Func, + reflect.Chan, + reflect.Pointer, + reflect.UnsafePointer, + reflect.Map, + 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 + switch v.Kind() { //nolint:exhaustive + case reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Struct, reflect.Array: + return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) + case reflect.Invalid: + return true + default: + return false + } +} + +// IsNil checks if input is nil. +// +// For types chan, func, interface, map, pointer, or slice it returns true if its argument is nil. +// +// See [reflect.Value.IsNil]. +func IsNil(input any) bool { + if input == nil { + return true + } + + kind := reflect.TypeOf(input).Kind() + switch kind { //nolint:exhaustive + case reflect.Pointer, + reflect.UnsafePointer, + reflect.Map, + reflect.Slice, + reflect.Chan, + reflect.Interface, + reflect.Func: + return reflect.ValueOf(input).IsNil() + default: + return false + } +} diff --git a/api/vendor/github.com/go-openapi/swag/typeutils_iface.go b/api/vendor/github.com/go-openapi/swag/typeutils_iface.go new file mode 100644 index 000000000000..b63813ea408e --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/typeutils_iface.go @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/typeutils" + +// IsZero returns true when the value passed into the function is a zero value. +// This allows for safer checking of interface values. +// +// Deprecated: use [typeutils.IsZero] instead. +func IsZero(data any) bool { return typeutils.IsZero(data) } diff --git a/api/vendor/github.com/go-openapi/swag/util.go b/api/vendor/github.com/go-openapi/swag/util.go deleted file mode 100644 index 5051401c49ff..000000000000 --- a/api/vendor/github.com/go-openapi/swag/util.go +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "reflect" - "strings" - "unicode" - "unicode/utf8" -) - -// GoNamePrefixFunc sets an optional rule to prefix go names -// which do not start with a letter. -// -// The prefix function is assumed to return a string that starts with an upper case letter. -// -// e.g. to help convert "123" into "{prefix}123" -// -// The default is to prefix with "X" -var GoNamePrefixFunc func(string) string - -func prefixFunc(name, in string) string { - if GoNamePrefixFunc == nil { - return "X" + in - } - - return GoNamePrefixFunc(name) + in -} - -const ( - // collectionFormatComma = "csv" - collectionFormatSpace = "ssv" - collectionFormatTab = "tsv" - collectionFormatPipe = "pipes" - collectionFormatMulti = "multi" -) - -// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute): -// -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func JoinByFormat(data []string, format string) []string { - if len(data) == 0 { - return data - } - var sep string - switch format { - case collectionFormatSpace: - sep = " " - case collectionFormatTab: - sep = "\t" - case collectionFormatPipe: - sep = "|" - case collectionFormatMulti: - return data - default: - sep = "," - } - return []string{strings.Join(data, sep)} -} - -// SplitByFormat splits a string by a known format: -// -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func SplitByFormat(data, format string) []string { - if data == "" { - return nil - } - var sep string - switch format { - case collectionFormatSpace: - sep = " " - case collectionFormatTab: - sep = "\t" - case collectionFormatPipe: - sep = "|" - case collectionFormatMulti: - return nil - default: - sep = "," - } - var result []string - for _, s := range strings.Split(data, sep) { - if ts := strings.TrimSpace(s); ts != "" { - result = append(result, ts) - } - } - return result -} - -// Removes leading whitespaces -func trim(str string) string { - return strings.TrimSpace(str) -} - -// Shortcut to strings.ToUpper() -func upper(str string) string { - return strings.ToUpper(trim(str)) -} - -// Shortcut to strings.ToLower() -func lower(str string) string { - return strings.ToLower(trim(str)) -} - -// Camelize an uppercased word -func Camelize(word string) string { - camelized := poolOfBuffers.BorrowBuffer(len(word)) - defer func() { - poolOfBuffers.RedeemBuffer(camelized) - }() - - for pos, ru := range []rune(word) { - if pos > 0 { - camelized.WriteRune(unicode.ToLower(ru)) - } else { - camelized.WriteRune(unicode.ToUpper(ru)) - } - } - return camelized.String() -} - -// ToFileName lowercases and underscores a go type name -func ToFileName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for _, w := range in { - out = append(out, lower(w)) - } - - return strings.Join(out, "_") -} - -// ToCommandName lowercases and underscores a go type name -func ToCommandName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for _, w := range in { - out = append(out, lower(w)) - } - return strings.Join(out, "-") -} - -// ToHumanNameLower represents a code name as a human series of words -func ToHumanNameLower(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - in := s.split(name) - poolOfSplitters.RedeemSplitter(s) - out := make([]string, 0, len(*in)) - - for _, w := range *in { - if !w.IsInitialism() { - out = append(out, lower(w.GetOriginal())) - } else { - out = append(out, trim(w.GetOriginal())) - } - } - poolOfLexems.RedeemLexems(in) - - return strings.Join(out, " ") -} - -// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized -func ToHumanNameTitle(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - in := s.split(name) - poolOfSplitters.RedeemSplitter(s) - - out := make([]string, 0, len(*in)) - for _, w := range *in { - original := trim(w.GetOriginal()) - if !w.IsInitialism() { - out = append(out, Camelize(original)) - } else { - out = append(out, original) - } - } - poolOfLexems.RedeemLexems(in) - - return strings.Join(out, " ") -} - -// ToJSONName camelcases a name which can be underscored or pascal cased -func ToJSONName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for i, w := range in { - if i == 0 { - out = append(out, lower(w)) - continue - } - out = append(out, Camelize(trim(w))) - } - return strings.Join(out, "") -} - -// ToVarName camelcases a name which can be underscored or pascal cased -func ToVarName(name string) string { - res := ToGoName(name) - if isInitialism(res) { - return lower(res) - } - if len(res) <= 1 { - return lower(res) - } - return lower(res[:1]) + res[1:] -} - -// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes -func ToGoName(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - lexems := s.split(name) - poolOfSplitters.RedeemSplitter(s) - defer func() { - poolOfLexems.RedeemLexems(lexems) - }() - lexemes := *lexems - - if len(lexemes) == 0 { - return "" - } - - result := poolOfBuffers.BorrowBuffer(len(name)) - defer func() { - poolOfBuffers.RedeemBuffer(result) - }() - - // check if not starting with a letter, upper case - firstPart := lexemes[0].GetUnsafeGoName() - if lexemes[0].IsInitialism() { - firstPart = upper(firstPart) - } - - if c := firstPart[0]; c < utf8.RuneSelf { - // ASCII - switch { - case 'A' <= c && c <= 'Z': - result.WriteString(firstPart) - case 'a' <= c && c <= 'z': - result.WriteByte(c - 'a' + 'A') - result.WriteString(firstPart[1:]) - default: - result.WriteString(prefixFunc(name, firstPart)) - // NOTE: no longer check if prefixFunc returns a string that starts with uppercase: - // assume this is always the case - } - } else { - // unicode - firstRune, _ := utf8.DecodeRuneInString(firstPart) - switch { - case !unicode.IsLetter(firstRune): - result.WriteString(prefixFunc(name, firstPart)) - case !unicode.IsUpper(firstRune): - result.WriteString(prefixFunc(name, firstPart)) - /* - result.WriteRune(unicode.ToUpper(firstRune)) - result.WriteString(firstPart[offset:]) - */ - default: - result.WriteString(firstPart) - } - } - - for _, lexem := range lexemes[1:] { - goName := lexem.GetUnsafeGoName() - - // to support old behavior - if lexem.IsInitialism() { - goName = upper(goName) - } - result.WriteString(goName) - } - - return result.String() -} - -// ContainsStrings searches a slice of strings for a case-sensitive match -func ContainsStrings(coll []string, item string) bool { - for _, a := range coll { - if a == item { - return true - } - } - return false -} - -// ContainsStringsCI searches a slice of strings for a case-insensitive match -func ContainsStringsCI(coll []string, item string) bool { - for _, a := range coll { - if strings.EqualFold(a, item) { - return true - } - } - return false -} - -type zeroable interface { - IsZero() bool -} - -// 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() { //nolint:exhaustive - 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 - switch v.Kind() { //nolint:exhaustive - case reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Struct, reflect.Array: - return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) - case reflect.Invalid: - return true - default: - return false - } -} - -// CommandLineOptionsGroup represents a group of user-defined command line options -type CommandLineOptionsGroup struct { - ShortDescription string - LongDescription string - Options interface{} -} diff --git a/api/vendor/github.com/go-openapi/swag/yaml.go b/api/vendor/github.com/go-openapi/swag/yaml.go deleted file mode 100644 index 575346539ac8..000000000000 --- a/api/vendor/github.com/go-openapi/swag/yaml.go +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "encoding/json" - "fmt" - "path/filepath" - "reflect" - "sort" - "strconv" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" - yaml "gopkg.in/yaml.v3" -) - -// YAMLMatcher matches yaml -func YAMLMatcher(path string) bool { - ext := filepath.Ext(path) - return ext == ".yaml" || ext == ".yml" -} - -// YAMLToJSON converts YAML unmarshaled data into json compatible data -func YAMLToJSON(data interface{}) (json.RawMessage, error) { - jm, err := transformData(data) - if err != nil { - return nil, err - } - b, err := WriteJSON(jm) - return json.RawMessage(b), err -} - -// BytesToYAMLDoc converts a byte slice into a YAML document -func BytesToYAMLDoc(data []byte) (interface{}, error) { - var document yaml.Node // preserve order that is present in the document - if err := yaml.Unmarshal(data, &document); err != nil { - return nil, err - } - if document.Kind != yaml.DocumentNode || len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { - return nil, fmt.Errorf("only YAML documents that are objects are supported: %w", ErrYAML) - } - return &document, nil -} - -func yamlNode(root *yaml.Node) (interface{}, error) { - switch root.Kind { - case yaml.DocumentNode: - return yamlDocument(root) - case yaml.SequenceNode: - return yamlSequence(root) - case yaml.MappingNode: - return yamlMapping(root) - case yaml.ScalarNode: - return yamlScalar(root) - case yaml.AliasNode: - return yamlNode(root.Alias) - default: - return nil, fmt.Errorf("unsupported YAML node type: %v: %w", root.Kind, ErrYAML) - } -} - -func yamlDocument(node *yaml.Node) (interface{}, error) { - if len(node.Content) != 1 { - return nil, fmt.Errorf("unexpected YAML Document node content length: %d: %w", len(node.Content), ErrYAML) - } - return yamlNode(node.Content[0]) -} - -func yamlMapping(node *yaml.Node) (interface{}, error) { - const sensibleAllocDivider = 2 - m := make(JSONMapSlice, len(node.Content)/sensibleAllocDivider) - - var j int - for i := 0; i < len(node.Content); i += 2 { - var nmi JSONMapItem - k, err := yamlStringScalarC(node.Content[i]) - if err != nil { - return nil, fmt.Errorf("unable to decode YAML map key: %w: %w", err, ErrYAML) - } - nmi.Key = k - v, err := yamlNode(node.Content[i+1]) - if err != nil { - return nil, fmt.Errorf("unable to process YAML map value for key %q: %w: %w", k, err, ErrYAML) - } - nmi.Value = v - m[j] = nmi - j++ - } - return m, nil -} - -func yamlSequence(node *yaml.Node) (interface{}, error) { - s := make([]interface{}, 0) - - for i := 0; i < len(node.Content); i++ { - - v, err := yamlNode(node.Content[i]) - if err != nil { - return nil, fmt.Errorf("unable to decode YAML sequence value: %w: %w", err, ErrYAML) - } - s = append(s, v) - } - return s, nil -} - -const ( // See https://yaml.org/type/ - yamlStringScalar = "tag:yaml.org,2002:str" - yamlIntScalar = "tag:yaml.org,2002:int" - yamlBoolScalar = "tag:yaml.org,2002:bool" - yamlFloatScalar = "tag:yaml.org,2002:float" - yamlTimestamp = "tag:yaml.org,2002:timestamp" - yamlNull = "tag:yaml.org,2002:null" -) - -func yamlScalar(node *yaml.Node) (interface{}, error) { - switch node.LongTag() { - case yamlStringScalar: - return node.Value, nil - case yamlBoolScalar: - b, err := strconv.ParseBool(node.Value) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting bool content: %w: %w", node.Value, err, ErrYAML) - } - return b, nil - case yamlIntScalar: - i, err := strconv.ParseInt(node.Value, 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting integer content: %w: %w", node.Value, err, ErrYAML) - } - return i, nil - case yamlFloatScalar: - f, err := strconv.ParseFloat(node.Value, 64) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting float content: %w: %w", node.Value, err, ErrYAML) - } - return f, nil - case yamlTimestamp: - return node.Value, nil - case yamlNull: - return nil, nil //nolint:nilnil - default: - return nil, fmt.Errorf("YAML tag %q is not supported: %w", node.LongTag(), ErrYAML) - } -} - -func yamlStringScalarC(node *yaml.Node) (string, error) { - if node.Kind != yaml.ScalarNode { - return "", fmt.Errorf("expecting a string scalar but got %q: %w", node.Kind, ErrYAML) - } - switch node.LongTag() { - case yamlStringScalar, yamlIntScalar, yamlFloatScalar: - return node.Value, nil - default: - return "", fmt.Errorf("YAML tag %q is not supported as map key: %w", node.LongTag(), ErrYAML) - } -} - -// JSONMapSlice represent a JSON object, with the order of keys maintained -type JSONMapSlice []JSONMapItem - -// MarshalJSON renders a JSONMapSlice as JSON -func (s JSONMapSlice) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -// MarshalEasyJSON renders a JSONMapSlice as JSON, using easyJSON -func (s JSONMapSlice) MarshalEasyJSON(w *jwriter.Writer) { - w.RawByte('{') - - ln := len(s) - last := ln - 1 - for i := 0; i < ln; i++ { - s[i].MarshalEasyJSON(w) - if i != last { // last item - w.RawByte(',') - } - } - - w.RawByte('}') -} - -// UnmarshalJSON makes a JSONMapSlice from JSON -func (s *JSONMapSlice) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON makes a JSONMapSlice from JSON, using easyJSON -func (s *JSONMapSlice) UnmarshalEasyJSON(in *jlexer.Lexer) { - if in.IsNull() { - in.Skip() - return - } - - var result JSONMapSlice - in.Delim('{') - for !in.IsDelim('}') { - var mi JSONMapItem - mi.UnmarshalEasyJSON(in) - result = append(result, mi) - } - *s = result -} - -func (s JSONMapSlice) MarshalYAML() (interface{}, error) { - var n yaml.Node - n.Kind = yaml.DocumentNode - var nodes []*yaml.Node - for _, item := range s { - nn, err := json2yaml(item.Value) - if err != nil { - return nil, err - } - ns := []*yaml.Node{ - { - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: item.Key, - }, - nn, - } - nodes = append(nodes, ns...) - } - - n.Content = []*yaml.Node{ - { - Kind: yaml.MappingNode, - Content: nodes, - }, - } - - return yaml.Marshal(&n) -} - -func isNil(input interface{}) bool { - if input == nil { - return true - } - kind := reflect.TypeOf(input).Kind() - switch kind { //nolint:exhaustive - case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: - return reflect.ValueOf(input).IsNil() - default: - return false - } -} - -func json2yaml(item interface{}) (*yaml.Node, error) { - if isNil(item) { - return &yaml.Node{ - Kind: yaml.ScalarNode, - Value: "null", - }, nil - } - - switch val := item.(type) { - case JSONMapSlice: - var n yaml.Node - n.Kind = yaml.MappingNode - for i := range val { - childNode, err := json2yaml(&val[i].Value) - if err != nil { - return nil, err - } - n.Content = append(n.Content, &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: val[i].Key, - }, childNode) - } - return &n, nil - case map[string]interface{}: - var n yaml.Node - n.Kind = yaml.MappingNode - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - v := val[k] - childNode, err := json2yaml(v) - if err != nil { - return nil, err - } - n.Content = append(n.Content, &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: k, - }, childNode) - } - return &n, nil - case []interface{}: - var n yaml.Node - n.Kind = yaml.SequenceNode - for i := range val { - childNode, err := json2yaml(val[i]) - if err != nil { - return nil, err - } - n.Content = append(n.Content, childNode) - } - return &n, nil - case string: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: val, - }, nil - case float64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlFloatScalar, - Value: strconv.FormatFloat(val, 'f', -1, 64), - }, nil - case int64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlIntScalar, - Value: strconv.FormatInt(val, 10), - }, nil - case uint64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlIntScalar, - Value: strconv.FormatUint(val, 10), - }, nil - case bool: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlBoolScalar, - Value: strconv.FormatBool(val), - }, nil - default: - return nil, fmt.Errorf("unhandled type: %T: %w", val, ErrYAML) - } -} - -// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice -type JSONMapItem struct { - Key string - Value interface{} -} - -// MarshalJSON renders a JSONMapItem as JSON -func (s JSONMapItem) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -// MarshalEasyJSON renders a JSONMapItem as JSON, using easyJSON -func (s JSONMapItem) MarshalEasyJSON(w *jwriter.Writer) { - w.String(s.Key) - w.RawByte(':') - w.Raw(WriteJSON(s.Value)) -} - -// UnmarshalJSON makes a JSONMapItem from JSON -func (s *JSONMapItem) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON makes a JSONMapItem from JSON, using easyJSON -func (s *JSONMapItem) UnmarshalEasyJSON(in *jlexer.Lexer) { - key := in.UnsafeString() - in.WantColon() - value := in.Interface() - in.WantComma() - s.Key = key - s.Value = value -} - -func transformData(input interface{}) (out interface{}, err error) { - format := func(t interface{}) (string, error) { - switch k := t.(type) { - case string: - return k, nil - case uint: - return strconv.FormatUint(uint64(k), 10), nil - case uint8: - return strconv.FormatUint(uint64(k), 10), nil - case uint16: - return strconv.FormatUint(uint64(k), 10), nil - case uint32: - return strconv.FormatUint(uint64(k), 10), nil - case uint64: - return strconv.FormatUint(k, 10), nil - case int: - return strconv.Itoa(k), nil - case int8: - return strconv.FormatInt(int64(k), 10), nil - case int16: - return strconv.FormatInt(int64(k), 10), nil - case int32: - return strconv.FormatInt(int64(k), 10), nil - case int64: - return strconv.FormatInt(k, 10), nil - default: - return "", fmt.Errorf("unexpected map key type, got: %T: %w", k, ErrYAML) - } - } - - switch in := input.(type) { - case yaml.Node: - return yamlNode(&in) - case *yaml.Node: - return yamlNode(in) - case map[interface{}]interface{}: - o := make(JSONMapSlice, 0, len(in)) - for ke, va := range in { - var nmi JSONMapItem - if nmi.Key, err = format(ke); err != nil { - return nil, err - } - - v, ert := transformData(va) - if ert != nil { - return nil, ert - } - nmi.Value = v - o = append(o, nmi) - } - return o, nil - case []interface{}: - len1 := len(in) - o := make([]interface{}, len1) - for i := 0; i < len1; i++ { - o[i], err = transformData(in[i]) - if err != nil { - return nil, err - } - } - return o, nil - } - return input, nil -} - -// YAMLDoc loads a yaml document from either http or a file and converts it to json -func YAMLDoc(path string) (json.RawMessage, error) { - yamlDoc, err := YAMLData(path) - if err != nil { - return nil, err - } - - data, err := YAMLToJSON(yamlDoc) - if err != nil { - return nil, err - } - - return data, nil -} - -// YAMLData loads a yaml document from either http or a file -func YAMLData(path string) (interface{}, error) { - data, err := LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - - return BytesToYAMLDoc(data) -} diff --git a/api/vendor/github.com/go-openapi/swag/yamlutils/LICENSE b/api/vendor/github.com/go-openapi/swag/yamlutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/yamlutils/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/api/vendor/github.com/go-openapi/swag/yamlutils/doc.go b/api/vendor/github.com/go-openapi/swag/yamlutils/doc.go new file mode 100644 index 000000000000..7bb92a82f1b0 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/yamlutils/doc.go @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package yamlutils provides utilities to work with YAML documents. +// +// - [BytesToYAMLDoc] to construct a [yaml.Node] document +// - [YAMLToJSON] to convert a [yaml.Node] document to JSON bytes +// - [YAMLMapSlice] to serialize and deserialize YAML with the order of keys maintained +package yamlutils + +import ( + _ "go.yaml.in/yaml/v3" // for documentation purpose only +) diff --git a/api/vendor/github.com/go-openapi/swag/yamlutils/errors.go b/api/vendor/github.com/go-openapi/swag/yamlutils/errors.go new file mode 100644 index 000000000000..e87bc5e8beb3 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/yamlutils/errors.go @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package yamlutils + +type yamlError string + +const ( + // ErrYAML is an error raised by YAML utilities + ErrYAML yamlError = "yaml error" +) + +func (e yamlError) Error() string { + return string(e) +} diff --git a/api/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go b/api/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go new file mode 100644 index 000000000000..3daf68dbba0c --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go @@ -0,0 +1,316 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package yamlutils + +import ( + "fmt" + "iter" + "slices" + "sort" + "strconv" + + "github.com/go-openapi/swag/conv" + "github.com/go-openapi/swag/jsonutils" + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" + "github.com/go-openapi/swag/typeutils" + yaml "go.yaml.in/yaml/v3" +) + +var ( + _ yaml.Marshaler = YAMLMapSlice{} + _ yaml.Unmarshaler = &YAMLMapSlice{} +) + +// YAMLMapSlice represents a YAML object, with the order of keys maintained. +// +// It is similar to [jsonutils.JSONMapSlice] and also knows how to marshal and unmarshal YAML. +// +// It behaves like an ordered map, but keys can't be accessed in constant time. +type YAMLMapSlice []YAMLMapItem + +// YAMLMapItem represents the value of a key in a YAML object held by [YAMLMapSlice]. +// +// It is entirely equivalent to [jsonutils.JSONMapItem], with the same limitation that +// you should not Marshal or Unmarshal directly this type, outside of a [YAMLMapSlice]. +type YAMLMapItem = jsonutils.JSONMapItem + +func (s YAMLMapSlice) OrderedItems() iter.Seq2[string, any] { + return func(yield func(string, any) bool) { + for _, item := range s { + if !yield(item.Key, item.Value) { + return + } + } + } +} + +// SetOrderedItems implements [ifaces.SetOrdered]: it merges keys passed by the iterator argument +// into the [YAMLMapSlice]. +func (s *YAMLMapSlice) SetOrderedItems(items iter.Seq2[string, any]) { + if items == nil { + // force receiver to be a nil slice + *s = nil + + return + } + + m := *s + if len(m) > 0 { + // update mode: short-circuited when unmarshaling fresh data structures + idx := make(map[string]int, len(m)) + + for i, item := range m { + idx[item.Key] = i + } + + for k, v := range items { + idx, ok := idx[k] + if ok { + m[idx].Value = v + + continue + } + + m = append(m, YAMLMapItem{Key: k, Value: v}) + } + + *s = m + + return + } + + for k, v := range items { + m = append(m, YAMLMapItem{Key: k, Value: v}) + } + + *s = m +} + +// MarshalJSON renders this YAML object as JSON bytes. +// +// The difference with standard JSON marshaling is that the order of keys is maintained. +func (s YAMLMapSlice) MarshalJSON() ([]byte, error) { + return jsonutils.JSONMapSlice(s).MarshalJSON() +} + +// UnmarshalJSON builds this YAML object from JSON bytes. +// +// The difference with standard JSON marshaling is that the order of keys is maintained. +func (s *YAMLMapSlice) UnmarshalJSON(data []byte) error { + js := jsonutils.JSONMapSlice(*s) + + if err := js.UnmarshalJSON(data); err != nil { + return err + } + + *s = YAMLMapSlice(js) + + return nil +} + +// MarshalYAML produces a YAML document as bytes +// +// The difference with standard YAML marshaling is that the order of keys is maintained. +// +// It implements [yaml.Marshaler]. +func (s YAMLMapSlice) MarshalYAML() (any, error) { + if typeutils.IsNil(s) { + return []byte("null\n"), nil + } + var n yaml.Node + n.Kind = yaml.DocumentNode + var nodes []*yaml.Node + + for _, item := range s { + nn, err := json2yaml(item.Value) + if err != nil { + return nil, err + } + + ns := []*yaml.Node{ + { + Kind: yaml.ScalarNode, + Tag: yamlStringScalar, + Value: item.Key, + }, + nn, + } + nodes = append(nodes, ns...) + } + + n.Content = []*yaml.Node{ + { + Kind: yaml.MappingNode, + Content: nodes, + }, + } + + return yaml.Marshal(&n) +} + +// UnmarshalYAML builds a YAMLMapSlice object from a YAML document [yaml.Node]. +// +// It implements [yaml.Unmarshaler]. +func (s *YAMLMapSlice) UnmarshalYAML(node *yaml.Node) error { + if typeutils.IsNil(*s) { + // allow to unmarshal with a simple var declaration (nil slice) + *s = YAMLMapSlice{} + } + if node == nil { + *s = nil + return nil + } + + const sensibleAllocDivider = 2 + m := slices.Grow(*s, len(node.Content)/sensibleAllocDivider) + m = m[:0] + + for i := 0; i < len(node.Content); i += 2 { + var nmi YAMLMapItem + k, err := yamlStringScalarC(node.Content[i]) + if err != nil { + return fmt.Errorf("unable to decode YAML map key: %w: %w", err, ErrYAML) + } + nmi.Key = k + v, err := yamlNode(node.Content[i+1]) + if err != nil { + return fmt.Errorf("unable to process YAML map value for key %q: %w: %w", k, err, ErrYAML) + } + nmi.Value = v + m = append(m, nmi) + } + + *s = m + + return nil +} + +func json2yaml(item any) (*yaml.Node, error) { + if typeutils.IsNil(item) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Value: "null", + }, nil + } + + switch val := item.(type) { + case ifaces.Ordered: + return orderedYAML(val) + + case map[string]any: + var n yaml.Node + n.Kind = yaml.MappingNode + keys := make([]string, 0, len(val)) + for k := range val { + keys = append(keys, k) + } + sort.Strings(keys) + + for _, k := range keys { + v := val[k] + childNode, err := json2yaml(v) + if err != nil { + return nil, err + } + n.Content = append(n.Content, &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlStringScalar, + Value: k, + }, childNode) + } + return &n, nil + + case []any: + var n yaml.Node + n.Kind = yaml.SequenceNode + for i := range val { + childNode, err := json2yaml(val[i]) + if err != nil { + return nil, err + } + n.Content = append(n.Content, childNode) + } + return &n, nil + case string: + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlStringScalar, + Value: val, + }, nil + case float32: + return floatNode(val) + case float64: + return floatNode(val) + case int: + return integerNode(val) + case int8: + return integerNode(val) + case int16: + return integerNode(val) + case int32: + return integerNode(val) + case int64: + return integerNode(val) + case uint: + return uintegerNode(val) + case uint8: + return uintegerNode(val) + case uint16: + return uintegerNode(val) + case uint32: + return uintegerNode(val) + case uint64: + return uintegerNode(val) + case bool: + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlBoolScalar, + Value: strconv.FormatBool(val), + }, nil + default: + return nil, fmt.Errorf("unhandled type: %T: %w", val, ErrYAML) + } +} + +func floatNode[T conv.Float](val T) (*yaml.Node, error) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlFloatScalar, + Value: conv.FormatFloat(val), + }, nil +} + +func integerNode[T conv.Signed](val T) (*yaml.Node, error) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlIntScalar, + Value: conv.FormatInteger(val), + }, nil +} + +func uintegerNode[T conv.Unsigned](val T) (*yaml.Node, error) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlIntScalar, + Value: conv.FormatUinteger(val), + }, nil +} + +func orderedYAML[T ifaces.Ordered](val T) (*yaml.Node, error) { + var n yaml.Node + n.Kind = yaml.MappingNode + for key, value := range val.OrderedItems() { + childNode, err := json2yaml(value) + if err != nil { + return nil, err + } + + n.Content = append(n.Content, &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlStringScalar, + Value: key, + }, childNode) + } + return &n, nil +} diff --git a/api/vendor/github.com/go-openapi/swag/yamlutils/yaml.go b/api/vendor/github.com/go-openapi/swag/yamlutils/yaml.go new file mode 100644 index 000000000000..e3aff3c2fde9 --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/yamlutils/yaml.go @@ -0,0 +1,211 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package yamlutils + +import ( + json "encoding/json" + "fmt" + "strconv" + + "github.com/go-openapi/swag/jsonutils" + yaml "go.yaml.in/yaml/v3" +) + +// YAMLToJSON converts a YAML document into JSON bytes. +// +// Note: a YAML document is the output from a [yaml.Marshaler], e.g a pointer to a [yaml.Node]. +// +// [YAMLToJSON] is typically called after [BytesToYAMLDoc]. +func YAMLToJSON(value any) (json.RawMessage, error) { + jm, err := transformData(value) + if err != nil { + return nil, err + } + + b, err := jsonutils.WriteJSON(jm) + + return json.RawMessage(b), err +} + +// BytesToYAMLDoc converts a byte slice into a YAML document. +// +// This function only supports root documents that are objects. +// +// A YAML document is a pointer to a [yaml.Node]. +func BytesToYAMLDoc(data []byte) (any, error) { + var document yaml.Node // preserve order that is present in the document + if err := yaml.Unmarshal(data, &document); err != nil { + return nil, err + } + if document.Kind != yaml.DocumentNode || len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { + return nil, fmt.Errorf("only YAML documents that are objects are supported: %w", ErrYAML) + } + return &document, nil +} + +func yamlNode(root *yaml.Node) (any, error) { + switch root.Kind { + case yaml.DocumentNode: + return yamlDocument(root) + case yaml.SequenceNode: + return yamlSequence(root) + case yaml.MappingNode: + return yamlMapping(root) + case yaml.ScalarNode: + return yamlScalar(root) + case yaml.AliasNode: + return yamlNode(root.Alias) + default: + return nil, fmt.Errorf("unsupported YAML node type: %v: %w", root.Kind, ErrYAML) + } +} + +func yamlDocument(node *yaml.Node) (any, error) { + if len(node.Content) != 1 { + return nil, fmt.Errorf("unexpected YAML Document node content length: %d: %w", len(node.Content), ErrYAML) + } + return yamlNode(node.Content[0]) +} + +func yamlMapping(node *yaml.Node) (any, error) { + const sensibleAllocDivider = 2 // nodes concatenate (key,value) sequences + m := make(YAMLMapSlice, len(node.Content)/sensibleAllocDivider) + + if err := m.UnmarshalYAML(node); err != nil { + return nil, err + } + + return m, nil +} + +func yamlSequence(node *yaml.Node) (any, error) { + s := make([]any, 0) + + for i := range len(node.Content) { + v, err := yamlNode(node.Content[i]) + if err != nil { + return nil, fmt.Errorf("unable to decode YAML sequence value: %w: %w", err, ErrYAML) + } + s = append(s, v) + } + return s, nil +} + +const ( // See https://yaml.org/type/ + yamlStringScalar = "tag:yaml.org,2002:str" + yamlIntScalar = "tag:yaml.org,2002:int" + yamlBoolScalar = "tag:yaml.org,2002:bool" + yamlFloatScalar = "tag:yaml.org,2002:float" + yamlTimestamp = "tag:yaml.org,2002:timestamp" + yamlNull = "tag:yaml.org,2002:null" +) + +func yamlScalar(node *yaml.Node) (any, error) { + switch node.LongTag() { + case yamlStringScalar: + return node.Value, nil + case yamlBoolScalar: + b, err := strconv.ParseBool(node.Value) + if err != nil { + return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting bool content: %w: %w", node.Value, err, ErrYAML) + } + return b, nil + case yamlIntScalar: + i, err := strconv.ParseInt(node.Value, 10, 64) + if err != nil { + return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting integer content: %w: %w", node.Value, err, ErrYAML) + } + return i, nil + case yamlFloatScalar: + f, err := strconv.ParseFloat(node.Value, 64) + if err != nil { + return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting float content: %w: %w", node.Value, err, ErrYAML) + } + return f, nil + case yamlTimestamp: + // YAML timestamp is marshaled as string, not time + return node.Value, nil + case yamlNull: + return nil, nil //nolint:nilnil + default: + return nil, fmt.Errorf("YAML tag %q is not supported: %w", node.LongTag(), ErrYAML) + } +} + +func yamlStringScalarC(node *yaml.Node) (string, error) { + if node.Kind != yaml.ScalarNode { + return "", fmt.Errorf("expecting a string scalar but got %q: %w", node.Kind, ErrYAML) + } + switch node.LongTag() { + case yamlStringScalar, yamlIntScalar, yamlFloatScalar: + return node.Value, nil + default: + return "", fmt.Errorf("YAML tag %q is not supported as map key: %w", node.LongTag(), ErrYAML) + } +} + +func format(t any) (string, error) { + switch k := t.(type) { + case string: + return k, nil + case uint: + return strconv.FormatUint(uint64(k), 10), nil + case uint8: + return strconv.FormatUint(uint64(k), 10), nil + case uint16: + return strconv.FormatUint(uint64(k), 10), nil + case uint32: + return strconv.FormatUint(uint64(k), 10), nil + case uint64: + return strconv.FormatUint(k, 10), nil + case int: + return strconv.Itoa(k), nil + case int8: + return strconv.FormatInt(int64(k), 10), nil + case int16: + return strconv.FormatInt(int64(k), 10), nil + case int32: + return strconv.FormatInt(int64(k), 10), nil + case int64: + return strconv.FormatInt(k, 10), nil + default: + return "", fmt.Errorf("unexpected map key type, got: %T: %w", k, ErrYAML) + } +} + +func transformData(input any) (out any, err error) { + switch in := input.(type) { + case yaml.Node: + return yamlNode(&in) + case *yaml.Node: + return yamlNode(in) + case map[any]any: + o := make(YAMLMapSlice, 0, len(in)) + for ke, va := range in { + var nmi YAMLMapItem + if nmi.Key, err = format(ke); err != nil { + return nil, err + } + + v, ert := transformData(va) + if ert != nil { + return nil, ert + } + nmi.Value = v + o = append(o, nmi) + } + return o, nil + case []any: + len1 := len(in) + o := make([]any, len1) + for i := range len1 { + o[i], err = transformData(in[i]) + if err != nil { + return nil, err + } + } + return o, nil + } + return input, nil +} diff --git a/api/vendor/github.com/go-openapi/swag/yamlutils_iface.go b/api/vendor/github.com/go-openapi/swag/yamlutils_iface.go new file mode 100644 index 000000000000..57767efc567f --- /dev/null +++ b/api/vendor/github.com/go-openapi/swag/yamlutils_iface.go @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "encoding/json" + + "github.com/go-openapi/swag/yamlutils" +) + +// YAMLToJSON converts YAML unmarshaled data into json compatible data +// +// Deprecated: use [yamlutils.YAMLToJSON] instead. +func YAMLToJSON(data any) (json.RawMessage, error) { return yamlutils.YAMLToJSON(data) } + +// BytesToYAMLDoc converts a byte slice into a YAML document +// +// Deprecated: use [yamlutils.BytesToYAMLDoc] instead. +func BytesToYAMLDoc(data []byte) (any, error) { return yamlutils.BytesToYAMLDoc(data) } diff --git a/api/vendor/github.com/google/gnostic-models/extensions/extension.proto b/api/vendor/github.com/google/gnostic-models/extensions/extension.proto index 875137c1a860..a600429890c5 100644 --- a/api/vendor/github.com/google/gnostic-models/extensions/extension.proto +++ b/api/vendor/github.com/google/gnostic-models/extensions/extension.proto @@ -42,7 +42,7 @@ option java_package = "org.gnostic.v1"; option objc_class_prefix = "GNX"; // The Go package name. -option go_package = "./extensions;gnostic_extension_v1"; +option go_package = "github.com/google/gnostic-models/extensions;gnostic_extension_v1"; // The version number of Gnostic. message Version { diff --git a/api/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto b/api/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto index 1c59b2f4ae13..49adafcc8e2b 100644 --- a/api/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto +++ b/api/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto @@ -42,7 +42,7 @@ option java_package = "org.openapi_v2"; option objc_class_prefix = "OAS"; // The Go package name. -option go_package = "./openapiv2;openapi_v2"; +option go_package = "github.com/google/gnostic-models/openapiv2;openapi_v2"; message AdditionalPropertiesItem { oneof oneof { diff --git a/api/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.proto b/api/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.proto index 1be335b89ba0..af4b6254bc97 100644 --- a/api/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.proto +++ b/api/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 = "./openapiv3;openapi_v3"; +option go_package = "github.com/google/gnostic-models/openapiv3;openapi_v3"; message AdditionalPropertiesItem { oneof oneof { diff --git a/api/vendor/github.com/google/gnostic-models/openapiv3/annotations.proto b/api/vendor/github.com/google/gnostic-models/openapiv3/annotations.proto index 09ee0aac51b4..895b4567cd69 100644 --- a/api/vendor/github.com/google/gnostic-models/openapiv3/annotations.proto +++ b/api/vendor/github.com/google/gnostic-models/openapiv3/annotations.proto @@ -20,7 +20,7 @@ import "google/protobuf/descriptor.proto"; import "openapiv3/OpenAPIv3.proto"; // The Go package name. -option go_package = "./openapiv3;openapi_v3"; +option go_package = "github.com/google/gnostic-models/openapiv3;openapi_v3"; // 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 diff --git a/api/vendor/github.com/josharian/intern/README.md b/api/vendor/github.com/josharian/intern/README.md deleted file mode 100644 index ffc44b219b2f..000000000000 --- a/api/vendor/github.com/josharian/intern/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Docs: https://godoc.org/github.com/josharian/intern - -See also [Go issue 5160](https://golang.org/issue/5160). - -License: MIT diff --git a/api/vendor/github.com/josharian/intern/intern.go b/api/vendor/github.com/josharian/intern/intern.go deleted file mode 100644 index 7acb1fe90a11..000000000000 --- a/api/vendor/github.com/josharian/intern/intern.go +++ /dev/null @@ -1,44 +0,0 @@ -// Package intern interns strings. -// Interning is best effort only. -// Interned strings may be removed automatically -// at any time without notification. -// All functions may be called concurrently -// with themselves and each other. -package intern - -import "sync" - -var ( - pool sync.Pool = sync.Pool{ - New: func() interface{} { - return make(map[string]string) - }, - } -) - -// String returns s, interned. -func String(s string) string { - m := pool.Get().(map[string]string) - c, ok := m[s] - if ok { - pool.Put(m) - return c - } - m[s] = s - pool.Put(m) - return s -} - -// Bytes returns b converted to a string, interned. -func Bytes(b []byte) string { - m := pool.Get().(map[string]string) - c, ok := m[string(b)] - if ok { - pool.Put(m) - return c - } - s := string(b) - m[s] = s - pool.Put(m) - return s -} diff --git a/api/vendor/github.com/josharian/intern/license.md b/api/vendor/github.com/josharian/intern/license.md deleted file mode 100644 index 353d3055f0b4..000000000000 --- a/api/vendor/github.com/josharian/intern/license.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Josh Bleecher Snyder - -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/api/vendor/github.com/mailru/easyjson/LICENSE b/api/vendor/github.com/mailru/easyjson/LICENSE deleted file mode 100644 index fbff658f70d9..000000000000 --- a/api/vendor/github.com/mailru/easyjson/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2016 Mail.Ru Group - -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/api/vendor/github.com/mailru/easyjson/buffer/pool.go b/api/vendor/github.com/mailru/easyjson/buffer/pool.go deleted file mode 100644 index 598a54af9dbf..000000000000 --- a/api/vendor/github.com/mailru/easyjson/buffer/pool.go +++ /dev/null @@ -1,278 +0,0 @@ -// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to -// reduce copying and to allow reuse of individual chunks. -package buffer - -import ( - "io" - "net" - "sync" -) - -// PoolConfig contains configuration for the allocation and reuse strategy. -type PoolConfig struct { - StartSize int // Minimum chunk size that is allocated. - PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. - MaxSize int // Maximum chunk size that will be allocated. -} - -var config = PoolConfig{ - StartSize: 128, - PooledSize: 512, - MaxSize: 32768, -} - -// Reuse pool: chunk size -> pool. -var buffers = map[int]*sync.Pool{} - -func initBuffers() { - for l := config.PooledSize; l <= config.MaxSize; l *= 2 { - buffers[l] = new(sync.Pool) - } -} - -func init() { - initBuffers() -} - -// Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. -func Init(cfg PoolConfig) { - config = cfg - initBuffers() -} - -// putBuf puts a chunk to reuse pool if it can be reused. -func putBuf(buf []byte) { - size := cap(buf) - if size < config.PooledSize { - return - } - if c := buffers[size]; c != nil { - c.Put(buf[:0]) - } -} - -// getBuf gets a chunk from reuse pool or creates a new one if reuse failed. -func getBuf(size int) []byte { - if size >= config.PooledSize { - if c := buffers[size]; c != nil { - v := c.Get() - if v != nil { - return v.([]byte) - } - } - } - return make([]byte, 0, size) -} - -// Buffer is a buffer optimized for serialization without extra copying. -type Buffer struct { - - // Buf is the current chunk that can be used for serialization. - Buf []byte - - toPool []byte - bufs [][]byte -} - -// EnsureSpace makes sure that the current chunk contains at least s free bytes, -// possibly creating a new chunk. -func (b *Buffer) EnsureSpace(s int) { - if cap(b.Buf)-len(b.Buf) < s { - b.ensureSpaceSlow(s) - } -} - -func (b *Buffer) ensureSpaceSlow(s int) { - l := len(b.Buf) - if l > 0 { - if cap(b.toPool) != cap(b.Buf) { - // Chunk was reallocated, toPool can be pooled. - putBuf(b.toPool) - } - if cap(b.bufs) == 0 { - b.bufs = make([][]byte, 0, 8) - } - b.bufs = append(b.bufs, b.Buf) - l = cap(b.toPool) * 2 - } else { - l = config.StartSize - } - - if l > config.MaxSize { - l = config.MaxSize - } - b.Buf = getBuf(l) - b.toPool = b.Buf -} - -// AppendByte appends a single byte to buffer. -func (b *Buffer) AppendByte(data byte) { - b.EnsureSpace(1) - b.Buf = append(b.Buf, data) -} - -// AppendBytes appends a byte slice to buffer. -func (b *Buffer) AppendBytes(data []byte) { - if len(data) <= cap(b.Buf)-len(b.Buf) { - b.Buf = append(b.Buf, data...) // fast path - } else { - b.appendBytesSlow(data) - } -} - -func (b *Buffer) appendBytesSlow(data []byte) { - for len(data) > 0 { - b.EnsureSpace(1) - - sz := cap(b.Buf) - len(b.Buf) - if sz > len(data) { - sz = len(data) - } - - b.Buf = append(b.Buf, data[:sz]...) - data = data[sz:] - } -} - -// AppendString appends a string to buffer. -func (b *Buffer) AppendString(data string) { - if len(data) <= cap(b.Buf)-len(b.Buf) { - b.Buf = append(b.Buf, data...) // fast path - } else { - b.appendStringSlow(data) - } -} - -func (b *Buffer) appendStringSlow(data string) { - for len(data) > 0 { - b.EnsureSpace(1) - - sz := cap(b.Buf) - len(b.Buf) - if sz > len(data) { - sz = len(data) - } - - b.Buf = append(b.Buf, data[:sz]...) - data = data[sz:] - } -} - -// Size computes the size of a buffer by adding sizes of every chunk. -func (b *Buffer) Size() int { - size := len(b.Buf) - for _, buf := range b.bufs { - size += len(buf) - } - return size -} - -// DumpTo outputs the contents of a buffer to a writer and resets the buffer. -func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { - bufs := net.Buffers(b.bufs) - if len(b.Buf) > 0 { - bufs = append(bufs, b.Buf) - } - n, err := bufs.WriteTo(w) - - for _, buf := range b.bufs { - putBuf(buf) - } - putBuf(b.toPool) - - b.bufs = nil - b.Buf = nil - b.toPool = nil - - return int(n), err -} - -// BuildBytes creates a single byte slice with all the contents of the buffer. Data is -// copied if it does not fit in a single chunk. You can optionally provide one byte -// slice as argument that it will try to reuse. -func (b *Buffer) BuildBytes(reuse ...[]byte) []byte { - if len(b.bufs) == 0 { - ret := b.Buf - b.toPool = nil - b.Buf = nil - return ret - } - - var ret []byte - size := b.Size() - - // If we got a buffer as argument and it is big enough, reuse it. - if len(reuse) == 1 && cap(reuse[0]) >= size { - ret = reuse[0][:0] - } else { - ret = make([]byte, 0, size) - } - for _, buf := range b.bufs { - ret = append(ret, buf...) - putBuf(buf) - } - - ret = append(ret, b.Buf...) - putBuf(b.toPool) - - b.bufs = nil - b.toPool = nil - b.Buf = nil - - return ret -} - -type readCloser struct { - offset int - bufs [][]byte -} - -func (r *readCloser) Read(p []byte) (n int, err error) { - for _, buf := range r.bufs { - // Copy as much as we can. - x := copy(p[n:], buf[r.offset:]) - n += x // Increment how much we filled. - - // Did we empty the whole buffer? - if r.offset+x == len(buf) { - // On to the next buffer. - r.offset = 0 - r.bufs = r.bufs[1:] - - // We can release this buffer. - putBuf(buf) - } else { - r.offset += x - } - - if n == len(p) { - break - } - } - // No buffers left or nothing read? - if len(r.bufs) == 0 { - err = io.EOF - } - return -} - -func (r *readCloser) Close() error { - // Release all remaining buffers. - for _, buf := range r.bufs { - putBuf(buf) - } - // In case Close gets called multiple times. - r.bufs = nil - - return nil -} - -// ReadCloser creates an io.ReadCloser with all the contents of the buffer. -func (b *Buffer) ReadCloser() io.ReadCloser { - ret := &readCloser{0, append(b.bufs, b.Buf)} - - b.bufs = nil - b.toPool = nil - b.Buf = nil - - return ret -} diff --git a/api/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go b/api/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go deleted file mode 100644 index e68108f86876..000000000000 --- a/api/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go +++ /dev/null @@ -1,21 +0,0 @@ -// This file will only be included to the build if neither -// easyjson_nounsafe nor appengine build tag is set. See README notes -// for more details. - -//+build !easyjson_nounsafe -//+build !appengine - -package jlexer - -import ( - "unsafe" -) - -// bytesToStr creates a string pointing at the slice to avoid copying. -// -// Warning: the string returned by the function should be used with care, as the whole input data -// chunk may be either blocked from being freed by GC because of a single string or the buffer.Data -// may be garbage-collected even when the string exists. -func bytesToStr(data []byte) string { - return *(*string)(unsafe.Pointer(&data)) -} diff --git a/api/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go b/api/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go deleted file mode 100644 index 864d1be67638..000000000000 --- a/api/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go +++ /dev/null @@ -1,13 +0,0 @@ -// This file is included to the build if any of the buildtags below -// are defined. Refer to README notes for more details. - -//+build easyjson_nounsafe appengine - -package jlexer - -// bytesToStr creates a string normally from []byte -// -// Note that this method is roughly 1.5x slower than using the 'unsafe' method. -func bytesToStr(data []byte) string { - return string(data) -} diff --git a/api/vendor/github.com/mailru/easyjson/jlexer/error.go b/api/vendor/github.com/mailru/easyjson/jlexer/error.go deleted file mode 100644 index e90ec40d05f5..000000000000 --- a/api/vendor/github.com/mailru/easyjson/jlexer/error.go +++ /dev/null @@ -1,15 +0,0 @@ -package jlexer - -import "fmt" - -// LexerError implements the error interface and represents all possible errors that can be -// generated during parsing the JSON data. -type LexerError struct { - Reason string - Offset int - Data string -} - -func (l *LexerError) Error() string { - return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data) -} diff --git a/api/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/api/vendor/github.com/mailru/easyjson/jlexer/lexer.go deleted file mode 100644 index a27705b12b54..000000000000 --- a/api/vendor/github.com/mailru/easyjson/jlexer/lexer.go +++ /dev/null @@ -1,1257 +0,0 @@ -// Package jlexer contains a JSON lexer implementation. -// -// It is expected that it is mostly used with generated parser code, so the interface is tuned -// for a parser that knows what kind of data is expected. -package jlexer - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "strconv" - "unicode" - "unicode/utf16" - "unicode/utf8" - - "github.com/josharian/intern" -) - -// TokenKind determines type of a token. -type TokenKind byte - -const ( - TokenUndef TokenKind = iota // No token. - TokenDelim // Delimiter: one of '{', '}', '[' or ']'. - TokenString // A string literal, e.g. "abc\u1234" - TokenNumber // Number literal, e.g. 1.5e5 - TokenBool // Boolean literal: true or false. - TokenNull // null keyword. -) - -// token describes a single token: type, position in the input and value. -type token struct { - kind TokenKind // Type of a token. - - boolValue bool // Value if a boolean literal token. - byteValueCloned bool // true if byteValue was allocated and does not refer to original json body - byteValue []byte // Raw value of a token. - delimValue byte -} - -// Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice. -type Lexer struct { - Data []byte // Input data given to the lexer. - - start int // Start of the current token. - pos int // Current unscanned position in the input stream. - token token // Last scanned token, if token.kind != TokenUndef. - - firstElement bool // Whether current element is the first in array or an object. - wantSep byte // A comma or a colon character, which need to occur before a token. - - UseMultipleErrors bool // If we want to use multiple errors. - fatalError error // Fatal error occurred during lexing. It is usually a syntax error. - multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors. -} - -// FetchToken scans the input for the next token. -func (r *Lexer) FetchToken() { - r.token.kind = TokenUndef - r.start = r.pos - - // Check if r.Data has r.pos element - // If it doesn't, it mean corrupted input data - if len(r.Data) < r.pos { - r.errParse("Unexpected end of data") - return - } - // Determine the type of a token by skipping whitespace and reading the - // first character. - for _, c := range r.Data[r.pos:] { - switch c { - case ':', ',': - if r.wantSep == c { - r.pos++ - r.start++ - r.wantSep = 0 - } else { - r.errSyntax() - } - - case ' ', '\t', '\r', '\n': - r.pos++ - r.start++ - - case '"': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = TokenString - r.fetchString() - return - - case '{', '[': - if r.wantSep != 0 { - r.errSyntax() - } - r.firstElement = true - r.token.kind = TokenDelim - r.token.delimValue = r.Data[r.pos] - r.pos++ - return - - case '}', ']': - if !r.firstElement && (r.wantSep != ',') { - r.errSyntax() - } - r.wantSep = 0 - r.token.kind = TokenDelim - r.token.delimValue = r.Data[r.pos] - r.pos++ - return - - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': - if r.wantSep != 0 { - r.errSyntax() - } - r.token.kind = TokenNumber - r.fetchNumber() - return - - case 'n': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = TokenNull - r.fetchNull() - return - - case 't': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = TokenBool - r.token.boolValue = true - r.fetchTrue() - return - - case 'f': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = TokenBool - r.token.boolValue = false - r.fetchFalse() - return - - default: - r.errSyntax() - return - } - } - r.fatalError = io.EOF - return -} - -// isTokenEnd returns true if the char can follow a non-delimiter token -func isTokenEnd(c byte) bool { - return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' -} - -// fetchNull fetches and checks remaining bytes of null keyword. -func (r *Lexer) fetchNull() { - r.pos += 4 - if r.pos > len(r.Data) || - r.Data[r.pos-3] != 'u' || - r.Data[r.pos-2] != 'l' || - r.Data[r.pos-1] != 'l' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 4 - r.errSyntax() - } -} - -// fetchTrue fetches and checks remaining bytes of true keyword. -func (r *Lexer) fetchTrue() { - r.pos += 4 - if r.pos > len(r.Data) || - r.Data[r.pos-3] != 'r' || - r.Data[r.pos-2] != 'u' || - r.Data[r.pos-1] != 'e' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 4 - r.errSyntax() - } -} - -// fetchFalse fetches and checks remaining bytes of false keyword. -func (r *Lexer) fetchFalse() { - r.pos += 5 - if r.pos > len(r.Data) || - r.Data[r.pos-4] != 'a' || - r.Data[r.pos-3] != 'l' || - r.Data[r.pos-2] != 's' || - r.Data[r.pos-1] != 'e' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 5 - r.errSyntax() - } -} - -// fetchNumber scans a number literal token. -func (r *Lexer) fetchNumber() { - hasE := false - afterE := false - hasDot := false - - r.pos++ - for i, c := range r.Data[r.pos:] { - switch { - case c >= '0' && c <= '9': - afterE = false - case c == '.' && !hasDot: - hasDot = true - case (c == 'e' || c == 'E') && !hasE: - hasE = true - hasDot = true - afterE = true - case (c == '+' || c == '-') && afterE: - afterE = false - default: - r.pos += i - if !isTokenEnd(c) { - r.errSyntax() - } else { - r.token.byteValue = r.Data[r.start:r.pos] - } - return - } - } - - r.pos = len(r.Data) - r.token.byteValue = r.Data[r.start:] -} - -// findStringLen tries to scan into the string literal for ending quote char to determine required size. -// The size will be exact if no escapes are present and may be inexact if there are escaped chars. -func findStringLen(data []byte) (isValid bool, length int) { - for { - idx := bytes.IndexByte(data, '"') - if idx == -1 { - return false, len(data) - } - if idx == 0 || (idx > 0 && data[idx-1] != '\\') { - return true, length + idx - } - - // count \\\\\\\ sequences. even number of slashes means quote is not really escaped - cnt := 1 - for idx-cnt-1 >= 0 && data[idx-cnt-1] == '\\' { - cnt++ - } - if cnt%2 == 0 { - return true, length + idx - } - - length += idx + 1 - data = data[idx+1:] - } -} - -// unescapeStringToken performs unescaping of string token. -// if no escaping is needed, original string is returned, otherwise - a new one allocated -func (r *Lexer) unescapeStringToken() (err error) { - data := r.token.byteValue - var unescapedData []byte - - for { - i := bytes.IndexByte(data, '\\') - if i == -1 { - break - } - - escapedRune, escapedBytes, err := decodeEscape(data[i:]) - if err != nil { - r.errParse(err.Error()) - return err - } - - if unescapedData == nil { - unescapedData = make([]byte, 0, len(r.token.byteValue)) - } - - var d [4]byte - s := utf8.EncodeRune(d[:], escapedRune) - unescapedData = append(unescapedData, data[:i]...) - unescapedData = append(unescapedData, d[:s]...) - - data = data[i+escapedBytes:] - } - - if unescapedData != nil { - r.token.byteValue = append(unescapedData, data...) - r.token.byteValueCloned = true - } - return -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - var val rune - for i := 2; i < len(s) && i < 6; i++ { - var v byte - c := s[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - v = c - '0' - case 'a', 'b', 'c', 'd', 'e', 'f': - v = c - 'a' + 10 - case 'A', 'B', 'C', 'D', 'E', 'F': - v = c - 'A' + 10 - default: - return -1 - } - - val <<= 4 - val |= rune(v) - } - return val -} - -// decodeEscape processes a single escape sequence and returns number of bytes processed. -func decodeEscape(data []byte) (decoded rune, bytesProcessed int, err error) { - if len(data) < 2 { - return 0, 0, errors.New("incorrect escape symbol \\ at the end of token") - } - - c := data[1] - switch c { - case '"', '/', '\\': - return rune(c), 2, nil - case 'b': - return '\b', 2, nil - case 'f': - return '\f', 2, nil - case 'n': - return '\n', 2, nil - case 'r': - return '\r', 2, nil - case 't': - return '\t', 2, nil - case 'u': - rr := getu4(data) - if rr < 0 { - return 0, 0, errors.New("incorrectly escaped \\uXXXX sequence") - } - - read := 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(data[read:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - read += 6 - rr = dec - } else { - rr = unicode.ReplacementChar - } - } - return rr, read, nil - } - - return 0, 0, errors.New("incorrectly escaped bytes") -} - -// fetchString scans a string literal token. -func (r *Lexer) fetchString() { - r.pos++ - data := r.Data[r.pos:] - - isValid, length := findStringLen(data) - if !isValid { - r.pos += length - r.errParse("unterminated string literal") - return - } - r.token.byteValue = data[:length] - r.pos += length + 1 // skip closing '"' as well -} - -// scanToken scans the next token if no token is currently available in the lexer. -func (r *Lexer) scanToken() { - if r.token.kind != TokenUndef || r.fatalError != nil { - return - } - - r.FetchToken() -} - -// consume resets the current token to allow scanning the next one. -func (r *Lexer) consume() { - r.token.kind = TokenUndef - r.token.byteValueCloned = false - r.token.delimValue = 0 -} - -// Ok returns true if no error (including io.EOF) was encountered during scanning. -func (r *Lexer) Ok() bool { - return r.fatalError == nil -} - -const maxErrorContextLen = 13 - -func (r *Lexer) errParse(what string) { - if r.fatalError == nil { - var str string - if len(r.Data)-r.pos <= maxErrorContextLen { - str = string(r.Data) - } else { - str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..." - } - r.fatalError = &LexerError{ - Reason: what, - Offset: r.pos, - Data: str, - } - } -} - -func (r *Lexer) errSyntax() { - r.errParse("syntax error") -} - -func (r *Lexer) errInvalidToken(expected string) { - if r.fatalError != nil { - return - } - if r.UseMultipleErrors { - r.pos = r.start - r.consume() - r.SkipRecursive() - switch expected { - case "[": - r.token.delimValue = ']' - r.token.kind = TokenDelim - case "{": - r.token.delimValue = '}' - r.token.kind = TokenDelim - } - r.addNonfatalError(&LexerError{ - Reason: fmt.Sprintf("expected %s", expected), - Offset: r.start, - Data: string(r.Data[r.start:r.pos]), - }) - return - } - - var str string - if len(r.token.byteValue) <= maxErrorContextLen { - str = string(r.token.byteValue) - } else { - str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..." - } - r.fatalError = &LexerError{ - Reason: fmt.Sprintf("expected %s", expected), - Offset: r.pos, - Data: str, - } -} - -func (r *Lexer) GetPos() int { - return r.pos -} - -// Delim consumes a token and verifies that it is the given delimiter. -func (r *Lexer) Delim(c byte) { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() || r.token.delimValue != c { - r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled. - r.errInvalidToken(string([]byte{c})) - } else { - r.consume() - } -} - -// IsDelim returns true if there was no scanning error and next token is the given delimiter. -func (r *Lexer) IsDelim(c byte) bool { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - return !r.Ok() || r.token.delimValue == c -} - -// Null verifies that the next token is null and consumes it. -func (r *Lexer) Null() { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenNull { - r.errInvalidToken("null") - } - r.consume() -} - -// IsNull returns true if the next token is a null keyword. -func (r *Lexer) IsNull() bool { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - return r.Ok() && r.token.kind == TokenNull -} - -// Skip skips a single token. -func (r *Lexer) Skip() { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - r.consume() -} - -// SkipRecursive skips next array or object completely, or just skips a single token if not -// an array/object. -// -// Note: no syntax validation is performed on the skipped data. -func (r *Lexer) SkipRecursive() { - r.scanToken() - var start, end byte - startPos := r.start - - switch r.token.delimValue { - case '{': - start, end = '{', '}' - case '[': - start, end = '[', ']' - default: - r.consume() - return - } - - r.consume() - - level := 1 - inQuotes := false - wasEscape := false - - for i, c := range r.Data[r.pos:] { - switch { - case c == start && !inQuotes: - level++ - case c == end && !inQuotes: - level-- - if level == 0 { - r.pos += i + 1 - if !json.Valid(r.Data[startPos:r.pos]) { - r.pos = len(r.Data) - r.fatalError = &LexerError{ - Reason: "skipped array/object json value is invalid", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - } - } - return - } - case c == '\\' && inQuotes: - wasEscape = !wasEscape - continue - case c == '"' && inQuotes: - inQuotes = wasEscape - case c == '"': - inQuotes = true - } - wasEscape = false - } - r.pos = len(r.Data) - r.fatalError = &LexerError{ - Reason: "EOF reached while skipping array/object or token", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - } -} - -// Raw fetches the next item recursively as a data slice -func (r *Lexer) Raw() []byte { - r.SkipRecursive() - if !r.Ok() { - return nil - } - return r.Data[r.start:r.pos] -} - -// IsStart returns whether the lexer is positioned at the start -// of an input string. -func (r *Lexer) IsStart() bool { - return r.pos == 0 -} - -// Consumed reads all remaining bytes from the input, publishing an error if -// there is anything but whitespace remaining. -func (r *Lexer) Consumed() { - if r.pos > len(r.Data) || !r.Ok() { - return - } - - for _, c := range r.Data[r.pos:] { - if c != ' ' && c != '\t' && c != '\r' && c != '\n' { - r.AddError(&LexerError{ - Reason: "invalid character '" + string(c) + "' after top-level value", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - }) - return - } - - r.pos++ - r.start++ - } -} - -func (r *Lexer) unsafeString(skipUnescape bool) (string, []byte) { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenString { - r.errInvalidToken("string") - return "", nil - } - if !skipUnescape { - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "", nil - } - } - - bytes := r.token.byteValue - ret := bytesToStr(r.token.byteValue) - r.consume() - return ret, bytes -} - -// UnsafeString returns the string value if the token is a string literal. -// -// Warning: returned string may point to the input buffer, so the string should not outlive -// the input buffer. Intended pattern of usage is as an argument to a switch statement. -func (r *Lexer) UnsafeString() string { - ret, _ := r.unsafeString(false) - return ret -} - -// UnsafeBytes returns the byte slice if the token is a string literal. -func (r *Lexer) UnsafeBytes() []byte { - _, ret := r.unsafeString(false) - return ret -} - -// UnsafeFieldName returns current member name string token -func (r *Lexer) UnsafeFieldName(skipUnescape bool) string { - ret, _ := r.unsafeString(skipUnescape) - return ret -} - -// String reads a string literal. -func (r *Lexer) String() string { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenString { - r.errInvalidToken("string") - return "" - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "" - } - var ret string - if r.token.byteValueCloned { - ret = bytesToStr(r.token.byteValue) - } else { - ret = string(r.token.byteValue) - } - r.consume() - return ret -} - -// StringIntern reads a string literal, and performs string interning on it. -func (r *Lexer) StringIntern() string { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenString { - r.errInvalidToken("string") - return "" - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "" - } - ret := intern.Bytes(r.token.byteValue) - r.consume() - return ret -} - -// Bytes reads a string literal and base64 decodes it into a byte slice. -func (r *Lexer) Bytes() []byte { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenString { - r.errInvalidToken("string") - return nil - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return nil - } - ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue))) - n, err := base64.StdEncoding.Decode(ret, r.token.byteValue) - if err != nil { - r.fatalError = &LexerError{ - Reason: err.Error(), - } - return nil - } - - r.consume() - return ret[:n] -} - -// Bool reads a true or false boolean keyword. -func (r *Lexer) Bool() bool { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenBool { - r.errInvalidToken("bool") - return false - } - ret := r.token.boolValue - r.consume() - return ret -} - -func (r *Lexer) number() string { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenNumber { - r.errInvalidToken("number") - return "" - } - ret := bytesToStr(r.token.byteValue) - r.consume() - return ret -} - -func (r *Lexer) Uint8() uint8 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint8(n) -} - -func (r *Lexer) Uint16() uint16 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint16(n) -} - -func (r *Lexer) Uint32() uint32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint32(n) -} - -func (r *Lexer) Uint64() uint64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Uint() uint { - return uint(r.Uint64()) -} - -func (r *Lexer) Int8() int8 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int8(n) -} - -func (r *Lexer) Int16() int16 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int16(n) -} - -func (r *Lexer) Int32() int32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int32(n) -} - -func (r *Lexer) Int64() int64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Int() int { - return int(r.Int64()) -} - -func (r *Lexer) Uint8Str() uint8 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint8(n) -} - -func (r *Lexer) Uint16Str() uint16 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint16(n) -} - -func (r *Lexer) Uint32Str() uint32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint32(n) -} - -func (r *Lexer) Uint64Str() uint64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) UintStr() uint { - return uint(r.Uint64Str()) -} - -func (r *Lexer) UintptrStr() uintptr { - return uintptr(r.Uint64Str()) -} - -func (r *Lexer) Int8Str() int8 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int8(n) -} - -func (r *Lexer) Int16Str() int16 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int16(n) -} - -func (r *Lexer) Int32Str() int32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int32(n) -} - -func (r *Lexer) Int64Str() int64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) IntStr() int { - return int(r.Int64Str()) -} - -func (r *Lexer) Float32() float32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseFloat(s, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return float32(n) -} - -func (r *Lexer) Float32Str() float32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - n, err := strconv.ParseFloat(s, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return float32(n) -} - -func (r *Lexer) Float64() float64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseFloat(s, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Float64Str() float64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - n, err := strconv.ParseFloat(s, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) Error() error { - return r.fatalError -} - -func (r *Lexer) AddError(e error) { - if r.fatalError == nil { - r.fatalError = e - } -} - -func (r *Lexer) AddNonFatalError(e error) { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Data: string(r.Data[r.start:r.pos]), - Reason: e.Error(), - }) -} - -func (r *Lexer) addNonfatalError(err *LexerError) { - if r.UseMultipleErrors { - // We don't want to add errors with the same offset. - if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset { - return - } - r.multipleErrors = append(r.multipleErrors, err) - return - } - r.fatalError = err -} - -func (r *Lexer) GetNonFatalErrors() []*LexerError { - return r.multipleErrors -} - -// JsonNumber fetches and json.Number from 'encoding/json' package. -// Both int, float or string, contains them are valid values -func (r *Lexer) JsonNumber() json.Number { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() { - r.errInvalidToken("json.Number") - return json.Number("") - } - - switch r.token.kind { - case TokenString: - return json.Number(r.String()) - case TokenNumber: - return json.Number(r.Raw()) - case TokenNull: - r.Null() - return json.Number("") - default: - r.errSyntax() - return json.Number("") - } -} - -// Interface fetches an interface{} analogous to the 'encoding/json' package. -func (r *Lexer) Interface() interface{} { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() { - return nil - } - switch r.token.kind { - case TokenString: - return r.String() - case TokenNumber: - return r.Float64() - case TokenBool: - return r.Bool() - case TokenNull: - r.Null() - return nil - } - - if r.token.delimValue == '{' { - r.consume() - - ret := map[string]interface{}{} - for !r.IsDelim('}') { - key := r.String() - r.WantColon() - ret[key] = r.Interface() - r.WantComma() - } - r.Delim('}') - - if r.Ok() { - return ret - } else { - return nil - } - } else if r.token.delimValue == '[' { - r.consume() - - ret := []interface{}{} - for !r.IsDelim(']') { - ret = append(ret, r.Interface()) - r.WantComma() - } - r.Delim(']') - - if r.Ok() { - return ret - } else { - return nil - } - } - r.errSyntax() - return nil -} - -// WantComma requires a comma to be present before fetching next token. -func (r *Lexer) WantComma() { - r.wantSep = ',' - r.firstElement = false -} - -// WantColon requires a colon to be present before fetching next token. -func (r *Lexer) WantColon() { - r.wantSep = ':' - r.firstElement = false -} - -// CurrentToken returns current token kind if there were no errors and TokenUndef otherwise -func (r *Lexer) CurrentToken() TokenKind { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() { - return TokenUndef - } - - return r.token.kind -} diff --git a/api/vendor/github.com/mailru/easyjson/jwriter/writer.go b/api/vendor/github.com/mailru/easyjson/jwriter/writer.go deleted file mode 100644 index 34b0ade46852..000000000000 --- a/api/vendor/github.com/mailru/easyjson/jwriter/writer.go +++ /dev/null @@ -1,417 +0,0 @@ -// Package jwriter contains a JSON writer. -package jwriter - -import ( - "io" - "strconv" - "unicode/utf8" - - "github.com/mailru/easyjson/buffer" -) - -// Flags describe various encoding options. The behavior may be actually implemented in the encoder, but -// Flags field in Writer is used to set and pass them around. -type Flags int - -const ( - NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. - NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. -) - -// Writer is a JSON writer. -type Writer struct { - Flags Flags - - Error error - Buffer buffer.Buffer - NoEscapeHTML bool -} - -// Size returns the size of the data that was written out. -func (w *Writer) Size() int { - return w.Buffer.Size() -} - -// DumpTo outputs the data to given io.Writer, resetting the buffer. -func (w *Writer) DumpTo(out io.Writer) (written int, err error) { - return w.Buffer.DumpTo(out) -} - -// BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice -// as argument that it will try to reuse. -func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { - if w.Error != nil { - return nil, w.Error - } - - return w.Buffer.BuildBytes(reuse...), nil -} - -// ReadCloser returns an io.ReadCloser that can be used to read the data. -// ReadCloser also resets the buffer. -func (w *Writer) ReadCloser() (io.ReadCloser, error) { - if w.Error != nil { - return nil, w.Error - } - - return w.Buffer.ReadCloser(), nil -} - -// RawByte appends raw binary data to the buffer. -func (w *Writer) RawByte(c byte) { - w.Buffer.AppendByte(c) -} - -// RawByte appends raw binary data to the buffer. -func (w *Writer) RawString(s string) { - w.Buffer.AppendString(s) -} - -// RawBytesString appends string from bytes to the buffer. -func (w *Writer) RawBytesString(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - default: - w.String(string(data)) - } -} - -// Raw appends raw binary data to the buffer or sets the error if it is given. Useful for -// calling with results of MarshalJSON-like functions. -func (w *Writer) Raw(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - case len(data) > 0: - w.Buffer.AppendBytes(data) - default: - w.RawString("null") - } -} - -// RawText encloses raw binary data in quotes and appends in to the buffer. -// Useful for calling with results of MarshalText-like functions. -func (w *Writer) RawText(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - case len(data) > 0: - w.String(string(data)) - default: - w.RawString("null") - } -} - -// Base64Bytes appends data to the buffer after base64 encoding it -func (w *Writer) Base64Bytes(data []byte) { - if data == nil { - w.Buffer.AppendString("null") - return - } - w.Buffer.AppendByte('"') - w.base64(data) - w.Buffer.AppendByte('"') -} - -func (w *Writer) Uint8(n uint8) { - w.Buffer.EnsureSpace(3) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint16(n uint16) { - w.Buffer.EnsureSpace(5) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint32(n uint32) { - w.Buffer.EnsureSpace(10) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint(n uint) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint64(n uint64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) -} - -func (w *Writer) Int8(n int8) { - w.Buffer.EnsureSpace(4) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int16(n int16) { - w.Buffer.EnsureSpace(6) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int32(n int32) { - w.Buffer.EnsureSpace(11) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int(n int) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int64(n int64) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) -} - -func (w *Writer) Uint8Str(n uint8) { - w.Buffer.EnsureSpace(3) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint16Str(n uint16) { - w.Buffer.EnsureSpace(5) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint32Str(n uint32) { - w.Buffer.EnsureSpace(10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) UintStr(n uint) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint64Str(n uint64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) UintptrStr(n uintptr) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int8Str(n int8) { - w.Buffer.EnsureSpace(4) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int16Str(n int16) { - w.Buffer.EnsureSpace(6) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int32Str(n int32) { - w.Buffer.EnsureSpace(11) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) IntStr(n int) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int64Str(n int64) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Float32(n float32) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) -} - -func (w *Writer) Float32Str(n float32) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Float64(n float64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) -} - -func (w *Writer) Float64Str(n float64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 64) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Bool(v bool) { - w.Buffer.EnsureSpace(5) - if v { - w.Buffer.Buf = append(w.Buffer.Buf, "true"...) - } else { - w.Buffer.Buf = append(w.Buffer.Buf, "false"...) - } -} - -const chars = "0123456789abcdef" - -func getTable(falseValues ...int) [128]bool { - table := [128]bool{} - - for i := 0; i < 128; i++ { - table[i] = true - } - - for _, v := range falseValues { - table[v] = false - } - - return table -} - -var ( - htmlEscapeTable = getTable(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, '"', '&', '<', '>', '\\') - htmlNoEscapeTable = getTable(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, '"', '\\') -) - -func (w *Writer) String(s string) { - w.Buffer.AppendByte('"') - - // Portions of the string that contain no escapes are appended as - // byte slices. - - p := 0 // last non-escape symbol - - escapeTable := &htmlEscapeTable - if w.NoEscapeHTML { - escapeTable = &htmlNoEscapeTable - } - - for i := 0; i < len(s); { - c := s[i] - - if c < utf8.RuneSelf { - if escapeTable[c] { - // single-width character, no escaping is required - i++ - continue - } - - w.Buffer.AppendString(s[p:i]) - switch c { - case '\t': - w.Buffer.AppendString(`\t`) - case '\r': - w.Buffer.AppendString(`\r`) - case '\n': - w.Buffer.AppendString(`\n`) - case '\\': - w.Buffer.AppendString(`\\`) - case '"': - w.Buffer.AppendString(`\"`) - default: - w.Buffer.AppendString(`\u00`) - w.Buffer.AppendByte(chars[c>>4]) - w.Buffer.AppendByte(chars[c&0xf]) - } - - i++ - p = i - continue - } - - // broken utf - runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) - if runeValue == utf8.RuneError && runeWidth == 1 { - w.Buffer.AppendString(s[p:i]) - w.Buffer.AppendString(`\ufffd`) - i++ - p = i - continue - } - - // jsonp stuff - tab separator and line separator - if runeValue == '\u2028' || runeValue == '\u2029' { - w.Buffer.AppendString(s[p:i]) - w.Buffer.AppendString(`\u202`) - w.Buffer.AppendByte(chars[runeValue&0xf]) - i += runeWidth - p = i - continue - } - i += runeWidth - } - w.Buffer.AppendString(s[p:]) - w.Buffer.AppendByte('"') -} - -const encode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -const padChar = '=' - -func (w *Writer) base64(in []byte) { - - if len(in) == 0 { - return - } - - w.Buffer.EnsureSpace(((len(in)-1)/3 + 1) * 4) - - si := 0 - n := (len(in) / 3) * 3 - - for si < n { - // Convert 3x 8bit source bytes into 4 bytes - val := uint(in[si+0])<<16 | uint(in[si+1])<<8 | uint(in[si+2]) - - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F], encode[val>>6&0x3F], encode[val&0x3F]) - - si += 3 - } - - remain := len(in) - si - if remain == 0 { - return - } - - // Add the remaining small block - val := uint(in[si+0]) << 16 - if remain == 2 { - val |= uint(in[si+1]) << 8 - } - - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F]) - - switch remain { - case 2: - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>6&0x3F], byte(padChar)) - case 1: - w.Buffer.Buf = append(w.Buffer.Buf, byte(padChar), byte(padChar)) - } -} diff --git a/api/vendor/github.com/pkg/errors/.gitignore b/api/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b1b347..000000000000 --- a/api/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# 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 diff --git a/api/vendor/github.com/pkg/errors/.travis.yml b/api/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 9159de03e03d..000000000000 --- a/api/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.11.x - - 1.12.x - - 1.13.x - - tip - -script: - - make check diff --git a/api/vendor/github.com/pkg/errors/LICENSE b/api/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e755ce..000000000000 --- a/api/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, 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/api/vendor/github.com/pkg/errors/Makefile b/api/vendor/github.com/pkg/errors/Makefile deleted file mode 100644 index ce9d7cded649..000000000000 --- a/api/vendor/github.com/pkg/errors/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -PKGS := github.com/pkg/errors -SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS)) -GO := go - -check: test vet gofmt misspell unconvert staticcheck ineffassign unparam - -test: - $(GO) test $(PKGS) - -vet: | test - $(GO) vet $(PKGS) - -staticcheck: - $(GO) get honnef.co/go/tools/cmd/staticcheck - staticcheck -checks all $(PKGS) - -misspell: - $(GO) get github.com/client9/misspell/cmd/misspell - misspell \ - -locale GB \ - -error \ - *.md *.go - -unconvert: - $(GO) get github.com/mdempsky/unconvert - unconvert -v $(PKGS) - -ineffassign: - $(GO) get github.com/gordonklaus/ineffassign - find $(SRCDIRS) -name '*.go' | xargs ineffassign - -pedantic: check errcheck - -unparam: - $(GO) get mvdan.cc/unparam - unparam ./... - -errcheck: - $(GO) get github.com/kisielk/errcheck - errcheck $(PKGS) - -gofmt: - @echo Checking code is gofmted - @test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)" diff --git a/api/vendor/github.com/pkg/errors/README.md b/api/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 54dfdcb12ea1..000000000000 --- a/api/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Roadmap - -With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: - -- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) -- 1.0. Final release. - -## Contributing - -Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports. - -Before sending a PR, please discuss your change by raising an issue. - -## License - -BSD-2-Clause diff --git a/api/vendor/github.com/pkg/errors/appveyor.yml b/api/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade0240..000000000000 --- a/api/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/api/vendor/github.com/pkg/errors/errors.go b/api/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 161aea258296..000000000000 --- a/api/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,288 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which when applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// together with the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required, the errors.WithStack and -// errors.WithMessage functions destructure errors.Wrap into its component -// operations: annotating an error with a stack trace and with a message, -// respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error that does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// Although the causer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported: -// -// %s print the error. If the error has a Cause it will be -// printed recursively. -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface: -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// The returned errors.StackTrace type is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d\n", f, f) -// } -// } -// -// Although the stackTracer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withStack) Unwrap() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is called, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -// WithMessagef annotates err with the format specifier. -// If err is nil, WithMessagef returns nil. -func WithMessagef(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withMessage) Unwrap() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/api/vendor/github.com/pkg/errors/go113.go b/api/vendor/github.com/pkg/errors/go113.go deleted file mode 100644 index be0d10d0c793..000000000000 --- a/api/vendor/github.com/pkg/errors/go113.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build go1.13 - -package errors - -import ( - stderrors "errors" -) - -// Is reports whether any error in err's chain matches target. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error is considered to match a target if it is equal to that target or if -// it implements a method Is(error) bool such that Is(target) returns true. -func Is(err, target error) bool { return stderrors.Is(err, target) } - -// As finds the first error in err's chain that matches target, and if so, sets -// target to that error value and returns true. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error matches target if the error's concrete value is assignable to the value -// pointed to by target, or if the error has a method As(interface{}) bool such that -// As(target) returns true. In the latter case, the As method is responsible for -// setting target. -// -// As will panic if target is not a non-nil pointer to either a type that implements -// error, or to any interface type. As returns false if err is nil. -func As(err error, target interface{}) bool { return stderrors.As(err, target) } - -// Unwrap returns the result of calling the Unwrap method on err, if err's -// type contains an Unwrap method returning error. -// Otherwise, Unwrap returns nil. -func Unwrap(err error) error { - return stderrors.Unwrap(err) -} diff --git a/api/vendor/github.com/pkg/errors/stack.go b/api/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 779a8348fb9c..000000000000 --- a/api/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,177 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strconv" - "strings" -) - -// Frame represents a program counter inside a stack frame. -// For historical reasons if Frame is interpreted as a uintptr -// its value represents the program counter + 1. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// name returns the name of this function, if known. -func (f Frame) name() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - return fn.Name() -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s function name and path of source file relative to the compile time -// GOPATH separated by \n\t (\n\t) -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - io.WriteString(s, f.name()) - io.WriteString(s, "\n\t") - io.WriteString(s, f.file()) - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - io.WriteString(s, strconv.Itoa(f.line())) - case 'n': - io.WriteString(s, funcname(f.name())) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// MarshalText formats a stacktrace Frame as a text string. The output is the -// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. -func (f Frame) MarshalText() ([]byte, error) { - name := f.name() - if name == "unknown" { - return []byte(name), nil - } - return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -// Format formats the stack of Frames according to the fmt.Formatter interface. -// -// %s lists source files for each Frame in the stack -// %v lists the source file and line number for each Frame in the stack -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+v Prints filename, function, and line number for each Frame in the stack. -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - io.WriteString(s, "\n") - f.Format(s, verb) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - st.formatSlice(s, verb) - } - case 's': - st.formatSlice(s, verb) - } -} - -// formatSlice will format this StackTrace into the given buffer as a slice of -// Frame, only valid when called with '%s' or '%v'. -func (st StackTrace) formatSlice(s fmt.State, verb rune) { - io.WriteString(s, "[") - for i, f := range st { - if i > 0 { - io.WriteString(s, " ") - } - f.Format(s, verb) - } - io.WriteString(s, "]") -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} diff --git a/api/vendor/github.com/prometheus/procfs/.golangci.yml b/api/vendor/github.com/prometheus/procfs/.golangci.yml index 3c3bf910fdfb..23ecd4505b2a 100644 --- a/api/vendor/github.com/prometheus/procfs/.golangci.yml +++ b/api/vendor/github.com/prometheus/procfs/.golangci.yml @@ -1,7 +1,9 @@ version: "2" linters: enable: + - errorlint - forbidigo + - gocritic - godot - misspell - revive @@ -11,6 +13,20 @@ linters: forbid: - pattern: ^fmt\.Print.*$ msg: Do not commit print statements. + gocritic: + enable-all: true + disabled-checks: + - commentFormatting + - commentedOutCode + - deferInLoop + - filepathJoin + - hugeParam + - importShadow + - paramTypeCombine + - rangeValCopy + - tooManyResultsChecker + - unnamedResult + - whyNoLint godot: exclude: # Ignore "See: URL". @@ -19,16 +35,12 @@ linters: misspell: locale: US exclusions: - generated: lax presets: - comments - common-false-positives - legacy - std-error-handling - paths: - - third_party$ - - builtin$ - - examples$ + warn-unused: true formatters: enable: - gofmt @@ -37,9 +49,3 @@ formatters: goimports: local-prefixes: - github.com/prometheus/procfs - exclusions: - generated: lax - paths: - - third_party$ - - builtin$ - - examples$ diff --git a/api/vendor/github.com/prometheus/procfs/Makefile b/api/vendor/github.com/prometheus/procfs/Makefile index 7edfe4d09325..bce50a19c504 100644 --- a/api/vendor/github.com/prometheus/procfs/Makefile +++ b/api/vendor/github.com/prometheus/procfs/Makefile @@ -1,4 +1,4 @@ -# Copyright 2018 The Prometheus Authors +# Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/Makefile.common b/api/vendor/github.com/prometheus/procfs/Makefile.common index 0ed55c2ba21f..6f61bec48fdb 100644 --- a/api/vendor/github.com/prometheus/procfs/Makefile.common +++ b/api/vendor/github.com/prometheus/procfs/Makefile.common @@ -33,7 +33,7 @@ GOHOSTOS ?= $(shell $(GO) env GOHOSTOS) GOHOSTARCH ?= $(shell $(GO) env GOHOSTARCH) GO_VERSION ?= $(shell $(GO) version) -GO_VERSION_NUMBER ?= $(word 3, $(GO_VERSION))Error Parsing File +GO_VERSION_NUMBER ?= $(word 3, $(GO_VERSION)) PRE_GO_111 ?= $(shell echo $(GO_VERSION_NUMBER) | grep -E 'go1\.(10|[0-9])\.') PROMU := $(FIRST_GOPATH)/bin/promu @@ -61,7 +61,8 @@ PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_ SKIP_GOLANGCI_LINT := GOLANGCI_LINT := GOLANGCI_LINT_OPTS ?= -GOLANGCI_LINT_VERSION ?= v2.0.2 +GOLANGCI_LINT_VERSION ?= v2.1.5 +GOLANGCI_FMT_OPTS ?= # golangci-lint only supports linux, darwin and windows platforms on i386/amd64/arm64. # windows isn't included here because of the path separator being different. ifeq ($(GOHOSTOS),$(filter $(GOHOSTOS),linux darwin)) @@ -138,7 +139,7 @@ common-deps: update-go-deps: @echo ">> updating Go dependencies" @for m in $$($(GO) list -mod=readonly -m -f '{{ if and (not .Indirect) (not .Main)}}{{.Path}}{{end}}' all); do \ - $(GO) get -d $$m; \ + $(GO) get $$m; \ done $(GO) mod tidy @@ -156,9 +157,13 @@ $(GOTEST_DIR): @mkdir -p $@ .PHONY: common-format -common-format: +common-format: $(GOLANGCI_LINT) @echo ">> formatting code" $(GO) fmt $(pkgs) +ifdef GOLANGCI_LINT + @echo ">> formatting code with golangci-lint" + $(GOLANGCI_LINT) fmt $(GOLANGCI_FMT_OPTS) +endif .PHONY: common-vet common-vet: @@ -248,8 +253,8 @@ $(PROMU): cp $(PROMU_TMP)/promu-$(PROMU_VERSION).$(GO_BUILD_PLATFORM)/promu $(FIRST_GOPATH)/bin/promu rm -r $(PROMU_TMP) -.PHONY: proto -proto: +.PHONY: common-proto +common-proto: @echo ">> generating code from proto files" @./scripts/genproto.sh diff --git a/api/vendor/github.com/prometheus/procfs/arp.go b/api/vendor/github.com/prometheus/procfs/arp.go index 2e53344151f5..716bdef10909 100644 --- a/api/vendor/github.com/prometheus/procfs/arp.go +++ b/api/vendor/github.com/prometheus/procfs/arp.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -73,15 +73,16 @@ func parseARPEntries(data []byte) ([]ARPEntry, error) { columns := strings.Fields(line) width := len(columns) - if width == expectedHeaderWidth || width == 0 { + switch width { + case expectedHeaderWidth, 0: continue - } else if width == expectedDataWidth { + case expectedDataWidth: entry, err := parseARPEntry(columns) if err != nil { return []ARPEntry{}, fmt.Errorf("%w: Failed to parse ARP entry: %v: %w", ErrFileParse, entry, err) } entries = append(entries, entry) - } else { + default: return []ARPEntry{}, fmt.Errorf("%w: %d columns found, but expected %d: %w", ErrFileParse, width, expectedDataWidth, err) } diff --git a/api/vendor/github.com/prometheus/procfs/buddyinfo.go b/api/vendor/github.com/prometheus/procfs/buddyinfo.go index 83807500908f..53243e687583 100644 --- a/api/vendor/github.com/prometheus/procfs/buddyinfo.go +++ b/api/vendor/github.com/prometheus/procfs/buddyinfo.go @@ -1,4 +1,4 @@ -// Copyright 2017 The Prometheus Authors +// Copyright 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 @@ -64,14 +64,12 @@ func parseBuddyInfo(r io.Reader) ([]BuddyInfo, error) { if bucketCount == -1 { bucketCount = arraySize - } else { - if bucketCount != arraySize { - return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, bucketCount, arraySize) - } + } else if bucketCount != arraySize { + return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, bucketCount, arraySize) } sizes := make([]float64, arraySize) - for i := 0; i < arraySize; i++ { + for i := range arraySize { sizes[i], err = strconv.ParseFloat(parts[i+4], 64) if err != nil { return nil, fmt.Errorf("%w: Invalid valid in buddyinfo: %f: %w", ErrFileParse, sizes[i], err) diff --git a/api/vendor/github.com/prometheus/procfs/cmdline.go b/api/vendor/github.com/prometheus/procfs/cmdline.go index bf4f3b48c0e8..4f1cac1f0ac7 100644 --- a/api/vendor/github.com/prometheus/procfs/cmdline.go +++ b/api/vendor/github.com/prometheus/procfs/cmdline.go @@ -1,4 +1,4 @@ -// Copyright 2021 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo.go b/api/vendor/github.com/prometheus/procfs/cpuinfo.go index f0950bb49534..5fe6cecd3dd5 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo_armx.go b/api/vendor/github.com/prometheus/procfs/cpuinfo_armx.go index 64cfd534c1f9..8f155551e527 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo_armx.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo_armx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go b/api/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go index d88442f0edfd..e81a5db94905 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go b/api/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go index c11207f3ab61..4be2b1cc549d 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo_others.go b/api/vendor/github.com/prometheus/procfs/cpuinfo_others.go index a6b2b3127cb1..e713bae8dfe6 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo_others.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo_others.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go b/api/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go index 003bc2ad4a33..0825aa1a8308 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go b/api/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go index 1c9b7313b6cb..496770b05f6e 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go b/api/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go index fa3686bc0048..b3228ce3d861 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/cpuinfo_x86.go b/api/vendor/github.com/prometheus/procfs/cpuinfo_x86.go index a0ef55562ebb..575eb022eb0a 100644 --- a/api/vendor/github.com/prometheus/procfs/cpuinfo_x86.go +++ b/api/vendor/github.com/prometheus/procfs/cpuinfo_x86.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/crypto.go b/api/vendor/github.com/prometheus/procfs/crypto.go index 5f2a37a78b3f..e4a5876eafbc 100644 --- a/api/vendor/github.com/prometheus/procfs/crypto.go +++ b/api/vendor/github.com/prometheus/procfs/crypto.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/doc.go b/api/vendor/github.com/prometheus/procfs/doc.go index f9d961e44179..26bfea071bae 100644 --- a/api/vendor/github.com/prometheus/procfs/doc.go +++ b/api/vendor/github.com/prometheus/procfs/doc.go @@ -1,4 +1,4 @@ -// Copyright 2014 Prometheus Team +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/fs.go b/api/vendor/github.com/prometheus/procfs/fs.go index 9bdaccc7c8a4..8f27912a13a5 100644 --- a/api/vendor/github.com/prometheus/procfs/fs.go +++ b/api/vendor/github.com/prometheus/procfs/fs.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/fs_statfs_notype.go b/api/vendor/github.com/prometheus/procfs/fs_statfs_notype.go index 1b5bdbdf84ac..3c53023c5440 100644 --- a/api/vendor/github.com/prometheus/procfs/fs_statfs_notype.go +++ b/api/vendor/github.com/prometheus/procfs/fs_statfs_notype.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/fs_statfs_type.go b/api/vendor/github.com/prometheus/procfs/fs_statfs_type.go index 80df79c31930..80fce484789e 100644 --- a/api/vendor/github.com/prometheus/procfs/fs_statfs_type.go +++ b/api/vendor/github.com/prometheus/procfs/fs_statfs_type.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/fscache.go b/api/vendor/github.com/prometheus/procfs/fscache.go index 7db863307793..9dde85707376 100644 --- a/api/vendor/github.com/prometheus/procfs/fscache.go +++ b/api/vendor/github.com/prometheus/procfs/fscache.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -388,20 +388,21 @@ func parseFscacheinfo(r io.Reader) (*Fscacheinfo, error) { } } case "CacheOp:": - if strings.Split(fields[1], "=")[0] == "alo" { + switch strings.Split(fields[1], "=")[0] { + case "alo": err := setFSCacheFields(fields[1:], &m.CacheopAllocationsinProgress, &m.CacheopLookupObjectInProgress, &m.CacheopLookupCompleteInPorgress, &m.CacheopGrabObjectInProgress) if err != nil { return &m, err } - } else if strings.Split(fields[1], "=")[0] == "inv" { + case "inv": err := setFSCacheFields(fields[1:], &m.CacheopInvalidations, &m.CacheopUpdateObjectInProgress, &m.CacheopDropObjectInProgress, &m.CacheopPutObjectInProgress, &m.CacheopAttributeChangeInProgress, &m.CacheopSyncCacheInProgress) if err != nil { return &m, err } - } else { + default: err := setFSCacheFields(fields[1:], &m.CacheopReadOrAllocPageInProgress, &m.CacheopReadOrAllocPagesInProgress, &m.CacheopAllocatePageInProgress, &m.CacheopAllocatePagesInProgress, &m.CacheopWritePagesInProgress, &m.CacheopUncachePagesInProgress, &m.CacheopDissociatePagesInProgress) diff --git a/api/vendor/github.com/prometheus/procfs/internal/fs/fs.go b/api/vendor/github.com/prometheus/procfs/internal/fs/fs.go index 3a43e83915f5..e7ccad66b2ed 100644 --- a/api/vendor/github.com/prometheus/procfs/internal/fs/fs.go +++ b/api/vendor/github.com/prometheus/procfs/internal/fs/fs.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/internal/util/parse.go b/api/vendor/github.com/prometheus/procfs/internal/util/parse.go index 5a7d2df06ae3..30c5872019a9 100644 --- a/api/vendor/github.com/prometheus/procfs/internal/util/parse.go +++ b/api/vendor/github.com/prometheus/procfs/internal/util/parse.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/internal/util/readfile.go b/api/vendor/github.com/prometheus/procfs/internal/util/readfile.go index 71b7a70ebd68..0e41f71af189 100644 --- a/api/vendor/github.com/prometheus/procfs/internal/util/readfile.go +++ b/api/vendor/github.com/prometheus/procfs/internal/util/readfile.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go b/api/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go index d5404a6d7284..8318d8dfd519 100644 --- a/api/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go +++ b/api/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go b/api/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go index 1d86f5e63f3c..15bb096ee20f 100644 --- a/api/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go +++ b/api/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/internal/util/valueparser.go b/api/vendor/github.com/prometheus/procfs/internal/util/valueparser.go index fe2355d3c6ff..e0ed671ea076 100644 --- a/api/vendor/github.com/prometheus/procfs/internal/util/valueparser.go +++ b/api/vendor/github.com/prometheus/procfs/internal/util/valueparser.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/ipvs.go b/api/vendor/github.com/prometheus/procfs/ipvs.go index bc3a20c932d1..5374da9fa891 100644 --- a/api/vendor/github.com/prometheus/procfs/ipvs.go +++ b/api/vendor/github.com/prometheus/procfs/ipvs.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/kernel_hung.go b/api/vendor/github.com/prometheus/procfs/kernel_hung.go new file mode 100644 index 000000000000..539c11151420 --- /dev/null +++ b/api/vendor/github.com/prometheus/procfs/kernel_hung.go @@ -0,0 +1,45 @@ +// Copyright 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 !windows +// +build !windows + +package procfs + +import ( + "os" + "strconv" + "strings" +) + +// KernelHung contains information about to the kernel's hung_task_detect_count number. +type KernelHung struct { + // Indicates the total number of tasks that have been detected as hung since the system boot. + // This file shows up if `CONFIG_DETECT_HUNG_TASK` is enabled. + HungTaskDetectCount *uint64 +} + +// KernelHung returns values from /proc/sys/kernel/hung_task_detect_count. +func (fs FS) KernelHung() (KernelHung, error) { + data, err := os.ReadFile(fs.proc.Path("sys", "kernel", "hung_task_detect_count")) + if err != nil { + return KernelHung{}, err + } + val, err := strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) + if err != nil { + return KernelHung{}, err + } + return KernelHung{ + HungTaskDetectCount: &val, + }, nil +} diff --git a/api/vendor/github.com/prometheus/procfs/kernel_random.go b/api/vendor/github.com/prometheus/procfs/kernel_random.go index db88566bdf0a..b66565a1043d 100644 --- a/api/vendor/github.com/prometheus/procfs/kernel_random.go +++ b/api/vendor/github.com/prometheus/procfs/kernel_random.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/loadavg.go b/api/vendor/github.com/prometheus/procfs/loadavg.go index 332e76c17f5b..c8c78a65edc5 100644 --- a/api/vendor/github.com/prometheus/procfs/loadavg.go +++ b/api/vendor/github.com/prometheus/procfs/loadavg.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/mdstat.go b/api/vendor/github.com/prometheus/procfs/mdstat.go index 67a9d2b44867..d66eeda82a2f 100644 --- a/api/vendor/github.com/prometheus/procfs/mdstat.go +++ b/api/vendor/github.com/prometheus/procfs/mdstat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -27,13 +27,34 @@ var ( recoveryLinePctRE = regexp.MustCompile(`= (.+)%`) recoveryLineFinishRE = regexp.MustCompile(`finish=(.+)min`) recoveryLineSpeedRE = regexp.MustCompile(`speed=(.+)[A-Z]`) - componentDeviceRE = regexp.MustCompile(`(.*)\[\d+\]`) + componentDeviceRE = regexp.MustCompile(`(.*)\[(\d+)\](\([SF]+\))?`) + personalitiesPrefix = "Personalities : " ) +type MDStatComponent struct { + // Name of the component device. + Name string + // DescriptorIndex number of component device, e.g. the order in the superblock. + DescriptorIndex int32 + // Flags per Linux drivers/md/md.[ch] as of v6.12-rc1 + // Subset that are exposed in mdstat + WriteMostly bool + Journal bool + Faulty bool // "Faulty" is what kernel source uses for "(F)" + Spare bool + Replacement bool + // Some additional flags that are NOT exposed in procfs today; they may + // be available via sysfs. + // In_sync, Bitmap_sync, Blocked, WriteErrorSeen, FaultRecorded, + // BlockedBadBlocks, WantReplacement, Candidate, ... +} + // MDStat holds info parsed from /proc/mdstat. type MDStat struct { // Name of the device. Name string + // raid type of the device. + Type string // activity-state of the device. ActivityState string // Number of active disks. @@ -58,8 +79,8 @@ type MDStat struct { BlocksSyncedFinishTime float64 // current sync speed (in Kilobytes/sec) BlocksSyncedSpeed float64 - // Name of md component devices - Devices []string + // component devices + Devices []MDStatComponent } // MDStat parses an mdstat-file (/proc/mdstat) and returns a slice of @@ -80,28 +101,52 @@ func (fs FS) MDStat() ([]MDStat, error) { // parseMDStat parses data from mdstat file (/proc/mdstat) and returns a slice of // structs containing the relevant info. func parseMDStat(mdStatData []byte) ([]MDStat, error) { + // TODO: + // - parse global hotspares from the "unused devices" line. mdStats := []MDStat{} lines := strings.Split(string(mdStatData), "\n") + knownRaidTypes := make(map[string]bool) for i, line := range lines { if strings.TrimSpace(line) == "" || line[0] == ' ' || - strings.HasPrefix(line, "Personalities") || strings.HasPrefix(line, "unused") { continue } + // Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10] + if len(knownRaidTypes) == 0 && strings.HasPrefix(line, personalitiesPrefix) { + personalities := strings.Fields(line[len(personalitiesPrefix):]) + for _, word := range personalities { + word := word[1 : len(word)-1] + knownRaidTypes[word] = true + } + continue + } deviceFields := strings.Fields(line) if len(deviceFields) < 3 { return nil, fmt.Errorf("%w: Expected 3+ lines, got %q", ErrFileParse, line) } mdName := deviceFields[0] // mdx - state := deviceFields[2] // active or inactive + state := deviceFields[2] // active, inactive, broken + + mdType := "unknown" // raid1, raid5, etc. + var deviceStartIndex int + if len(deviceFields) > 3 { // mdType may be in the 3rd or 4th field + if isRaidType(deviceFields[3], knownRaidTypes) { + mdType = deviceFields[3] + deviceStartIndex = 4 + } else if len(deviceFields) > 4 && isRaidType(deviceFields[4], knownRaidTypes) { + // if the 3rd field is (...), the 4th field is the mdType + mdType = deviceFields[4] + deviceStartIndex = 5 + } + } if len(lines) <= i+3 { return nil, fmt.Errorf("%w: Too few lines for md device: %q", ErrFileParse, mdName) } - // Failed disks have the suffix (F) & Spare disks have the suffix (S). + // Failed (Faulty) disks have the suffix (F) & Spare disks have the suffix (S). fail := int64(strings.Count(line, "(F)")) spare := int64(strings.Count(line, "(S)")) active, total, down, size, err := evalStatusLine(lines[i], lines[i+1]) @@ -123,16 +168,20 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { finish := float64(0) pct := float64(0) recovering := strings.Contains(lines[syncLineIdx], "recovery") + reshaping := strings.Contains(lines[syncLineIdx], "reshape") resyncing := strings.Contains(lines[syncLineIdx], "resync") checking := strings.Contains(lines[syncLineIdx], "check") // Append recovery and resyncing state info. - if recovering || resyncing || checking { - if recovering { + if recovering || resyncing || checking || reshaping { + switch { + case recovering: state = "recovering" - } else if checking { + case reshaping: + state = "reshaping" + case checking: state = "checking" - } else { + default: state = "resyncing" } @@ -148,8 +197,14 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { } } + devices, err := evalComponentDevices(deviceFields[deviceStartIndex:]) + if err != nil { + return nil, fmt.Errorf("error parsing components in md device %q: %w", mdName, err) + } + mdStats = append(mdStats, MDStat{ Name: mdName, + Type: mdType, ActivityState: state, DisksActive: active, DisksFailed: fail, @@ -162,14 +217,24 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { BlocksSyncedPct: pct, BlocksSyncedFinishTime: finish, BlocksSyncedSpeed: speed, - Devices: evalComponentDevices(deviceFields), + Devices: devices, }) } return mdStats, nil } +// check if a string's format is like the mdType +// Rule 1: mdType should not be like (...) +// Rule 2: mdType should not be like sda[0] +// . +func isRaidType(mdType string, knownRaidTypes map[string]bool) bool { + _, ok := knownRaidTypes[mdType] + return !strings.ContainsAny(mdType, "([") && ok +} + func evalStatusLine(deviceLine, statusLine string) (active, total, down, size int64, err error) { + // e.g. 523968 blocks super 1.2 [4/4] [UUUU] statusFields := strings.Fields(statusLine) if len(statusFields) < 1 { return 0, 0, 0, 0, fmt.Errorf("%w: Unexpected statusline %q: %w", ErrFileParse, statusLine, err) @@ -260,17 +325,29 @@ func evalRecoveryLine(recoveryLine string) (blocksSynced int64, blocksToBeSynced return blocksSynced, blocksToBeSynced, pct, finish, speed, nil } -func evalComponentDevices(deviceFields []string) []string { - mdComponentDevices := make([]string, 0) - if len(deviceFields) > 3 { - for _, field := range deviceFields[4:] { - match := componentDeviceRE.FindStringSubmatch(field) - if match == nil { - continue - } - mdComponentDevices = append(mdComponentDevices, match[1]) +func evalComponentDevices(deviceFields []string) ([]MDStatComponent, error) { + mdComponentDevices := make([]MDStatComponent, 0) + for _, field := range deviceFields { + match := componentDeviceRE.FindStringSubmatch(field) + if match == nil { + continue + } + descriptorIndex, err := strconv.ParseInt(match[2], 10, 32) + if err != nil { + return mdComponentDevices, fmt.Errorf("error parsing int from device %q: %w", match[2], err) } + mdComponentDevices = append(mdComponentDevices, MDStatComponent{ + Name: match[1], + DescriptorIndex: int32(descriptorIndex), + // match may contain one or more of these + // https://github.com/torvalds/linux/blob/7ec462100ef9142344ddbf86f2c3008b97acddbe/drivers/md/md.c#L8376-L8392 + Faulty: strings.Contains(match[3], "(F)"), + Spare: strings.Contains(match[3], "(S)"), + Journal: strings.Contains(match[3], "(J)"), + Replacement: strings.Contains(match[3], "(R)"), + WriteMostly: strings.Contains(match[3], "(W)"), + }) } - return mdComponentDevices + return mdComponentDevices, nil } diff --git a/api/vendor/github.com/prometheus/procfs/meminfo.go b/api/vendor/github.com/prometheus/procfs/meminfo.go index 4b2c4050a3df..34203831871e 100644 --- a/api/vendor/github.com/prometheus/procfs/meminfo.go +++ b/api/vendor/github.com/prometheus/procfs/meminfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -66,6 +66,10 @@ type Meminfo struct { // Memory which has been evicted from RAM, and is temporarily // on the disk SwapFree *uint64 + // Memory consumed by the zswap backend (compressed size) + Zswap *uint64 + // Amount of anonymous memory stored in zswap (original size) + Zswapped *uint64 // Memory which is waiting to get written back to the disk Dirty *uint64 // Memory which is actively being written back to the disk @@ -85,6 +89,8 @@ type Meminfo struct { // amount of memory dedicated to the lowest level of page // tables. PageTables *uint64 + // secondary page tables. + SecPageTables *uint64 // NFS pages sent to the server, but not yet committed to // stable storage NFSUnstable *uint64 @@ -129,15 +135,18 @@ type Meminfo struct { Percpu *uint64 HardwareCorrupted *uint64 AnonHugePages *uint64 + FileHugePages *uint64 ShmemHugePages *uint64 ShmemPmdMapped *uint64 CmaTotal *uint64 CmaFree *uint64 + Unaccepted *uint64 HugePagesTotal *uint64 HugePagesFree *uint64 HugePagesRsvd *uint64 HugePagesSurp *uint64 Hugepagesize *uint64 + Hugetlb *uint64 DirectMap4k *uint64 DirectMap2M *uint64 DirectMap1G *uint64 @@ -161,6 +170,8 @@ type Meminfo struct { MlockedBytes *uint64 SwapTotalBytes *uint64 SwapFreeBytes *uint64 + ZswapBytes *uint64 + ZswappedBytes *uint64 DirtyBytes *uint64 WritebackBytes *uint64 AnonPagesBytes *uint64 @@ -171,6 +182,7 @@ type Meminfo struct { SUnreclaimBytes *uint64 KernelStackBytes *uint64 PageTablesBytes *uint64 + SecPageTablesBytes *uint64 NFSUnstableBytes *uint64 BounceBytes *uint64 WritebackTmpBytes *uint64 @@ -182,11 +194,14 @@ type Meminfo struct { PercpuBytes *uint64 HardwareCorruptedBytes *uint64 AnonHugePagesBytes *uint64 + FileHugePagesBytes *uint64 ShmemHugePagesBytes *uint64 ShmemPmdMappedBytes *uint64 CmaTotalBytes *uint64 CmaFreeBytes *uint64 + UnacceptedBytes *uint64 HugepagesizeBytes *uint64 + HugetlbBytes *uint64 DirectMap4kBytes *uint64 DirectMap2MBytes *uint64 DirectMap1GBytes *uint64 @@ -287,6 +302,12 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "SwapFree:": m.SwapFree = &val m.SwapFreeBytes = &valBytes + case "Zswap:": + m.Zswap = &val + m.ZswapBytes = &valBytes + case "Zswapped:": + m.Zswapped = &val + m.ZswappedBytes = &valBytes case "Dirty:": m.Dirty = &val m.DirtyBytes = &valBytes @@ -317,6 +338,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "PageTables:": m.PageTables = &val m.PageTablesBytes = &valBytes + case "SecPageTables:": + m.SecPageTables = &val + m.SecPageTablesBytes = &valBytes case "NFS_Unstable:": m.NFSUnstable = &val m.NFSUnstableBytes = &valBytes @@ -350,6 +374,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "AnonHugePages:": m.AnonHugePages = &val m.AnonHugePagesBytes = &valBytes + case "FileHugePages:": + m.FileHugePages = &val + m.FileHugePagesBytes = &valBytes case "ShmemHugePages:": m.ShmemHugePages = &val m.ShmemHugePagesBytes = &valBytes @@ -362,6 +389,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "CmaFree:": m.CmaFree = &val m.CmaFreeBytes = &valBytes + case "Unaccepted:": + m.Unaccepted = &val + m.UnacceptedBytes = &valBytes case "HugePages_Total:": m.HugePagesTotal = &val case "HugePages_Free:": @@ -373,6 +403,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "Hugepagesize:": m.Hugepagesize = &val m.HugepagesizeBytes = &valBytes + case "Hugetlb:": + m.Hugetlb = &val + m.HugetlbBytes = &valBytes case "DirectMap4k:": m.DirectMap4k = &val m.DirectMap4kBytes = &valBytes diff --git a/api/vendor/github.com/prometheus/procfs/mountinfo.go b/api/vendor/github.com/prometheus/procfs/mountinfo.go index a704c5e735f3..9414a12f42f0 100644 --- a/api/vendor/github.com/prometheus/procfs/mountinfo.go +++ b/api/vendor/github.com/prometheus/procfs/mountinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -147,8 +147,7 @@ func mountOptionsParseOptionalFields(o []string) (map[string]string, error) { // mountOptionsParser parses the mount options, superblock options. func mountOptionsParser(mountOptions string) map[string]string { opts := make(map[string]string) - options := strings.Split(mountOptions, ",") - for _, opt := range options { + for opt := range strings.SplitSeq(mountOptions, ",") { splitOption := strings.Split(opt, "=") if len(splitOption) < 2 { key := splitOption[0] @@ -178,3 +177,21 @@ func GetProcMounts(pid int) ([]*MountInfo, error) { } return parseMountInfo(data) } + +// GetMounts retrieves mountinfo information from `/proc/self/mountinfo`. +func (fs FS) GetMounts() ([]*MountInfo, error) { + data, err := util.ReadFileNoStat(fs.proc.Path("self/mountinfo")) + if err != nil { + return nil, err + } + return parseMountInfo(data) +} + +// GetProcMounts retrieves mountinfo information from a processes' `/proc//mountinfo`. +func (fs FS) GetProcMounts(pid int) ([]*MountInfo, error) { + data, err := util.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%d/mountinfo", pid))) + if err != nil { + return nil, err + } + return parseMountInfo(data) +} diff --git a/api/vendor/github.com/prometheus/procfs/mountstats.go b/api/vendor/github.com/prometheus/procfs/mountstats.go index 50caa73274eb..e503cb3a6c5d 100644 --- a/api/vendor/github.com/prometheus/procfs/mountstats.go +++ b/api/vendor/github.com/prometheus/procfs/mountstats.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -383,7 +383,7 @@ func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, e if stats.Opts == nil { stats.Opts = map[string]string{} } - for _, opt := range strings.Split(ss[1], ",") { + for opt := range strings.SplitSeq(ss[1], ",") { split := strings.Split(opt, "=") if len(split) == 2 { stats.Opts[split[0]] = split[1] diff --git a/api/vendor/github.com/prometheus/procfs/net_conntrackstat.go b/api/vendor/github.com/prometheus/procfs/net_conntrackstat.go index 316df5fbb74e..e9ca35707905 100644 --- a/api/vendor/github.com/prometheus/procfs/net_conntrackstat.go +++ b/api/vendor/github.com/prometheus/procfs/net_conntrackstat.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_dev.go b/api/vendor/github.com/prometheus/procfs/net_dev.go index e66208aa05fe..7b3e1d61c95e 100644 --- a/api/vendor/github.com/prometheus/procfs/net_dev.go +++ b/api/vendor/github.com/prometheus/procfs/net_dev.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_dev_snmp6.go b/api/vendor/github.com/prometheus/procfs/net_dev_snmp6.go index f50b38e35288..2a0f60f29fee 100644 --- a/api/vendor/github.com/prometheus/procfs/net_dev_snmp6.go +++ b/api/vendor/github.com/prometheus/procfs/net_dev_snmp6.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -18,6 +18,7 @@ import ( "errors" "io" "os" + "path/filepath" "strconv" "strings" ) @@ -56,7 +57,9 @@ func newNetDevSNMP6(dir string) (NetDevSNMP6, error) { } for _, iFaceFile := range ifaceFiles { - f, err := os.Open(dir + "/" + iFaceFile.Name()) + filePath := filepath.Join(dir, iFaceFile.Name()) + + f, err := os.Open(filePath) if err != nil { return netDevSNMP6, err } diff --git a/api/vendor/github.com/prometheus/procfs/net_ip_socket.go b/api/vendor/github.com/prometheus/procfs/net_ip_socket.go index 19e3378f72d7..9291f8cd4c80 100644 --- a/api/vendor/github.com/prometheus/procfs/net_ip_socket.go +++ b/api/vendor/github.com/prometheus/procfs/net_ip_socket.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_protocols.go b/api/vendor/github.com/prometheus/procfs/net_protocols.go index 8d4b1ac05b00..eaa996cbcf19 100644 --- a/api/vendor/github.com/prometheus/procfs/net_protocols.go +++ b/api/vendor/github.com/prometheus/procfs/net_protocols.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 @@ -169,7 +169,7 @@ func (pc *NetProtocolCapabilities) parseCapabilities(capabilities []string) erro &pc.EnterMemoryPressure, } - for i := 0; i < len(capabilities); i++ { + for i := range capabilities { switch capabilities[i] { case "y": *capabilityFields[i] = true diff --git a/api/vendor/github.com/prometheus/procfs/net_route.go b/api/vendor/github.com/prometheus/procfs/net_route.go index deb7029fe1ef..fa3812d9d00c 100644 --- a/api/vendor/github.com/prometheus/procfs/net_route.go +++ b/api/vendor/github.com/prometheus/procfs/net_route.go @@ -1,4 +1,4 @@ -// Copyright 2023 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_sockstat.go b/api/vendor/github.com/prometheus/procfs/net_sockstat.go index fae62b13d961..8b221ebfff75 100644 --- a/api/vendor/github.com/prometheus/procfs/net_sockstat.go +++ b/api/vendor/github.com/prometheus/procfs/net_sockstat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -139,9 +139,6 @@ func parseSockstatKVs(kvs []string) (map[string]int, error) { func parseSockstatProtocol(kvs map[string]int) NetSockstatProtocol { var nsp NetSockstatProtocol for k, v := range kvs { - // Capture the range variable to ensure we get unique pointers for - // each of the optional fields. - v := v switch k { case "inuse": nsp.InUse = v diff --git a/api/vendor/github.com/prometheus/procfs/net_softnet.go b/api/vendor/github.com/prometheus/procfs/net_softnet.go index 71c8059f4d77..4a2dfa18fd82 100644 --- a/api/vendor/github.com/prometheus/procfs/net_softnet.go +++ b/api/vendor/github.com/prometheus/procfs/net_softnet.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_tcp.go b/api/vendor/github.com/prometheus/procfs/net_tcp.go index 0396d72015c0..610ea78e5648 100644 --- a/api/vendor/github.com/prometheus/procfs/net_tcp.go +++ b/api/vendor/github.com/prometheus/procfs/net_tcp.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_tls_stat.go b/api/vendor/github.com/prometheus/procfs/net_tls_stat.go index 13994c1782f4..b1b3f6a6a2f5 100644 --- a/api/vendor/github.com/prometheus/procfs/net_tls_stat.go +++ b/api/vendor/github.com/prometheus/procfs/net_tls_stat.go @@ -1,4 +1,4 @@ -// Copyright 2023 Prometheus Team +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_udp.go b/api/vendor/github.com/prometheus/procfs/net_udp.go index 9ac3daf2d4c5..8a327791026a 100644 --- a/api/vendor/github.com/prometheus/procfs/net_udp.go +++ b/api/vendor/github.com/prometheus/procfs/net_udp.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_unix.go b/api/vendor/github.com/prometheus/procfs/net_unix.go index d7e0cacb4c67..e4d635923659 100644 --- a/api/vendor/github.com/prometheus/procfs/net_unix.go +++ b/api/vendor/github.com/prometheus/procfs/net_unix.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_wireless.go b/api/vendor/github.com/prometheus/procfs/net_wireless.go index 7c597bc87089..69d079445161 100644 --- a/api/vendor/github.com/prometheus/procfs/net_wireless.go +++ b/api/vendor/github.com/prometheus/procfs/net_wireless.go @@ -1,4 +1,4 @@ -// Copyright 2023 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/net_xfrm.go b/api/vendor/github.com/prometheus/procfs/net_xfrm.go index 932ef2046847..5a9f497d1903 100644 --- a/api/vendor/github.com/prometheus/procfs/net_xfrm.go +++ b/api/vendor/github.com/prometheus/procfs/net_xfrm.go @@ -1,4 +1,4 @@ -// Copyright 2017 Prometheus Team +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/netstat.go b/api/vendor/github.com/prometheus/procfs/netstat.go index 742dff453ba8..dbdae473924b 100644 --- a/api/vendor/github.com/prometheus/procfs/netstat.go +++ b/api/vendor/github.com/prometheus/procfs/netstat.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/nfnetlink_queue.go b/api/vendor/github.com/prometheus/procfs/nfnetlink_queue.go new file mode 100644 index 000000000000..b0a73b11e9e4 --- /dev/null +++ b/api/vendor/github.com/prometheus/procfs/nfnetlink_queue.go @@ -0,0 +1,85 @@ +// Copyright 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 procfs + +import ( + "bufio" + "bytes" + "fmt" + + "github.com/prometheus/procfs/internal/util" +) + +const nfNetLinkQueueFormat = "%d %d %d %d %d %d %d %d %d" + +// NFNetLinkQueue contains general information about netfilter queues found in /proc/net/netfilter/nfnetlink_queue. +type NFNetLinkQueue struct { + // id of the queue + QueueID uint + // pid of process handling the queue + PeerPID uint + // number of packets waiting for a decision + QueueTotal uint + // indicate how userspace receive packets + CopyMode uint + // size of copy + CopyRange uint + // number of items dropped by the kernel because too many packets were waiting a decision. + // It queue_total is superior to queue_max_len (1024 per default) the packets are dropped. + QueueDropped uint + // number of packets dropped by userspace (due to kernel send failure on the netlink socket) + QueueUserDropped uint + // sequence number of packets queued. It gives a correct approximation of the number of queued packets. + SequenceID uint + // internal value (number of entity using the queue) + Use uint +} + +// NFNetLinkQueue returns information about current state of netfilter queues. +func (fs FS) NFNetLinkQueue() ([]NFNetLinkQueue, error) { + data, err := util.ReadFileNoStat(fs.proc.Path("net/netfilter/nfnetlink_queue")) + if err != nil { + return nil, err + } + + queue := []NFNetLinkQueue{} + if len(data) == 0 { + return queue, nil + } + + scanner := bufio.NewScanner(bytes.NewReader(data)) + for scanner.Scan() { + line := scanner.Text() + nFNetLinkQueue, err := parseNFNetLinkQueueLine(line) + if err != nil { + return nil, err + } + queue = append(queue, *nFNetLinkQueue) + } + return queue, nil +} + +// parseNFNetLinkQueueLine parses each line of the /proc/net/netfilter/nfnetlink_queue file. +func parseNFNetLinkQueueLine(line string) (*NFNetLinkQueue, error) { + nFNetLinkQueue := NFNetLinkQueue{} + _, err := fmt.Sscanf( + line, nfNetLinkQueueFormat, + &nFNetLinkQueue.QueueID, &nFNetLinkQueue.PeerPID, &nFNetLinkQueue.QueueTotal, &nFNetLinkQueue.CopyMode, + &nFNetLinkQueue.CopyRange, &nFNetLinkQueue.QueueDropped, &nFNetLinkQueue.QueueUserDropped, &nFNetLinkQueue.SequenceID, &nFNetLinkQueue.Use, + ) + if err != nil { + return nil, err + } + return &nFNetLinkQueue, nil +} diff --git a/api/vendor/github.com/prometheus/procfs/proc.go b/api/vendor/github.com/prometheus/procfs/proc.go index 368187fa884d..39c14aa55ebd 100644 --- a/api/vendor/github.com/prometheus/procfs/proc.go +++ b/api/vendor/github.com/prometheus/procfs/proc.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -49,7 +49,7 @@ func (p Procs) Less(i, j int) bool { return p[i].PID < p[j].PID } // Self returns a process for the current process read via /proc/self. func Self() (Proc, error) { fs, err := NewFS(DefaultMountPoint) - if err != nil || errors.Unwrap(err) == ErrMountPoint { + if err != nil || errors.Is(err, ErrMountPoint) { return Proc{}, err } return fs.Self() diff --git a/api/vendor/github.com/prometheus/procfs/proc_cgroup.go b/api/vendor/github.com/prometheus/procfs/proc_cgroup.go index 4a64347c03a2..535c08d6fc01 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_cgroup.go +++ b/api/vendor/github.com/prometheus/procfs/proc_cgroup.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_cgroups.go b/api/vendor/github.com/prometheus/procfs/proc_cgroups.go index 5dd4938999ad..0b275c3b1f5c 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_cgroups.go +++ b/api/vendor/github.com/prometheus/procfs/proc_cgroups.go @@ -1,4 +1,4 @@ -// Copyright 2021 The Prometheus Authors +// Copyright 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 @@ -40,13 +40,13 @@ type CgroupSummary struct { // parseCgroupSummary parses each line of the /proc/cgroup file // Line format is `subsys_name hierarchy num_cgroups enabled`. -func parseCgroupSummaryString(CgroupSummaryStr string) (*CgroupSummary, error) { +func parseCgroupSummaryString(cgroupSummaryStr string) (*CgroupSummary, error) { var err error - fields := strings.Fields(CgroupSummaryStr) + fields := strings.Fields(cgroupSummaryStr) // require at least 4 fields if len(fields) < 4 { - return nil, fmt.Errorf("%w: 4+ fields required, found %d fields in cgroup info string: %s", ErrFileParse, len(fields), CgroupSummaryStr) + return nil, fmt.Errorf("%w: 4+ fields required, found %d fields in cgroup info string: %s", ErrFileParse, len(fields), cgroupSummaryStr) } CgroupSummary := &CgroupSummary{ diff --git a/api/vendor/github.com/prometheus/procfs/proc_environ.go b/api/vendor/github.com/prometheus/procfs/proc_environ.go index 57a89895d66a..5b941de04779 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_environ.go +++ b/api/vendor/github.com/prometheus/procfs/proc_environ.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_fdinfo.go b/api/vendor/github.com/prometheus/procfs/proc_fdinfo.go index fa761b35295e..fa57761dbe36 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_fdinfo.go +++ b/api/vendor/github.com/prometheus/procfs/proc_fdinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -60,15 +60,16 @@ func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { scanner := bufio.NewScanner(bytes.NewReader(data)) for scanner.Scan() { text = scanner.Text() - if rPos.MatchString(text) { + switch { + case rPos.MatchString(text): pos = rPos.FindStringSubmatch(text)[1] - } else if rFlags.MatchString(text) { + case rFlags.MatchString(text): flags = rFlags.FindStringSubmatch(text)[1] - } else if rMntID.MatchString(text) { + case rMntID.MatchString(text): mntid = rMntID.FindStringSubmatch(text)[1] - } else if rIno.MatchString(text) { + case rIno.MatchString(text): ino = rIno.FindStringSubmatch(text)[1] - } else if rInotify.MatchString(text) { + case rInotify.MatchString(text): newInotify, err := parseInotifyInfo(text) if err != nil { return nil, err diff --git a/api/vendor/github.com/prometheus/procfs/proc_interrupts.go b/api/vendor/github.com/prometheus/procfs/proc_interrupts.go index 86b4b4524632..b942c50723ca 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_interrupts.go +++ b/api/vendor/github.com/prometheus/procfs/proc_interrupts.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_io.go b/api/vendor/github.com/prometheus/procfs/proc_io.go index d15b66ddb64a..dd8086ba2e7c 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_io.go +++ b/api/vendor/github.com/prometheus/procfs/proc_io.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_limits.go b/api/vendor/github.com/prometheus/procfs/proc_limits.go index 9530b14bc681..4b7d33784712 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_limits.go +++ b/api/vendor/github.com/prometheus/procfs/proc_limits.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -19,6 +19,7 @@ import ( "os" "regexp" "strconv" + "strings" ) // ProcLimits represents the soft limits for each of the process's resource @@ -74,7 +75,7 @@ const ( ) var ( - limitsMatch = regexp.MustCompile(`(Max \w+\s{0,1}?\w*\s{0,1}\w*)\s{2,}(\w+)\s+(\w+)`) + limitsMatch = regexp.MustCompile(`(Max \w+\s??\w*\s?\w*)\s{2,}(\w+)\s+(\w+)`) ) // NewLimits returns the current soft limits of the process. @@ -106,7 +107,7 @@ func (p Proc) Limits() (ProcLimits, error) { return ProcLimits{}, fmt.Errorf("%w: couldn't parse %q line %q", ErrFileParse, f.Name(), s.Text()) } - switch fields[1] { + switch strings.TrimSpace(fields[1]) { case "Max cpu time": l.CPUTime, err = parseUint(fields[2]) case "Max file size": diff --git a/api/vendor/github.com/prometheus/procfs/proc_maps.go b/api/vendor/github.com/prometheus/procfs/proc_maps.go index 7e75c286b5b4..cc519f92f9af 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_maps.go +++ b/api/vendor/github.com/prometheus/procfs/proc_maps.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_netstat.go b/api/vendor/github.com/prometheus/procfs/proc_netstat.go index 4248c1716ee9..7f94cc89145b 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_netstat.go +++ b/api/vendor/github.com/prometheus/procfs/proc_netstat.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_ns.go b/api/vendor/github.com/prometheus/procfs/proc_ns.go index 0f8f847f954b..5fc0eb9e2f9f 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_ns.go +++ b/api/vendor/github.com/prometheus/procfs/proc_ns.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_psi.go b/api/vendor/github.com/prometheus/procfs/proc_psi.go index ccd35f153a05..cc2c5de873e0 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_psi.go +++ b/api/vendor/github.com/prometheus/procfs/proc_psi.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_smaps.go b/api/vendor/github.com/prometheus/procfs/proc_smaps.go index 9a297afcf89e..3e48afd1d39c 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_smaps.go +++ b/api/vendor/github.com/prometheus/procfs/proc_smaps.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_snmp.go b/api/vendor/github.com/prometheus/procfs/proc_snmp.go index 4bdc90b07eae..8d9a9bcd67aa 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_snmp.go +++ b/api/vendor/github.com/prometheus/procfs/proc_snmp.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_snmp6.go b/api/vendor/github.com/prometheus/procfs/proc_snmp6.go index fb7fd3995bef..841fef464925 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_snmp6.go +++ b/api/vendor/github.com/prometheus/procfs/proc_snmp6.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/proc_stat.go b/api/vendor/github.com/prometheus/procfs/proc_stat.go index 06a8d931c983..02e3f9e316af 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_stat.go +++ b/api/vendor/github.com/prometheus/procfs/proc_stat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -101,6 +101,12 @@ type ProcStat struct { RSS int // Soft limit in bytes on the rss of the process. RSSLimit uint64 + // The address above which program text can run. + StartCode uint64 + // The address below which program text can run. + EndCode uint64 + // The address of the start (i.e., bottom) of the stack. + StartStack uint64 // CPU number last executed on. Processor uint // Real-time scheduling priority, a number in the range 1 to 99 for processes @@ -177,9 +183,9 @@ func (p Proc) Stat() (ProcStat, error) { &s.VSize, &s.RSS, &s.RSSLimit, - &ignoreUint64, - &ignoreUint64, - &ignoreUint64, + &s.StartCode, + &s.EndCode, + &s.StartStack, &ignoreUint64, &ignoreUint64, &ignoreUint64, diff --git a/api/vendor/github.com/prometheus/procfs/proc_statm.go b/api/vendor/github.com/prometheus/procfs/proc_statm.go new file mode 100644 index 000000000000..b0a936016774 --- /dev/null +++ b/api/vendor/github.com/prometheus/procfs/proc_statm.go @@ -0,0 +1,116 @@ +// Copyright 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 procfs + +import ( + "os" + "strconv" + "strings" + + "github.com/prometheus/procfs/internal/util" +) + +// - https://man7.org/linux/man-pages/man5/proc_pid_statm.5.html + +// ProcStatm Provides memory usage information for a process, measured in memory pages. +// Read from /proc/[pid]/statm. +type ProcStatm struct { + // The process ID. + PID int + // total program size (same as VmSize in status) + Size uint64 + // resident set size (same as VmRSS in status) + Resident uint64 + // number of resident shared pages (i.e., backed by a file) + Shared uint64 + // text (code) + Text uint64 + // library (unused since Linux 2.6; always 0) + Lib uint64 + // data + stack + Data uint64 + // dirty pages (unused since Linux 2.6; always 0) + Dt uint64 +} + +// NewStatm returns the current status information of the process. +// Deprecated: Use p.Statm() instead. +func (p Proc) NewStatm() (ProcStatm, error) { + return p.Statm() +} + +// Statm returns the current memory usage information of the process. +func (p Proc) Statm() (ProcStatm, error) { + data, err := util.ReadFileNoStat(p.path("statm")) + if err != nil { + return ProcStatm{}, err + } + + statmSlice, err := parseStatm(data) + if err != nil { + return ProcStatm{}, err + } + + procStatm := ProcStatm{ + PID: p.PID, + Size: statmSlice[0], + Resident: statmSlice[1], + Shared: statmSlice[2], + Text: statmSlice[3], + Lib: statmSlice[4], + Data: statmSlice[5], + Dt: statmSlice[6], + } + + return procStatm, nil +} + +// parseStatm return /proc/[pid]/statm data to uint64 slice. +func parseStatm(data []byte) ([]uint64, error) { + var statmSlice []uint64 + statmItems := strings.Fields(string(data)) + for i := range statmItems { + statmItem, err := strconv.ParseUint(statmItems[i], 10, 64) + if err != nil { + return nil, err + } + statmSlice = append(statmSlice, statmItem) + } + return statmSlice, nil +} + +// SizeBytes returns the process of total program size in bytes. +func (s ProcStatm) SizeBytes() uint64 { + return s.Size * uint64(os.Getpagesize()) +} + +// ResidentBytes returns the process of resident set size in bytes. +func (s ProcStatm) ResidentBytes() uint64 { + return s.Resident * uint64(os.Getpagesize()) +} + +// SHRBytes returns the process of share memory size in bytes. +func (s ProcStatm) SHRBytes() uint64 { + return s.Shared * uint64(os.Getpagesize()) +} + +// TextBytes returns the process of text (code) size in bytes. +func (s ProcStatm) TextBytes() uint64 { + return s.Text * uint64(os.Getpagesize()) +} + +// DataBytes returns the process of data + stack size in bytes. +func (s ProcStatm) DataBytes() uint64 { + return s.Data * uint64(os.Getpagesize()) +} diff --git a/api/vendor/github.com/prometheus/procfs/proc_status.go b/api/vendor/github.com/prometheus/procfs/proc_status.go index dd8aa56885ec..1ed2bced4174 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_status.go +++ b/api/vendor/github.com/prometheus/procfs/proc_status.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -16,7 +16,7 @@ package procfs import ( "bytes" "math/bits" - "sort" + "slices" "strconv" "strings" @@ -94,8 +94,7 @@ func (p Proc) NewStatus() (ProcStatus, error) { s := ProcStatus{PID: p.PID} - lines := strings.Split(string(data), "\n") - for _, line := range lines { + for line := range strings.SplitSeq(string(data), "\n") { if !bytes.Contains([]byte(line), []byte(":")) { continue } @@ -222,7 +221,7 @@ func calcCpusAllowedList(cpuString string) []uint64 { } - sort.Slice(g, func(i, j int) bool { return g[i] < g[j] }) + slices.Sort(g) return g } diff --git a/api/vendor/github.com/prometheus/procfs/proc_sys.go b/api/vendor/github.com/prometheus/procfs/proc_sys.go index 3810d1ac999f..52658a4d52d4 100644 --- a/api/vendor/github.com/prometheus/procfs/proc_sys.go +++ b/api/vendor/github.com/prometheus/procfs/proc_sys.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/schedstat.go b/api/vendor/github.com/prometheus/procfs/schedstat.go index 5f7f32dc83c6..fafd8dff740b 100644 --- a/api/vendor/github.com/prometheus/procfs/schedstat.go +++ b/api/vendor/github.com/prometheus/procfs/schedstat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/slab.go b/api/vendor/github.com/prometheus/procfs/slab.go index 8611c901770a..32a04678ad0b 100644 --- a/api/vendor/github.com/prometheus/procfs/slab.go +++ b/api/vendor/github.com/prometheus/procfs/slab.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/softirqs.go b/api/vendor/github.com/prometheus/procfs/softirqs.go index 403e6ae70868..47b73a7297b3 100644 --- a/api/vendor/github.com/prometheus/procfs/softirqs.go +++ b/api/vendor/github.com/prometheus/procfs/softirqs.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/stat.go b/api/vendor/github.com/prometheus/procfs/stat.go index e36b41c18a90..593ad0f62f05 100644 --- a/api/vendor/github.com/prometheus/procfs/stat.go +++ b/api/vendor/github.com/prometheus/procfs/stat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -16,6 +16,7 @@ package procfs import ( "bufio" "bytes" + "errors" "fmt" "io" "strconv" @@ -92,7 +93,7 @@ func parseCPUStat(line string) (CPUStat, int64, error) { &cpuStat.Iowait, &cpuStat.IRQ, &cpuStat.SoftIRQ, &cpuStat.Steal, &cpuStat.Guest, &cpuStat.GuestNice) - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return CPUStat{}, -1, fmt.Errorf("%w: couldn't parse %q (cpu): %w", ErrFileParse, line, err) } if count == 0 { diff --git a/api/vendor/github.com/prometheus/procfs/swaps.go b/api/vendor/github.com/prometheus/procfs/swaps.go index 65fec834bf41..ee17bf4888cd 100644 --- a/api/vendor/github.com/prometheus/procfs/swaps.go +++ b/api/vendor/github.com/prometheus/procfs/swaps.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/thread.go b/api/vendor/github.com/prometheus/procfs/thread.go index 80e0e947be78..0cfbb5418445 100644 --- a/api/vendor/github.com/prometheus/procfs/thread.go +++ b/api/vendor/github.com/prometheus/procfs/thread.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/vm.go b/api/vendor/github.com/prometheus/procfs/vm.go index 51c49d89e81b..2a8d76390973 100644 --- a/api/vendor/github.com/prometheus/procfs/vm.go +++ b/api/vendor/github.com/prometheus/procfs/vm.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/api/vendor/github.com/prometheus/procfs/zoneinfo.go b/api/vendor/github.com/prometheus/procfs/zoneinfo.go index e54d94b09039..806e171147d0 100644 --- a/api/vendor/github.com/prometheus/procfs/zoneinfo.go +++ b/api/vendor/github.com/prometheus/procfs/zoneinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -88,11 +88,9 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) { zoneinfo := []Zoneinfo{} - zoneinfoBlocks := bytes.Split(zoneinfoData, []byte("\nNode")) - for _, block := range zoneinfoBlocks { + for block := range bytes.SplitSeq(zoneinfoData, []byte("\nNode")) { var zoneinfoElement Zoneinfo - lines := strings.Split(string(block), "\n") - for _, line := range lines { + for line := range strings.SplitSeq(string(block), "\n") { if nodeZone := nodeZoneRE.FindStringSubmatch(line); nodeZone != nil { zoneinfoElement.Node = nodeZone[1] diff --git a/api/vendor/gopkg.in/evanphx/json-patch.v4/README.md b/api/vendor/gopkg.in/evanphx/json-patch.v4/README.md index 28e35169375b..86fefd5bf7d6 100644 --- a/api/vendor/gopkg.in/evanphx/json-patch.v4/README.md +++ b/api/vendor/gopkg.in/evanphx/json-patch.v4/README.md @@ -4,7 +4,7 @@ well as for calculating & applying [RFC7396 JSON merge patches](https://tools.ietf.org/html/rfc7396). [![GoDoc](https://godoc.org/github.com/evanphx/json-patch?status.svg)](http://godoc.org/github.com/evanphx/json-patch) -[![Build Status](https://travis-ci.org/evanphx/json-patch.svg?branch=master)](https://travis-ci.org/evanphx/json-patch) +[![Build Status](https://github.com/evanphx/json-patch/actions/workflows/go.yml/badge.svg)](https://github.com/evanphx/json-patch/actions/workflows/go.yml) [![Report Card](https://goreportcard.com/badge/github.com/evanphx/json-patch)](https://goreportcard.com/report/github.com/evanphx/json-patch) # Get It! @@ -14,9 +14,7 @@ well as for calculating & applying [RFC7396 JSON merge patches](https://tools.ie go get -u github.com/evanphx/json-patch/v5 ``` -**Stable Versions**: -* Version 5: `go get -u gopkg.in/evanphx/json-patch.v5` -* Version 4: `go get -u gopkg.in/evanphx/json-patch.v4` +If you need version 4, use `go get -u gopkg.in/evanphx/json-patch.v4` (previous versions below `v3` are unavailable) @@ -314,4 +312,4 @@ go test -cover ./... ``` Builds for pull requests are tested automatically -using [TravisCI](https://travis-ci.org/evanphx/json-patch). +using [GitHub Actions](https://github.com/evanphx/json-patch/actions/workflows/go.yml). diff --git a/api/vendor/gopkg.in/evanphx/json-patch.v4/patch.go b/api/vendor/gopkg.in/evanphx/json-patch.v4/patch.go index dc2b7e51e60b..95136681ba76 100644 --- a/api/vendor/gopkg.in/evanphx/json-patch.v4/patch.go +++ b/api/vendor/gopkg.in/evanphx/json-patch.v4/patch.go @@ -3,11 +3,10 @@ package jsonpatch import ( "bytes" "encoding/json" + "errors" "fmt" "strconv" "strings" - - "github.com/pkg/errors" ) const ( @@ -277,7 +276,7 @@ func (o Operation) Path() (string, error) { return op, nil } - return "unknown", errors.Wrapf(ErrMissing, "operation missing path field") + return "unknown", fmt.Errorf("operation missing path field: %w", ErrMissing) } // From reads the "from" field of the Operation. @@ -294,7 +293,7 @@ func (o Operation) From() (string, error) { return op, nil } - return "unknown", errors.Wrapf(ErrMissing, "operation, missing from field") + return "unknown", fmt.Errorf("operation, missing from field: %w", ErrMissing) } func (o Operation) value() *lazyNode { @@ -319,7 +318,7 @@ func (o Operation) ValueInterface() (interface{}, error) { return v, nil } - return nil, errors.Wrapf(ErrMissing, "operation, missing value field") + return nil, fmt.Errorf("operation, missing value field: %w", ErrMissing) } func isArray(buf []byte) bool { @@ -359,7 +358,7 @@ func findObject(pd *container, path string) (container, string) { next, ok := doc.get(decodePatchKey(part)) - if next == nil || ok != nil { + if next == nil || ok != nil || next.raw == nil { return nil, "" } @@ -398,7 +397,7 @@ func (d *partialDoc) get(key string) (*lazyNode, error) { func (d *partialDoc) remove(key string) error { _, ok := (*d)[key] if !ok { - return errors.Wrapf(ErrMissing, "Unable to remove nonexistent key: %s", key) + return fmt.Errorf("Unable to remove nonexistent key: %s: %w", key, ErrMissing) } delete(*d, key) @@ -415,10 +414,10 @@ func (d *partialArray) set(key string, val *lazyNode) error { if idx < 0 { if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(*d) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(*d) } @@ -435,7 +434,7 @@ func (d *partialArray) add(key string, val *lazyNode) error { idx, err := strconv.Atoi(key) if err != nil { - return errors.Wrapf(err, "value was not a proper array index: '%s'", key) + return fmt.Errorf("value was not a proper array index: '%s': %w", key, err) } sz := len(*d) + 1 @@ -445,15 +444,15 @@ func (d *partialArray) add(key string, val *lazyNode) error { cur := *d if idx >= len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < 0 { if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(ary) } @@ -475,16 +474,16 @@ func (d *partialArray) get(key string) (*lazyNode, error) { if idx < 0 { if !SupportNegativeIndices { - return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(*d) { - return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(*d) } if idx >= len(*d) { - return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } return (*d)[idx], nil @@ -499,15 +498,15 @@ func (d *partialArray) remove(key string) error { cur := *d if idx >= len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < 0 { if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(cur) } @@ -525,18 +524,18 @@ func (d *partialArray) remove(key string) error { func (p Patch) add(doc *container, op Operation) error { path, err := op.Path() if err != nil { - return errors.Wrapf(ErrMissing, "add operation failed to decode path") + return fmt.Errorf("add operation failed to decode path: %w", ErrMissing) } con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "add operation does not apply: doc is missing path: \"%s\"", path) + return fmt.Errorf("add operation does not apply: doc is missing path: \"%s\": %w", path, ErrMissing) } err = con.add(key, op.value()) if err != nil { - return errors.Wrapf(err, "error in add for path: '%s'", path) + return fmt.Errorf("error in add for path: '%s': %w", path, err) } return nil @@ -545,18 +544,18 @@ func (p Patch) add(doc *container, op Operation) error { func (p Patch) remove(doc *container, op Operation) error { path, err := op.Path() if err != nil { - return errors.Wrapf(ErrMissing, "remove operation failed to decode path") + return fmt.Errorf("remove operation failed to decode path: %w", ErrMissing) } con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "remove operation does not apply: doc is missing path: \"%s\"", path) + return fmt.Errorf("remove operation does not apply: doc is missing path: \"%s\": %w", path, ErrMissing) } err = con.remove(key) if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) + return fmt.Errorf("error in remove for path: '%s': %w", path, err) } return nil @@ -565,7 +564,7 @@ func (p Patch) remove(doc *container, op Operation) error { func (p Patch) replace(doc *container, op Operation) error { path, err := op.Path() if err != nil { - return errors.Wrapf(err, "replace operation failed to decode path") + return fmt.Errorf("replace operation failed to decode path: %w", err) } if path == "" { @@ -574,7 +573,7 @@ func (p Patch) replace(doc *container, op Operation) error { if val.which == eRaw { if !val.tryDoc() { if !val.tryAry() { - return errors.Wrapf(err, "replace operation value must be object or array") + return fmt.Errorf("replace operation value must be object or array: %w", err) } } } @@ -585,7 +584,7 @@ func (p Patch) replace(doc *container, op Operation) error { case eDoc: *doc = &val.doc case eRaw: - return errors.Wrapf(err, "replace operation hit impossible case") + return fmt.Errorf("replace operation hit impossible case: %w", err) } return nil @@ -594,17 +593,17 @@ func (p Patch) replace(doc *container, op Operation) error { con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing path: %s", path) + return fmt.Errorf("replace operation does not apply: doc is missing path: %s: %w", path, ErrMissing) } _, ok := con.get(key) if ok != nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing key: %s", path) + return fmt.Errorf("replace operation does not apply: doc is missing key: %s: %w", path, ErrMissing) } err = con.set(key, op.value()) if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) + return fmt.Errorf("error in remove for path: '%s': %w", path, err) } return nil @@ -613,39 +612,39 @@ func (p Patch) replace(doc *container, op Operation) error { func (p Patch) move(doc *container, op Operation) error { from, err := op.From() if err != nil { - return errors.Wrapf(err, "move operation failed to decode from") + return fmt.Errorf("move operation failed to decode from: %w", err) } con, key := findObject(doc, from) if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing from path: %s", from) + return fmt.Errorf("move operation does not apply: doc is missing from path: %s: %w", from, ErrMissing) } val, err := con.get(key) if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) + return fmt.Errorf("error in move for path: '%s': %w", key, err) } err = con.remove(key) if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) + return fmt.Errorf("error in move for path: '%s': %w", key, err) } path, err := op.Path() if err != nil { - return errors.Wrapf(err, "move operation failed to decode path") + return fmt.Errorf("move operation failed to decode path: %w", err) } con, key = findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing destination path: %s", path) + return fmt.Errorf("move operation does not apply: doc is missing destination path: %s: %w", path, ErrMissing) } err = con.add(key, val) if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", path) + return fmt.Errorf("error in move for path: '%s': %w", path, err) } return nil @@ -654,7 +653,7 @@ func (p Patch) move(doc *container, op Operation) error { func (p Patch) test(doc *container, op Operation) error { path, err := op.Path() if err != nil { - return errors.Wrapf(err, "test operation failed to decode path") + return fmt.Errorf("test operation failed to decode path: %w", err) } if path == "" { @@ -673,67 +672,67 @@ func (p Patch) test(doc *container, op Operation) error { return nil } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "test operation does not apply: is missing path: %s", path) + return fmt.Errorf("test operation does not apply: is missing path: %s: %w", path, ErrMissing) } val, err := con.get(key) if err != nil { - return errors.Wrapf(err, "error in test for path: '%s'", path) + return fmt.Errorf("error in test for path: '%s': %w", path, err) } if val == nil { - if op.value().raw == nil { + if op.value() == nil || op.value().raw == nil { return nil } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } else if op.value() == nil { - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } if val.equal(op.value()) { return nil } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64) error { from, err := op.From() if err != nil { - return errors.Wrapf(err, "copy operation failed to decode from") + return fmt.Errorf("copy operation failed to decode from: %w", err) } con, key := findObject(doc, from) if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing from path: %s", from) + return fmt.Errorf("copy operation does not apply: doc is missing from path: %s: %w", from, ErrMissing) } val, err := con.get(key) if err != nil { - return errors.Wrapf(err, "error in copy for from: '%s'", from) + return fmt.Errorf("error in copy for from: '%s': %w", from, err) } path, err := op.Path() if err != nil { - return errors.Wrapf(ErrMissing, "copy operation failed to decode path") + return fmt.Errorf("copy operation failed to decode path: %w", ErrMissing) } con, key = findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing destination path: %s", path) + return fmt.Errorf("copy operation does not apply: doc is missing destination path: %s: %w", path, ErrMissing) } valCopy, sz, err := deepCopy(val) if err != nil { - return errors.Wrapf(err, "error while performing deep copy") + return fmt.Errorf("error while performing deep copy: %w", err) } (*accumulatedCopySize) += int64(sz) @@ -743,7 +742,7 @@ func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64) er err = con.add(key, valCopy) if err != nil { - return errors.Wrapf(err, "error while adding value during copy") + return fmt.Errorf("error while adding value during copy: %w", err) } return nil diff --git a/api/vendor/gopkg.in/yaml.v3/LICENSE b/api/vendor/gopkg.in/yaml.v3/LICENSE deleted file mode 100644 index 2683e4bb1f24..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ - -This project is covered by two different licenses: MIT and Apache. - -#### MIT License #### - -The following files were ported to Go from C files of libyaml, and thus -are still covered by their original MIT license, with the additional -copyright staring in 2011 when the project was ported over: - - apic.go emitterc.go parserc.go readerc.go scannerc.go - writerc.go yamlh.go yamlprivateh.go - -Copyright (c) 2006-2010 Kirill Simonov -Copyright (c) 2006-2011 Kirill Simonov - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -### Apache License ### - -All the remaining project files are covered by the Apache license: - -Copyright (c) 2011-2019 Canonical Ltd - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/api/vendor/gopkg.in/yaml.v3/NOTICE b/api/vendor/gopkg.in/yaml.v3/NOTICE deleted file mode 100644 index 866d74a7ad79..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2011-2016 Canonical Ltd. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/api/vendor/gopkg.in/yaml.v3/README.md b/api/vendor/gopkg.in/yaml.v3/README.md deleted file mode 100644 index 08eb1babddfa..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/README.md +++ /dev/null @@ -1,150 +0,0 @@ -# YAML support for the Go language - -Introduction ------------- - -The yaml package enables Go programs to comfortably encode and decode YAML -values. It was developed within [Canonical](https://www.canonical.com) as -part of the [juju](https://juju.ubuntu.com) project, and is based on a -pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) -C library to parse and generate YAML data quickly and reliably. - -Compatibility -------------- - -The yaml package supports most of YAML 1.2, but preserves some behavior -from 1.1 for backwards compatibility. - -Specifically, as of v3 of the yaml package: - - - YAML 1.1 bools (_yes/no, on/off_) are supported as long as they are being - decoded into a typed bool value. Otherwise they behave as a string. Booleans - in YAML 1.2 are _true/false_ only. - - Octals encode and decode as _0777_ per YAML 1.1, rather than _0o777_ - as specified in YAML 1.2, because most parsers still use the old format. - Octals in the _0o777_ format are supported though, so new files work. - - Does not support base-60 floats. These are gone from YAML 1.2, and were - actually never supported by this package as it's clearly a poor choice. - -and offers backwards -compatibility with YAML 1.1 in some cases. -1.2, including support for -anchors, tags, map merging, etc. Multi-document unmarshalling is not yet -implemented, and base-60 floats from YAML 1.1 are purposefully not -supported since they're a poor design and are gone in YAML 1.2. - -Installation and usage ----------------------- - -The import path for the package is *gopkg.in/yaml.v3*. - -To install it, run: - - go get gopkg.in/yaml.v3 - -API documentation ------------------ - -If opened in a browser, the import path itself leads to the API documentation: - - - [https://gopkg.in/yaml.v3](https://gopkg.in/yaml.v3) - -API stability -------------- - -The package API for yaml v3 will remain stable as described in [gopkg.in](https://gopkg.in). - - -License -------- - -The yaml package is licensed under the MIT and Apache License 2.0 licenses. -Please see the LICENSE file for details. - - -Example -------- - -```Go -package main - -import ( - "fmt" - "log" - - "gopkg.in/yaml.v3" -) - -var data = ` -a: Easy! -b: - c: 2 - d: [3, 4] -` - -// Note: struct fields must be public in order for unmarshal to -// correctly populate the data. -type T struct { - A string - B struct { - RenamedC int `yaml:"c"` - D []int `yaml:",flow"` - } -} - -func main() { - t := T{} - - err := yaml.Unmarshal([]byte(data), &t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t:\n%v\n\n", t) - - d, err := yaml.Marshal(&t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t dump:\n%s\n\n", string(d)) - - m := make(map[interface{}]interface{}) - - err = yaml.Unmarshal([]byte(data), &m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m:\n%v\n\n", m) - - d, err = yaml.Marshal(&m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m dump:\n%s\n\n", string(d)) -} -``` - -This example will generate the following output: - -``` ---- t: -{Easy! {2 [3 4]}} - ---- t dump: -a: Easy! -b: - c: 2 - d: [3, 4] - - ---- m: -map[a:Easy! b:map[c:2 d:[3 4]]] - ---- m dump: -a: Easy! -b: - c: 2 - d: - - 3 - - 4 -``` - diff --git a/api/vendor/gopkg.in/yaml.v3/apic.go b/api/vendor/gopkg.in/yaml.v3/apic.go deleted file mode 100644 index ae7d049f182a..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/apic.go +++ /dev/null @@ -1,747 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package yaml - -import ( - "io" -) - -func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { - //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) - - // Check if we can move the queue at the beginning of the buffer. - if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { - if parser.tokens_head != len(parser.tokens) { - copy(parser.tokens, parser.tokens[parser.tokens_head:]) - } - parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] - parser.tokens_head = 0 - } - parser.tokens = append(parser.tokens, *token) - if pos < 0 { - return - } - copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) - parser.tokens[parser.tokens_head+pos] = *token -} - -// Create a new parser object. -func yaml_parser_initialize(parser *yaml_parser_t) bool { - *parser = yaml_parser_t{ - raw_buffer: make([]byte, 0, input_raw_buffer_size), - buffer: make([]byte, 0, input_buffer_size), - } - return true -} - -// Destroy a parser object. -func yaml_parser_delete(parser *yaml_parser_t) { - *parser = yaml_parser_t{} -} - -// String read handler. -func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - if parser.input_pos == len(parser.input) { - return 0, io.EOF - } - n = copy(buffer, parser.input[parser.input_pos:]) - parser.input_pos += n - return n, nil -} - -// Reader read handler. -func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - return parser.input_reader.Read(buffer) -} - -// Set a string input. -func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_string_read_handler - parser.input = input - parser.input_pos = 0 -} - -// Set a file input. -func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_reader_read_handler - parser.input_reader = r -} - -// Set the source encoding. -func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { - if parser.encoding != yaml_ANY_ENCODING { - panic("must set the encoding only once") - } - parser.encoding = encoding -} - -// Create a new emitter object. -func yaml_emitter_initialize(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{ - buffer: make([]byte, output_buffer_size), - raw_buffer: make([]byte, 0, output_raw_buffer_size), - states: make([]yaml_emitter_state_t, 0, initial_stack_size), - events: make([]yaml_event_t, 0, initial_queue_size), - best_width: -1, - } -} - -// Destroy an emitter object. -func yaml_emitter_delete(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{} -} - -// String write handler. -func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - *emitter.output_buffer = append(*emitter.output_buffer, buffer...) - return nil -} - -// yaml_writer_write_handler uses emitter.output_writer to write the -// emitted text. -func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - _, err := emitter.output_writer.Write(buffer) - return err -} - -// Set a string output. -func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_string_write_handler - emitter.output_buffer = output_buffer -} - -// Set a file output. -func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_writer_write_handler - emitter.output_writer = w -} - -// Set the output encoding. -func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { - if emitter.encoding != yaml_ANY_ENCODING { - panic("must set the output encoding only once") - } - emitter.encoding = encoding -} - -// Set the canonical output style. -func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { - emitter.canonical = canonical -} - -// Set the indentation increment. -func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { - if indent < 2 || indent > 9 { - indent = 2 - } - emitter.best_indent = indent -} - -// Set the preferred line width. -func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { - if width < 0 { - width = -1 - } - emitter.best_width = width -} - -// Set if unescaped non-ASCII characters are allowed. -func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { - emitter.unicode = unicode -} - -// Set the preferred line break character. -func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { - emitter.line_break = line_break -} - -///* -// * Destroy a token object. -// */ -// -//YAML_DECLARE(void) -//yaml_token_delete(yaml_token_t *token) -//{ -// assert(token); // Non-NULL token object expected. -// -// switch (token.type) -// { -// case YAML_TAG_DIRECTIVE_TOKEN: -// yaml_free(token.data.tag_directive.handle); -// yaml_free(token.data.tag_directive.prefix); -// break; -// -// case YAML_ALIAS_TOKEN: -// yaml_free(token.data.alias.value); -// break; -// -// case YAML_ANCHOR_TOKEN: -// yaml_free(token.data.anchor.value); -// break; -// -// case YAML_TAG_TOKEN: -// yaml_free(token.data.tag.handle); -// yaml_free(token.data.tag.suffix); -// break; -// -// case YAML_SCALAR_TOKEN: -// yaml_free(token.data.scalar.value); -// break; -// -// default: -// break; -// } -// -// memset(token, 0, sizeof(yaml_token_t)); -//} -// -///* -// * Check if a string is a valid UTF-8 sequence. -// * -// * Check 'reader.c' for more details on UTF-8 encoding. -// */ -// -//static int -//yaml_check_utf8(yaml_char_t *start, size_t length) -//{ -// yaml_char_t *end = start+length; -// yaml_char_t *pointer = start; -// -// while (pointer < end) { -// unsigned char octet; -// unsigned int width; -// unsigned int value; -// size_t k; -// -// octet = pointer[0]; -// width = (octet & 0x80) == 0x00 ? 1 : -// (octet & 0xE0) == 0xC0 ? 2 : -// (octet & 0xF0) == 0xE0 ? 3 : -// (octet & 0xF8) == 0xF0 ? 4 : 0; -// value = (octet & 0x80) == 0x00 ? octet & 0x7F : -// (octet & 0xE0) == 0xC0 ? octet & 0x1F : -// (octet & 0xF0) == 0xE0 ? octet & 0x0F : -// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; -// if (!width) return 0; -// if (pointer+width > end) return 0; -// for (k = 1; k < width; k ++) { -// octet = pointer[k]; -// if ((octet & 0xC0) != 0x80) return 0; -// value = (value << 6) + (octet & 0x3F); -// } -// if (!((width == 1) || -// (width == 2 && value >= 0x80) || -// (width == 3 && value >= 0x800) || -// (width == 4 && value >= 0x10000))) return 0; -// -// pointer += width; -// } -// -// return 1; -//} -// - -// Create STREAM-START. -func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - encoding: encoding, - } -} - -// Create STREAM-END. -func yaml_stream_end_event_initialize(event *yaml_event_t) { - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - } -} - -// Create DOCUMENT-START. -func yaml_document_start_event_initialize( - event *yaml_event_t, - version_directive *yaml_version_directive_t, - tag_directives []yaml_tag_directive_t, - implicit bool, -) { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: implicit, - } -} - -// Create DOCUMENT-END. -func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - implicit: implicit, - } -} - -// Create ALIAS. -func yaml_alias_event_initialize(event *yaml_event_t, anchor []byte) bool { - *event = yaml_event_t{ - typ: yaml_ALIAS_EVENT, - anchor: anchor, - } - return true -} - -// Create SCALAR. -func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - anchor: anchor, - tag: tag, - value: value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-START. -func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-END. -func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - } - return true -} - -// Create MAPPING-START. -func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } -} - -// Create MAPPING-END. -func yaml_mapping_end_event_initialize(event *yaml_event_t) { - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - } -} - -// Destroy an event object. -func yaml_event_delete(event *yaml_event_t) { - *event = yaml_event_t{} -} - -///* -// * Create a document object. -// */ -// -//YAML_DECLARE(int) -//yaml_document_initialize(document *yaml_document_t, -// version_directive *yaml_version_directive_t, -// tag_directives_start *yaml_tag_directive_t, -// tag_directives_end *yaml_tag_directive_t, -// start_implicit int, end_implicit int) -//{ -// struct { -// error yaml_error_type_t -// } context -// struct { -// start *yaml_node_t -// end *yaml_node_t -// top *yaml_node_t -// } nodes = { NULL, NULL, NULL } -// version_directive_copy *yaml_version_directive_t = NULL -// struct { -// start *yaml_tag_directive_t -// end *yaml_tag_directive_t -// top *yaml_tag_directive_t -// } tag_directives_copy = { NULL, NULL, NULL } -// value yaml_tag_directive_t = { NULL, NULL } -// mark yaml_mark_t = { 0, 0, 0 } -// -// assert(document) // Non-NULL document object is expected. -// assert((tag_directives_start && tag_directives_end) || -// (tag_directives_start == tag_directives_end)) -// // Valid tag directives are expected. -// -// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error -// -// if (version_directive) { -// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) -// if (!version_directive_copy) goto error -// version_directive_copy.major = version_directive.major -// version_directive_copy.minor = version_directive.minor -// } -// -// if (tag_directives_start != tag_directives_end) { -// tag_directive *yaml_tag_directive_t -// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) -// goto error -// for (tag_directive = tag_directives_start -// tag_directive != tag_directives_end; tag_directive ++) { -// assert(tag_directive.handle) -// assert(tag_directive.prefix) -// if (!yaml_check_utf8(tag_directive.handle, -// strlen((char *)tag_directive.handle))) -// goto error -// if (!yaml_check_utf8(tag_directive.prefix, -// strlen((char *)tag_directive.prefix))) -// goto error -// value.handle = yaml_strdup(tag_directive.handle) -// value.prefix = yaml_strdup(tag_directive.prefix) -// if (!value.handle || !value.prefix) goto error -// if (!PUSH(&context, tag_directives_copy, value)) -// goto error -// value.handle = NULL -// value.prefix = NULL -// } -// } -// -// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, -// tag_directives_copy.start, tag_directives_copy.top, -// start_implicit, end_implicit, mark, mark) -// -// return 1 -// -//error: -// STACK_DEL(&context, nodes) -// yaml_free(version_directive_copy) -// while (!STACK_EMPTY(&context, tag_directives_copy)) { -// value yaml_tag_directive_t = POP(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// } -// STACK_DEL(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// -// return 0 -//} -// -///* -// * Destroy a document object. -// */ -// -//YAML_DECLARE(void) -//yaml_document_delete(document *yaml_document_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// tag_directive *yaml_tag_directive_t -// -// context.error = YAML_NO_ERROR // Eliminate a compiler warning. -// -// assert(document) // Non-NULL document object is expected. -// -// while (!STACK_EMPTY(&context, document.nodes)) { -// node yaml_node_t = POP(&context, document.nodes) -// yaml_free(node.tag) -// switch (node.type) { -// case YAML_SCALAR_NODE: -// yaml_free(node.data.scalar.value) -// break -// case YAML_SEQUENCE_NODE: -// STACK_DEL(&context, node.data.sequence.items) -// break -// case YAML_MAPPING_NODE: -// STACK_DEL(&context, node.data.mapping.pairs) -// break -// default: -// assert(0) // Should not happen. -// } -// } -// STACK_DEL(&context, document.nodes) -// -// yaml_free(document.version_directive) -// for (tag_directive = document.tag_directives.start -// tag_directive != document.tag_directives.end -// tag_directive++) { -// yaml_free(tag_directive.handle) -// yaml_free(tag_directive.prefix) -// } -// yaml_free(document.tag_directives.start) -// -// memset(document, 0, sizeof(yaml_document_t)) -//} -// -///** -// * Get a document node. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_node(document *yaml_document_t, index int) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (index > 0 && document.nodes.start + index <= document.nodes.top) { -// return document.nodes.start + index - 1 -// } -// return NULL -//} -// -///** -// * Get the root object. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_root_node(document *yaml_document_t) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (document.nodes.top != document.nodes.start) { -// return document.nodes.start -// } -// return NULL -//} -// -///* -// * Add a scalar node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_scalar(document *yaml_document_t, -// tag *yaml_char_t, value *yaml_char_t, length int, -// style yaml_scalar_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// value_copy *yaml_char_t = NULL -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// assert(value) // Non-NULL value is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (length < 0) { -// length = strlen((char *)value) -// } -// -// if (!yaml_check_utf8(value, length)) goto error -// value_copy = yaml_malloc(length+1) -// if (!value_copy) goto error -// memcpy(value_copy, value, length) -// value_copy[length] = '\0' -// -// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// yaml_free(tag_copy) -// yaml_free(value_copy) -// -// return 0 -//} -// -///* -// * Add a sequence node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_sequence(document *yaml_document_t, -// tag *yaml_char_t, style yaml_sequence_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_item_t -// end *yaml_node_item_t -// top *yaml_node_item_t -// } items = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error -// -// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, items) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Add a mapping node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_mapping(document *yaml_document_t, -// tag *yaml_char_t, style yaml_mapping_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_pair_t -// end *yaml_node_pair_t -// top *yaml_node_pair_t -// } pairs = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error -// -// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, pairs) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Append an item to a sequence node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_sequence_item(document *yaml_document_t, -// sequence int, item int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// assert(document) // Non-NULL document is required. -// assert(sequence > 0 -// && document.nodes.start + sequence <= document.nodes.top) -// // Valid sequence id is required. -// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) -// // A sequence node is required. -// assert(item > 0 && document.nodes.start + item <= document.nodes.top) -// // Valid item id is required. -// -// if (!PUSH(&context, -// document.nodes.start[sequence-1].data.sequence.items, item)) -// return 0 -// -// return 1 -//} -// -///* -// * Append a pair of a key and a value to a mapping node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_mapping_pair(document *yaml_document_t, -// mapping int, key int, value int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// pair yaml_node_pair_t -// -// assert(document) // Non-NULL document is required. -// assert(mapping > 0 -// && document.nodes.start + mapping <= document.nodes.top) -// // Valid mapping id is required. -// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) -// // A mapping node is required. -// assert(key > 0 && document.nodes.start + key <= document.nodes.top) -// // Valid key id is required. -// assert(value > 0 && document.nodes.start + value <= document.nodes.top) -// // Valid value id is required. -// -// pair.key = key -// pair.value = value -// -// if (!PUSH(&context, -// document.nodes.start[mapping-1].data.mapping.pairs, pair)) -// return 0 -// -// return 1 -//} -// -// diff --git a/api/vendor/gopkg.in/yaml.v3/decode.go b/api/vendor/gopkg.in/yaml.v3/decode.go deleted file mode 100644 index 0173b6982e84..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/decode.go +++ /dev/null @@ -1,1000 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package yaml - -import ( - "encoding" - "encoding/base64" - "fmt" - "io" - "math" - "reflect" - "strconv" - "time" -) - -// ---------------------------------------------------------------------------- -// Parser, produces a node tree out of a libyaml event stream. - -type parser struct { - parser yaml_parser_t - event yaml_event_t - doc *Node - anchors map[string]*Node - doneInit bool - textless bool -} - -func newParser(b []byte) *parser { - p := parser{} - if !yaml_parser_initialize(&p.parser) { - panic("failed to initialize YAML emitter") - } - if len(b) == 0 { - b = []byte{'\n'} - } - yaml_parser_set_input_string(&p.parser, b) - return &p -} - -func newParserFromReader(r io.Reader) *parser { - p := parser{} - if !yaml_parser_initialize(&p.parser) { - panic("failed to initialize YAML emitter") - } - yaml_parser_set_input_reader(&p.parser, r) - return &p -} - -func (p *parser) init() { - if p.doneInit { - return - } - p.anchors = make(map[string]*Node) - p.expect(yaml_STREAM_START_EVENT) - p.doneInit = true -} - -func (p *parser) destroy() { - if p.event.typ != yaml_NO_EVENT { - yaml_event_delete(&p.event) - } - yaml_parser_delete(&p.parser) -} - -// expect consumes an event from the event stream and -// checks that it's of the expected type. -func (p *parser) expect(e yaml_event_type_t) { - if p.event.typ == yaml_NO_EVENT { - if !yaml_parser_parse(&p.parser, &p.event) { - p.fail() - } - } - if p.event.typ == yaml_STREAM_END_EVENT { - failf("attempted to go past the end of stream; corrupted value?") - } - if p.event.typ != e { - p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) - p.fail() - } - yaml_event_delete(&p.event) - p.event.typ = yaml_NO_EVENT -} - -// peek peeks at the next event in the event stream, -// puts the results into p.event and returns the event type. -func (p *parser) peek() yaml_event_type_t { - if p.event.typ != yaml_NO_EVENT { - return p.event.typ - } - // It's curious choice from the underlying API to generally return a - // positive result on success, but on this case return true in an error - // scenario. This was the source of bugs in the past (issue #666). - if !yaml_parser_parse(&p.parser, &p.event) || p.parser.error != yaml_NO_ERROR { - p.fail() - } - return p.event.typ -} - -func (p *parser) fail() { - var where string - var line int - if p.parser.context_mark.line != 0 { - line = p.parser.context_mark.line - // Scanner errors don't iterate line before returning error - if p.parser.error == yaml_SCANNER_ERROR { - line++ - } - } else if p.parser.problem_mark.line != 0 { - line = p.parser.problem_mark.line - // Scanner errors don't iterate line before returning error - if p.parser.error == yaml_SCANNER_ERROR { - line++ - } - } - if line != 0 { - where = "line " + strconv.Itoa(line) + ": " - } - var msg string - if len(p.parser.problem) > 0 { - msg = p.parser.problem - } else { - msg = "unknown problem parsing YAML content" - } - failf("%s%s", where, msg) -} - -func (p *parser) anchor(n *Node, anchor []byte) { - if anchor != nil { - n.Anchor = string(anchor) - p.anchors[n.Anchor] = n - } -} - -func (p *parser) parse() *Node { - p.init() - switch p.peek() { - case yaml_SCALAR_EVENT: - return p.scalar() - case yaml_ALIAS_EVENT: - return p.alias() - case yaml_MAPPING_START_EVENT: - return p.mapping() - case yaml_SEQUENCE_START_EVENT: - return p.sequence() - case yaml_DOCUMENT_START_EVENT: - return p.document() - case yaml_STREAM_END_EVENT: - // Happens when attempting to decode an empty buffer. - return nil - case yaml_TAIL_COMMENT_EVENT: - panic("internal error: unexpected tail comment event (please report)") - default: - panic("internal error: attempted to parse unknown event (please report): " + p.event.typ.String()) - } -} - -func (p *parser) node(kind Kind, defaultTag, tag, value string) *Node { - var style Style - if tag != "" && tag != "!" { - tag = shortTag(tag) - style = TaggedStyle - } else if defaultTag != "" { - tag = defaultTag - } else if kind == ScalarNode { - tag, _ = resolve("", value) - } - n := &Node{ - Kind: kind, - Tag: tag, - Value: value, - Style: style, - } - if !p.textless { - n.Line = p.event.start_mark.line + 1 - n.Column = p.event.start_mark.column + 1 - n.HeadComment = string(p.event.head_comment) - n.LineComment = string(p.event.line_comment) - n.FootComment = string(p.event.foot_comment) - } - return n -} - -func (p *parser) parseChild(parent *Node) *Node { - child := p.parse() - parent.Content = append(parent.Content, child) - return child -} - -func (p *parser) document() *Node { - n := p.node(DocumentNode, "", "", "") - p.doc = n - p.expect(yaml_DOCUMENT_START_EVENT) - p.parseChild(n) - if p.peek() == yaml_DOCUMENT_END_EVENT { - n.FootComment = string(p.event.foot_comment) - } - p.expect(yaml_DOCUMENT_END_EVENT) - return n -} - -func (p *parser) alias() *Node { - n := p.node(AliasNode, "", "", string(p.event.anchor)) - n.Alias = p.anchors[n.Value] - if n.Alias == nil { - failf("unknown anchor '%s' referenced", n.Value) - } - p.expect(yaml_ALIAS_EVENT) - return n -} - -func (p *parser) scalar() *Node { - var parsedStyle = p.event.scalar_style() - var nodeStyle Style - switch { - case parsedStyle&yaml_DOUBLE_QUOTED_SCALAR_STYLE != 0: - nodeStyle = DoubleQuotedStyle - case parsedStyle&yaml_SINGLE_QUOTED_SCALAR_STYLE != 0: - nodeStyle = SingleQuotedStyle - case parsedStyle&yaml_LITERAL_SCALAR_STYLE != 0: - nodeStyle = LiteralStyle - case parsedStyle&yaml_FOLDED_SCALAR_STYLE != 0: - nodeStyle = FoldedStyle - } - var nodeValue = string(p.event.value) - var nodeTag = string(p.event.tag) - var defaultTag string - if nodeStyle == 0 { - if nodeValue == "<<" { - defaultTag = mergeTag - } - } else { - defaultTag = strTag - } - n := p.node(ScalarNode, defaultTag, nodeTag, nodeValue) - n.Style |= nodeStyle - p.anchor(n, p.event.anchor) - p.expect(yaml_SCALAR_EVENT) - return n -} - -func (p *parser) sequence() *Node { - n := p.node(SequenceNode, seqTag, string(p.event.tag), "") - if p.event.sequence_style()&yaml_FLOW_SEQUENCE_STYLE != 0 { - n.Style |= FlowStyle - } - p.anchor(n, p.event.anchor) - p.expect(yaml_SEQUENCE_START_EVENT) - for p.peek() != yaml_SEQUENCE_END_EVENT { - p.parseChild(n) - } - n.LineComment = string(p.event.line_comment) - n.FootComment = string(p.event.foot_comment) - p.expect(yaml_SEQUENCE_END_EVENT) - return n -} - -func (p *parser) mapping() *Node { - n := p.node(MappingNode, mapTag, string(p.event.tag), "") - block := true - if p.event.mapping_style()&yaml_FLOW_MAPPING_STYLE != 0 { - block = false - n.Style |= FlowStyle - } - p.anchor(n, p.event.anchor) - p.expect(yaml_MAPPING_START_EVENT) - for p.peek() != yaml_MAPPING_END_EVENT { - k := p.parseChild(n) - if block && k.FootComment != "" { - // Must be a foot comment for the prior value when being dedented. - if len(n.Content) > 2 { - n.Content[len(n.Content)-3].FootComment = k.FootComment - k.FootComment = "" - } - } - v := p.parseChild(n) - if k.FootComment == "" && v.FootComment != "" { - k.FootComment = v.FootComment - v.FootComment = "" - } - if p.peek() == yaml_TAIL_COMMENT_EVENT { - if k.FootComment == "" { - k.FootComment = string(p.event.foot_comment) - } - p.expect(yaml_TAIL_COMMENT_EVENT) - } - } - n.LineComment = string(p.event.line_comment) - n.FootComment = string(p.event.foot_comment) - if n.Style&FlowStyle == 0 && n.FootComment != "" && len(n.Content) > 1 { - n.Content[len(n.Content)-2].FootComment = n.FootComment - n.FootComment = "" - } - p.expect(yaml_MAPPING_END_EVENT) - return n -} - -// ---------------------------------------------------------------------------- -// Decoder, unmarshals a node into a provided value. - -type decoder struct { - doc *Node - aliases map[*Node]bool - terrors []string - - stringMapType reflect.Type - generalMapType reflect.Type - - knownFields bool - uniqueKeys bool - decodeCount int - aliasCount int - aliasDepth int - - mergedFields map[interface{}]bool -} - -var ( - nodeType = reflect.TypeOf(Node{}) - durationType = reflect.TypeOf(time.Duration(0)) - stringMapType = reflect.TypeOf(map[string]interface{}{}) - generalMapType = reflect.TypeOf(map[interface{}]interface{}{}) - ifaceType = generalMapType.Elem() - timeType = reflect.TypeOf(time.Time{}) - ptrTimeType = reflect.TypeOf(&time.Time{}) -) - -func newDecoder() *decoder { - d := &decoder{ - stringMapType: stringMapType, - generalMapType: generalMapType, - uniqueKeys: true, - } - d.aliases = make(map[*Node]bool) - return d -} - -func (d *decoder) terror(n *Node, tag string, out reflect.Value) { - if n.Tag != "" { - tag = n.Tag - } - value := n.Value - if tag != seqTag && tag != mapTag { - if len(value) > 10 { - value = " `" + value[:7] + "...`" - } else { - value = " `" + value + "`" - } - } - d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.Line, shortTag(tag), value, out.Type())) -} - -func (d *decoder) callUnmarshaler(n *Node, u Unmarshaler) (good bool) { - err := u.UnmarshalYAML(n) - if e, ok := err.(*TypeError); ok { - d.terrors = append(d.terrors, e.Errors...) - return false - } - if err != nil { - fail(err) - } - return true -} - -func (d *decoder) callObsoleteUnmarshaler(n *Node, u obsoleteUnmarshaler) (good bool) { - terrlen := len(d.terrors) - err := u.UnmarshalYAML(func(v interface{}) (err error) { - defer handleErr(&err) - d.unmarshal(n, reflect.ValueOf(v)) - if len(d.terrors) > terrlen { - issues := d.terrors[terrlen:] - d.terrors = d.terrors[:terrlen] - return &TypeError{issues} - } - return nil - }) - if e, ok := err.(*TypeError); ok { - d.terrors = append(d.terrors, e.Errors...) - return false - } - if err != nil { - fail(err) - } - return true -} - -// d.prepare initializes and dereferences pointers and calls UnmarshalYAML -// if a value is found to implement it. -// It returns the initialized and dereferenced out value, whether -// unmarshalling was already done by UnmarshalYAML, and if so whether -// its types unmarshalled appropriately. -// -// If n holds a null value, prepare returns before doing anything. -func (d *decoder) prepare(n *Node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { - if n.ShortTag() == nullTag { - return out, false, false - } - again := true - for again { - again = false - if out.Kind() == reflect.Ptr { - if out.IsNil() { - out.Set(reflect.New(out.Type().Elem())) - } - out = out.Elem() - again = true - } - if out.CanAddr() { - outi := out.Addr().Interface() - if u, ok := outi.(Unmarshaler); ok { - good = d.callUnmarshaler(n, u) - return out, true, good - } - if u, ok := outi.(obsoleteUnmarshaler); ok { - good = d.callObsoleteUnmarshaler(n, u) - return out, true, good - } - } - } - return out, false, false -} - -func (d *decoder) fieldByIndex(n *Node, v reflect.Value, index []int) (field reflect.Value) { - if n.ShortTag() == nullTag { - return reflect.Value{} - } - for _, num := range index { - for { - if v.Kind() == reflect.Ptr { - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - continue - } - break - } - v = v.Field(num) - } - return v -} - -const ( - // 400,000 decode operations is ~500kb of dense object declarations, or - // ~5kb of dense object declarations with 10000% alias expansion - alias_ratio_range_low = 400000 - - // 4,000,000 decode operations is ~5MB of dense object declarations, or - // ~4.5MB of dense object declarations with 10% alias expansion - alias_ratio_range_high = 4000000 - - // alias_ratio_range is the range over which we scale allowed alias ratios - alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) -) - -func allowedAliasRatio(decodeCount int) float64 { - switch { - case decodeCount <= alias_ratio_range_low: - // allow 99% to come from alias expansion for small-to-medium documents - return 0.99 - case decodeCount >= alias_ratio_range_high: - // allow 10% to come from alias expansion for very large documents - return 0.10 - default: - // scale smoothly from 99% down to 10% over the range. - // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. - // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). - return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) - } -} - -func (d *decoder) unmarshal(n *Node, out reflect.Value) (good bool) { - d.decodeCount++ - if d.aliasDepth > 0 { - d.aliasCount++ - } - if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { - failf("document contains excessive aliasing") - } - if out.Type() == nodeType { - out.Set(reflect.ValueOf(n).Elem()) - return true - } - switch n.Kind { - case DocumentNode: - return d.document(n, out) - case AliasNode: - return d.alias(n, out) - } - out, unmarshaled, good := d.prepare(n, out) - if unmarshaled { - return good - } - switch n.Kind { - case ScalarNode: - good = d.scalar(n, out) - case MappingNode: - good = d.mapping(n, out) - case SequenceNode: - good = d.sequence(n, out) - case 0: - if n.IsZero() { - return d.null(out) - } - fallthrough - default: - failf("cannot decode node with unknown kind %d", n.Kind) - } - return good -} - -func (d *decoder) document(n *Node, out reflect.Value) (good bool) { - if len(n.Content) == 1 { - d.doc = n - d.unmarshal(n.Content[0], out) - return true - } - return false -} - -func (d *decoder) alias(n *Node, out reflect.Value) (good bool) { - if d.aliases[n] { - // TODO this could actually be allowed in some circumstances. - failf("anchor '%s' value contains itself", n.Value) - } - d.aliases[n] = true - d.aliasDepth++ - good = d.unmarshal(n.Alias, out) - d.aliasDepth-- - delete(d.aliases, n) - return good -} - -var zeroValue reflect.Value - -func resetMap(out reflect.Value) { - for _, k := range out.MapKeys() { - out.SetMapIndex(k, zeroValue) - } -} - -func (d *decoder) null(out reflect.Value) bool { - if out.CanAddr() { - switch out.Kind() { - case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: - out.Set(reflect.Zero(out.Type())) - return true - } - } - return false -} - -func (d *decoder) scalar(n *Node, out reflect.Value) bool { - var tag string - var resolved interface{} - if n.indicatedString() { - tag = strTag - resolved = n.Value - } else { - tag, resolved = resolve(n.Tag, n.Value) - if tag == binaryTag { - data, err := base64.StdEncoding.DecodeString(resolved.(string)) - if err != nil { - failf("!!binary value contains invalid base64 data") - } - resolved = string(data) - } - } - if resolved == nil { - return d.null(out) - } - if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { - // We've resolved to exactly the type we want, so use that. - out.Set(resolvedv) - return true - } - // Perhaps we can use the value as a TextUnmarshaler to - // set its value. - if out.CanAddr() { - u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) - if ok { - var text []byte - if tag == binaryTag { - text = []byte(resolved.(string)) - } else { - // We let any value be unmarshaled into TextUnmarshaler. - // That might be more lax than we'd like, but the - // TextUnmarshaler itself should bowl out any dubious values. - text = []byte(n.Value) - } - err := u.UnmarshalText(text) - if err != nil { - fail(err) - } - return true - } - } - switch out.Kind() { - case reflect.String: - if tag == binaryTag { - out.SetString(resolved.(string)) - return true - } - out.SetString(n.Value) - return true - case reflect.Interface: - out.Set(reflect.ValueOf(resolved)) - return true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - // This used to work in v2, but it's very unfriendly. - isDuration := out.Type() == durationType - - switch resolved := resolved.(type) { - case int: - if !isDuration && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case int64: - if !isDuration && !out.OverflowInt(resolved) { - out.SetInt(resolved) - return true - } - case uint64: - if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case float64: - if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case string: - if out.Type() == durationType { - d, err := time.ParseDuration(resolved) - if err == nil { - out.SetInt(int64(d)) - return true - } - } - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - switch resolved := resolved.(type) { - case int: - if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case int64: - if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case uint64: - if !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case float64: - if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - } - case reflect.Bool: - switch resolved := resolved.(type) { - case bool: - out.SetBool(resolved) - return true - case string: - // This offers some compatibility with the 1.1 spec (https://yaml.org/type/bool.html). - // It only works if explicitly attempting to unmarshal into a typed bool value. - switch resolved { - case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON": - out.SetBool(true) - return true - case "n", "N", "no", "No", "NO", "off", "Off", "OFF": - out.SetBool(false) - return true - } - } - case reflect.Float32, reflect.Float64: - switch resolved := resolved.(type) { - case int: - out.SetFloat(float64(resolved)) - return true - case int64: - out.SetFloat(float64(resolved)) - return true - case uint64: - out.SetFloat(float64(resolved)) - return true - case float64: - out.SetFloat(resolved) - return true - } - case reflect.Struct: - if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { - out.Set(resolvedv) - return true - } - case reflect.Ptr: - panic("yaml internal error: please report the issue") - } - d.terror(n, tag, out) - return false -} - -func settableValueOf(i interface{}) reflect.Value { - v := reflect.ValueOf(i) - sv := reflect.New(v.Type()).Elem() - sv.Set(v) - return sv -} - -func (d *decoder) sequence(n *Node, out reflect.Value) (good bool) { - l := len(n.Content) - - var iface reflect.Value - switch out.Kind() { - case reflect.Slice: - out.Set(reflect.MakeSlice(out.Type(), l, l)) - case reflect.Array: - if l != out.Len() { - failf("invalid array: want %d elements but got %d", out.Len(), l) - } - case reflect.Interface: - // No type hints. Will have to use a generic sequence. - iface = out - out = settableValueOf(make([]interface{}, l)) - default: - d.terror(n, seqTag, out) - return false - } - et := out.Type().Elem() - - j := 0 - for i := 0; i < l; i++ { - e := reflect.New(et).Elem() - if ok := d.unmarshal(n.Content[i], e); ok { - out.Index(j).Set(e) - j++ - } - } - if out.Kind() != reflect.Array { - out.Set(out.Slice(0, j)) - } - if iface.IsValid() { - iface.Set(out) - } - return true -} - -func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { - l := len(n.Content) - if d.uniqueKeys { - nerrs := len(d.terrors) - for i := 0; i < l; i += 2 { - ni := n.Content[i] - for j := i + 2; j < l; j += 2 { - nj := n.Content[j] - if ni.Kind == nj.Kind && ni.Value == nj.Value { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: mapping key %#v already defined at line %d", nj.Line, nj.Value, ni.Line)) - } - } - } - if len(d.terrors) > nerrs { - return false - } - } - switch out.Kind() { - case reflect.Struct: - return d.mappingStruct(n, out) - case reflect.Map: - // okay - case reflect.Interface: - iface := out - if isStringMap(n) { - out = reflect.MakeMap(d.stringMapType) - } else { - out = reflect.MakeMap(d.generalMapType) - } - iface.Set(out) - default: - d.terror(n, mapTag, out) - return false - } - - outt := out.Type() - kt := outt.Key() - et := outt.Elem() - - stringMapType := d.stringMapType - generalMapType := d.generalMapType - if outt.Elem() == ifaceType { - if outt.Key().Kind() == reflect.String { - d.stringMapType = outt - } else if outt.Key() == ifaceType { - d.generalMapType = outt - } - } - - mergedFields := d.mergedFields - d.mergedFields = nil - - var mergeNode *Node - - mapIsNew := false - if out.IsNil() { - out.Set(reflect.MakeMap(outt)) - mapIsNew = true - } - for i := 0; i < l; i += 2 { - if isMerge(n.Content[i]) { - mergeNode = n.Content[i+1] - continue - } - k := reflect.New(kt).Elem() - if d.unmarshal(n.Content[i], k) { - if mergedFields != nil { - ki := k.Interface() - if mergedFields[ki] { - continue - } - mergedFields[ki] = true - } - kkind := k.Kind() - if kkind == reflect.Interface { - kkind = k.Elem().Kind() - } - if kkind == reflect.Map || kkind == reflect.Slice { - failf("invalid map key: %#v", k.Interface()) - } - e := reflect.New(et).Elem() - if d.unmarshal(n.Content[i+1], e) || n.Content[i+1].ShortTag() == nullTag && (mapIsNew || !out.MapIndex(k).IsValid()) { - out.SetMapIndex(k, e) - } - } - } - - d.mergedFields = mergedFields - if mergeNode != nil { - d.merge(n, mergeNode, out) - } - - d.stringMapType = stringMapType - d.generalMapType = generalMapType - return true -} - -func isStringMap(n *Node) bool { - if n.Kind != MappingNode { - return false - } - l := len(n.Content) - for i := 0; i < l; i += 2 { - shortTag := n.Content[i].ShortTag() - if shortTag != strTag && shortTag != mergeTag { - return false - } - } - return true -} - -func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { - sinfo, err := getStructInfo(out.Type()) - if err != nil { - panic(err) - } - - var inlineMap reflect.Value - var elemType reflect.Type - if sinfo.InlineMap != -1 { - inlineMap = out.Field(sinfo.InlineMap) - elemType = inlineMap.Type().Elem() - } - - for _, index := range sinfo.InlineUnmarshalers { - field := d.fieldByIndex(n, out, index) - d.prepare(n, field) - } - - mergedFields := d.mergedFields - d.mergedFields = nil - var mergeNode *Node - var doneFields []bool - if d.uniqueKeys { - doneFields = make([]bool, len(sinfo.FieldsList)) - } - name := settableValueOf("") - l := len(n.Content) - for i := 0; i < l; i += 2 { - ni := n.Content[i] - if isMerge(ni) { - mergeNode = n.Content[i+1] - continue - } - if !d.unmarshal(ni, name) { - continue - } - sname := name.String() - if mergedFields != nil { - if mergedFields[sname] { - continue - } - mergedFields[sname] = true - } - if info, ok := sinfo.FieldsMap[sname]; ok { - if d.uniqueKeys { - if doneFields[info.Id] { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.Line, name.String(), out.Type())) - continue - } - doneFields[info.Id] = true - } - var field reflect.Value - if info.Inline == nil { - field = out.Field(info.Num) - } else { - field = d.fieldByIndex(n, out, info.Inline) - } - d.unmarshal(n.Content[i+1], field) - } else if sinfo.InlineMap != -1 { - if inlineMap.IsNil() { - inlineMap.Set(reflect.MakeMap(inlineMap.Type())) - } - value := reflect.New(elemType).Elem() - d.unmarshal(n.Content[i+1], value) - inlineMap.SetMapIndex(name, value) - } else if d.knownFields { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.Line, name.String(), out.Type())) - } - } - - d.mergedFields = mergedFields - if mergeNode != nil { - d.merge(n, mergeNode, out) - } - return true -} - -func failWantMap() { - failf("map merge requires map or sequence of maps as the value") -} - -func (d *decoder) merge(parent *Node, merge *Node, out reflect.Value) { - mergedFields := d.mergedFields - if mergedFields == nil { - d.mergedFields = make(map[interface{}]bool) - for i := 0; i < len(parent.Content); i += 2 { - k := reflect.New(ifaceType).Elem() - if d.unmarshal(parent.Content[i], k) { - d.mergedFields[k.Interface()] = true - } - } - } - - switch merge.Kind { - case MappingNode: - d.unmarshal(merge, out) - case AliasNode: - if merge.Alias != nil && merge.Alias.Kind != MappingNode { - failWantMap() - } - d.unmarshal(merge, out) - case SequenceNode: - for i := 0; i < len(merge.Content); i++ { - ni := merge.Content[i] - if ni.Kind == AliasNode { - if ni.Alias != nil && ni.Alias.Kind != MappingNode { - failWantMap() - } - } else if ni.Kind != MappingNode { - failWantMap() - } - d.unmarshal(ni, out) - } - default: - failWantMap() - } - - d.mergedFields = mergedFields -} - -func isMerge(n *Node) bool { - return n.Kind == ScalarNode && n.Value == "<<" && (n.Tag == "" || n.Tag == "!" || shortTag(n.Tag) == mergeTag) -} diff --git a/api/vendor/gopkg.in/yaml.v3/emitterc.go b/api/vendor/gopkg.in/yaml.v3/emitterc.go deleted file mode 100644 index 0f47c9ca8add..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/emitterc.go +++ /dev/null @@ -1,2020 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package yaml - -import ( - "bytes" - "fmt" -) - -// Flush the buffer if needed. -func flush(emitter *yaml_emitter_t) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) { - return yaml_emitter_flush(emitter) - } - return true -} - -// Put a character to the output buffer. -func put(emitter *yaml_emitter_t, value byte) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - emitter.buffer[emitter.buffer_pos] = value - emitter.buffer_pos++ - emitter.column++ - return true -} - -// Put a line break to the output buffer. -func put_break(emitter *yaml_emitter_t) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - switch emitter.line_break { - case yaml_CR_BREAK: - emitter.buffer[emitter.buffer_pos] = '\r' - emitter.buffer_pos += 1 - case yaml_LN_BREAK: - emitter.buffer[emitter.buffer_pos] = '\n' - emitter.buffer_pos += 1 - case yaml_CRLN_BREAK: - emitter.buffer[emitter.buffer_pos+0] = '\r' - emitter.buffer[emitter.buffer_pos+1] = '\n' - emitter.buffer_pos += 2 - default: - panic("unknown line break setting") - } - if emitter.column == 0 { - emitter.space_above = true - } - emitter.column = 0 - emitter.line++ - // [Go] Do this here and below and drop from everywhere else (see commented lines). - emitter.indention = true - return true -} - -// Copy a character from a string into buffer. -func write(emitter *yaml_emitter_t, s []byte, i *int) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - p := emitter.buffer_pos - w := width(s[*i]) - switch w { - case 4: - emitter.buffer[p+3] = s[*i+3] - fallthrough - case 3: - emitter.buffer[p+2] = s[*i+2] - fallthrough - case 2: - emitter.buffer[p+1] = s[*i+1] - fallthrough - case 1: - emitter.buffer[p+0] = s[*i+0] - default: - panic("unknown character width") - } - emitter.column++ - emitter.buffer_pos += w - *i += w - return true -} - -// Write a whole string into buffer. -func write_all(emitter *yaml_emitter_t, s []byte) bool { - for i := 0; i < len(s); { - if !write(emitter, s, &i) { - return false - } - } - return true -} - -// Copy a line break character from a string into buffer. -func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { - if s[*i] == '\n' { - if !put_break(emitter) { - return false - } - *i++ - } else { - if !write(emitter, s, i) { - return false - } - if emitter.column == 0 { - emitter.space_above = true - } - emitter.column = 0 - emitter.line++ - // [Go] Do this here and above and drop from everywhere else (see commented lines). - emitter.indention = true - } - return true -} - -// Set an emitter error and return false. -func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_EMITTER_ERROR - emitter.problem = problem - return false -} - -// Emit an event. -func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.events = append(emitter.events, *event) - for !yaml_emitter_need_more_events(emitter) { - event := &emitter.events[emitter.events_head] - if !yaml_emitter_analyze_event(emitter, event) { - return false - } - if !yaml_emitter_state_machine(emitter, event) { - return false - } - yaml_event_delete(event) - emitter.events_head++ - } - return true -} - -// Check if we need to accumulate more events before emitting. -// -// We accumulate extra -// - 1 event for DOCUMENT-START -// - 2 events for SEQUENCE-START -// - 3 events for MAPPING-START -// -func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { - if emitter.events_head == len(emitter.events) { - return true - } - var accumulate int - switch emitter.events[emitter.events_head].typ { - case yaml_DOCUMENT_START_EVENT: - accumulate = 1 - break - case yaml_SEQUENCE_START_EVENT: - accumulate = 2 - break - case yaml_MAPPING_START_EVENT: - accumulate = 3 - break - default: - return false - } - if len(emitter.events)-emitter.events_head > accumulate { - return false - } - var level int - for i := emitter.events_head; i < len(emitter.events); i++ { - switch emitter.events[i].typ { - case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: - level++ - case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: - level-- - } - if level == 0 { - return false - } - } - return true -} - -// Append a directive to the directives stack. -func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { - for i := 0; i < len(emitter.tag_directives); i++ { - if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") - } - } - - // [Go] Do we actually need to copy this given garbage collection - // and the lack of deallocating destructors? - tag_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(tag_copy.handle, value.handle) - copy(tag_copy.prefix, value.prefix) - emitter.tag_directives = append(emitter.tag_directives, tag_copy) - return true -} - -// Increase the indentation level. -func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { - emitter.indents = append(emitter.indents, emitter.indent) - if emitter.indent < 0 { - if flow { - emitter.indent = emitter.best_indent - } else { - emitter.indent = 0 - } - } else if !indentless { - // [Go] This was changed so that indentations are more regular. - if emitter.states[len(emitter.states)-1] == yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE { - // The first indent inside a sequence will just skip the "- " indicator. - emitter.indent += 2 - } else { - // Everything else aligns to the chosen indentation. - emitter.indent = emitter.best_indent*((emitter.indent+emitter.best_indent)/emitter.best_indent) - } - } - return true -} - -// State dispatcher. -func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { - switch emitter.state { - default: - case yaml_EMIT_STREAM_START_STATE: - return yaml_emitter_emit_stream_start(emitter, event) - - case yaml_EMIT_FIRST_DOCUMENT_START_STATE: - return yaml_emitter_emit_document_start(emitter, event, true) - - case yaml_EMIT_DOCUMENT_START_STATE: - return yaml_emitter_emit_document_start(emitter, event, false) - - case yaml_EMIT_DOCUMENT_CONTENT_STATE: - return yaml_emitter_emit_document_content(emitter, event) - - case yaml_EMIT_DOCUMENT_END_STATE: - return yaml_emitter_emit_document_end(emitter, event) - - case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, true, false) - - case yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, false, true) - - case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, false, false) - - case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, true, false) - - case yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, false, true) - - case yaml_EMIT_FLOW_MAPPING_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, false, false) - - case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: - return yaml_emitter_emit_flow_mapping_value(emitter, event, true) - - case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: - return yaml_emitter_emit_flow_mapping_value(emitter, event, false) - - case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_block_sequence_item(emitter, event, true) - - case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_block_sequence_item(emitter, event, false) - - case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_block_mapping_key(emitter, event, true) - - case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: - return yaml_emitter_emit_block_mapping_key(emitter, event, false) - - case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: - return yaml_emitter_emit_block_mapping_value(emitter, event, true) - - case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: - return yaml_emitter_emit_block_mapping_value(emitter, event, false) - - case yaml_EMIT_END_STATE: - return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") - } - panic("invalid emitter state") -} - -// Expect STREAM-START. -func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if event.typ != yaml_STREAM_START_EVENT { - return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") - } - if emitter.encoding == yaml_ANY_ENCODING { - emitter.encoding = event.encoding - if emitter.encoding == yaml_ANY_ENCODING { - emitter.encoding = yaml_UTF8_ENCODING - } - } - if emitter.best_indent < 2 || emitter.best_indent > 9 { - emitter.best_indent = 2 - } - if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { - emitter.best_width = 80 - } - if emitter.best_width < 0 { - emitter.best_width = 1<<31 - 1 - } - if emitter.line_break == yaml_ANY_BREAK { - emitter.line_break = yaml_LN_BREAK - } - - emitter.indent = -1 - emitter.line = 0 - emitter.column = 0 - emitter.whitespace = true - emitter.indention = true - emitter.space_above = true - emitter.foot_indent = -1 - - if emitter.encoding != yaml_UTF8_ENCODING { - if !yaml_emitter_write_bom(emitter) { - return false - } - } - emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE - return true -} - -// Expect DOCUMENT-START or STREAM-END. -func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - - if event.typ == yaml_DOCUMENT_START_EVENT { - - if event.version_directive != nil { - if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { - return false - } - } - - for i := 0; i < len(event.tag_directives); i++ { - tag_directive := &event.tag_directives[i] - if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { - return false - } - if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { - return false - } - } - - for i := 0; i < len(default_tag_directives); i++ { - tag_directive := &default_tag_directives[i] - if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { - return false - } - } - - implicit := event.implicit - if !first || emitter.canonical { - implicit = false - } - - if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if event.version_directive != nil { - implicit = false - if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if len(event.tag_directives) > 0 { - implicit = false - for i := 0; i < len(event.tag_directives); i++ { - tag_directive := &event.tag_directives[i] - if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { - return false - } - if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { - return false - } - if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - } - - if yaml_emitter_check_empty_document(emitter) { - implicit = false - } - if !implicit { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { - return false - } - if emitter.canonical || true { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - } - - if len(emitter.head_comment) > 0 { - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if !put_break(emitter) { - return false - } - } - - emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE - return true - } - - if event.typ == yaml_STREAM_END_EVENT { - if emitter.open_ended { - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_flush(emitter) { - return false - } - emitter.state = yaml_EMIT_END_STATE - return true - } - - return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") -} - -// Expect the root node. -func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) - - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if !yaml_emitter_emit_node(emitter, event, true, false, false, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -// Expect DOCUMENT-END. -func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if event.typ != yaml_DOCUMENT_END_EVENT { - return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") - } - // [Go] Force document foot separation. - emitter.foot_indent = 0 - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - emitter.foot_indent = -1 - if !yaml_emitter_write_indent(emitter) { - return false - } - if !event.implicit { - // [Go] Allocate the slice elsewhere. - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_flush(emitter) { - return false - } - emitter.state = yaml_EMIT_DOCUMENT_START_STATE - emitter.tag_directives = emitter.tag_directives[:0] - return true -} - -// Expect a flow item node. -func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { - if first { - if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - emitter.flow_level++ - } - - if event.typ == yaml_SEQUENCE_END_EVENT { - if emitter.canonical && !first && !trail { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.column == 0 || emitter.canonical && !first { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - - return true - } - - if !first && !trail { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if emitter.column == 0 { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE) - } else { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) - } - if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { - return false - } - if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -// Expect a flow key node. -func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { - if first { - if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - emitter.flow_level++ - } - - if event.typ == yaml_MAPPING_END_EVENT { - if (emitter.canonical || len(emitter.head_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0) && !first && !trail { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - if !yaml_emitter_process_head_comment(emitter) { - return false - } - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.canonical && !first { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - - if !first && !trail { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - - if !yaml_emitter_process_head_comment(emitter) { - return false - } - - if emitter.column == 0 { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, true) - } - if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a flow value node. -func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { - if simple { - if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { - return false - } - } else { - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { - return false - } - } - if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE) - } else { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) - } - if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { - return false - } - if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -// Expect a block item node. -func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_increase_indent(emitter, false, false) { - return false - } - } - if event.typ == yaml_SEQUENCE_END_EVENT { - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) - if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -// Expect a block key node. -func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_increase_indent(emitter, false, false) { - return false - } - } - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if event.typ == yaml_MAPPING_END_EVENT { - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if len(emitter.line_comment) > 0 { - // [Go] A line comment was provided for the key. That's unusual as the - // scanner associates line comments with the value. Either way, - // save the line comment and render it appropriately later. - emitter.key_line_comment = emitter.line_comment - emitter.line_comment = nil - } - if yaml_emitter_check_simple_key(emitter) { - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, true) - } - if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a block value node. -func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { - if simple { - if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { - return false - } - } else { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { - return false - } - } - if len(emitter.key_line_comment) > 0 { - // [Go] Line comments are generally associated with the value, but when there's - // no value on the same line as a mapping key they end up attached to the - // key itself. - if event.typ == yaml_SCALAR_EVENT { - if len(emitter.line_comment) == 0 { - // A scalar is coming and it has no line comments by itself yet, - // so just let it handle the line comment as usual. If it has a - // line comment, we can't have both so the one from the key is lost. - emitter.line_comment = emitter.key_line_comment - emitter.key_line_comment = nil - } - } else if event.sequence_style() != yaml_FLOW_SEQUENCE_STYLE && (event.typ == yaml_MAPPING_START_EVENT || event.typ == yaml_SEQUENCE_START_EVENT) { - // An indented block follows, so write the comment right now. - emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment - if !yaml_emitter_process_line_comment(emitter) { - return false - } - emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment - } - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) - if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -func yaml_emitter_silent_nil_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { - return event.typ == yaml_SCALAR_EVENT && event.implicit && !emitter.canonical && len(emitter.scalar_data.value) == 0 -} - -// Expect a node. -func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, - root bool, sequence bool, mapping bool, simple_key bool) bool { - - emitter.root_context = root - emitter.sequence_context = sequence - emitter.mapping_context = mapping - emitter.simple_key_context = simple_key - - switch event.typ { - case yaml_ALIAS_EVENT: - return yaml_emitter_emit_alias(emitter, event) - case yaml_SCALAR_EVENT: - return yaml_emitter_emit_scalar(emitter, event) - case yaml_SEQUENCE_START_EVENT: - return yaml_emitter_emit_sequence_start(emitter, event) - case yaml_MAPPING_START_EVENT: - return yaml_emitter_emit_mapping_start(emitter, event) - default: - return yaml_emitter_set_emitter_error(emitter, - fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) - } -} - -// Expect ALIAS. -func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true -} - -// Expect SCALAR. -func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_select_scalar_style(emitter, event) { - return false - } - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - if !yaml_emitter_process_scalar(emitter) { - return false - } - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true -} - -// Expect SEQUENCE-START. -func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || - yaml_emitter_check_empty_sequence(emitter) { - emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE - } else { - emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE - } - return true -} - -// Expect MAPPING-START. -func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || - yaml_emitter_check_empty_mapping(emitter) { - emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE - } else { - emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE - } - return true -} - -// Check if the document content is an empty scalar. -func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { - return false // [Go] Huh? -} - -// Check if the next events represent an empty sequence. -func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { - if len(emitter.events)-emitter.events_head < 2 { - return false - } - return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && - emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT -} - -// Check if the next events represent an empty mapping. -func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { - if len(emitter.events)-emitter.events_head < 2 { - return false - } - return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && - emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT -} - -// Check if the next node can be expressed as a simple key. -func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { - length := 0 - switch emitter.events[emitter.events_head].typ { - case yaml_ALIAS_EVENT: - length += len(emitter.anchor_data.anchor) - case yaml_SCALAR_EVENT: - if emitter.scalar_data.multiline { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) + - len(emitter.scalar_data.value) - case yaml_SEQUENCE_START_EVENT: - if !yaml_emitter_check_empty_sequence(emitter) { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) - case yaml_MAPPING_START_EVENT: - if !yaml_emitter_check_empty_mapping(emitter) { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) - default: - return false - } - return length <= 128 -} - -// Determine an acceptable scalar style. -func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { - - no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 - if no_tag && !event.implicit && !event.quoted_implicit { - return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") - } - - style := event.scalar_style() - if style == yaml_ANY_SCALAR_STYLE { - style = yaml_PLAIN_SCALAR_STYLE - } - if emitter.canonical { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - if emitter.simple_key_context && emitter.scalar_data.multiline { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - - if style == yaml_PLAIN_SCALAR_STYLE { - if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || - emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - if no_tag && !event.implicit { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - } - if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { - if !emitter.scalar_data.single_quoted_allowed { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - } - if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { - if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - } - - if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { - emitter.tag_data.handle = []byte{'!'} - } - emitter.scalar_data.style = style - return true -} - -// Write an anchor. -func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { - if emitter.anchor_data.anchor == nil { - return true - } - c := []byte{'&'} - if emitter.anchor_data.alias { - c[0] = '*' - } - if !yaml_emitter_write_indicator(emitter, c, true, false, false) { - return false - } - return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) -} - -// Write a tag. -func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { - if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { - return true - } - if len(emitter.tag_data.handle) > 0 { - if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { - return false - } - if len(emitter.tag_data.suffix) > 0 { - if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { - return false - } - } - } else { - // [Go] Allocate these slices elsewhere. - if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { - return false - } - if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { - return false - } - } - return true -} - -// Write a scalar. -func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { - switch emitter.scalar_data.style { - case yaml_PLAIN_SCALAR_STYLE: - return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_SINGLE_QUOTED_SCALAR_STYLE: - return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_DOUBLE_QUOTED_SCALAR_STYLE: - return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_LITERAL_SCALAR_STYLE: - return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) - - case yaml_FOLDED_SCALAR_STYLE: - return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) - } - panic("unknown scalar style") -} - -// Write a head comment. -func yaml_emitter_process_head_comment(emitter *yaml_emitter_t) bool { - if len(emitter.tail_comment) > 0 { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_comment(emitter, emitter.tail_comment) { - return false - } - emitter.tail_comment = emitter.tail_comment[:0] - emitter.foot_indent = emitter.indent - if emitter.foot_indent < 0 { - emitter.foot_indent = 0 - } - } - - if len(emitter.head_comment) == 0 { - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_comment(emitter, emitter.head_comment) { - return false - } - emitter.head_comment = emitter.head_comment[:0] - return true -} - -// Write an line comment. -func yaml_emitter_process_line_comment(emitter *yaml_emitter_t) bool { - if len(emitter.line_comment) == 0 { - return true - } - if !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !yaml_emitter_write_comment(emitter, emitter.line_comment) { - return false - } - emitter.line_comment = emitter.line_comment[:0] - return true -} - -// Write a foot comment. -func yaml_emitter_process_foot_comment(emitter *yaml_emitter_t) bool { - if len(emitter.foot_comment) == 0 { - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_comment(emitter, emitter.foot_comment) { - return false - } - emitter.foot_comment = emitter.foot_comment[:0] - emitter.foot_indent = emitter.indent - if emitter.foot_indent < 0 { - emitter.foot_indent = 0 - } - return true -} - -// Check if a %YAML directive is valid. -func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { - if version_directive.major != 1 || version_directive.minor != 1 { - return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") - } - return true -} - -// Check if a %TAG directive is valid. -func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { - handle := tag_directive.handle - prefix := tag_directive.prefix - if len(handle) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") - } - if handle[0] != '!' { - return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") - } - if handle[len(handle)-1] != '!' { - return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") - } - for i := 1; i < len(handle)-1; i += width(handle[i]) { - if !is_alpha(handle, i) { - return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") - } - } - if len(prefix) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") - } - return true -} - -// Check if an anchor is valid. -func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { - if len(anchor) == 0 { - problem := "anchor value must not be empty" - if alias { - problem = "alias value must not be empty" - } - return yaml_emitter_set_emitter_error(emitter, problem) - } - for i := 0; i < len(anchor); i += width(anchor[i]) { - if !is_alpha(anchor, i) { - problem := "anchor value must contain alphanumerical characters only" - if alias { - problem = "alias value must contain alphanumerical characters only" - } - return yaml_emitter_set_emitter_error(emitter, problem) - } - } - emitter.anchor_data.anchor = anchor - emitter.anchor_data.alias = alias - return true -} - -// Check if a tag is valid. -func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { - if len(tag) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") - } - for i := 0; i < len(emitter.tag_directives); i++ { - tag_directive := &emitter.tag_directives[i] - if bytes.HasPrefix(tag, tag_directive.prefix) { - emitter.tag_data.handle = tag_directive.handle - emitter.tag_data.suffix = tag[len(tag_directive.prefix):] - return true - } - } - emitter.tag_data.suffix = tag - return true -} - -// Check if a scalar is valid. -func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { - var ( - block_indicators = false - flow_indicators = false - line_breaks = false - special_characters = false - tab_characters = false - - leading_space = false - leading_break = false - trailing_space = false - trailing_break = false - break_space = false - space_break = false - - preceded_by_whitespace = false - followed_by_whitespace = false - previous_space = false - previous_break = false - ) - - emitter.scalar_data.value = value - - if len(value) == 0 { - emitter.scalar_data.multiline = false - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = true - emitter.scalar_data.single_quoted_allowed = true - emitter.scalar_data.block_allowed = false - return true - } - - if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { - block_indicators = true - flow_indicators = true - } - - preceded_by_whitespace = true - for i, w := 0, 0; i < len(value); i += w { - w = width(value[i]) - followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) - - if i == 0 { - switch value[i] { - case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': - flow_indicators = true - block_indicators = true - case '?', ':': - flow_indicators = true - if followed_by_whitespace { - block_indicators = true - } - case '-': - if followed_by_whitespace { - flow_indicators = true - block_indicators = true - } - } - } else { - switch value[i] { - case ',', '?', '[', ']', '{', '}': - flow_indicators = true - case ':': - flow_indicators = true - if followed_by_whitespace { - block_indicators = true - } - case '#': - if preceded_by_whitespace { - flow_indicators = true - block_indicators = true - } - } - } - - if value[i] == '\t' { - tab_characters = true - } else if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { - special_characters = true - } - if is_space(value, i) { - if i == 0 { - leading_space = true - } - if i+width(value[i]) == len(value) { - trailing_space = true - } - if previous_break { - break_space = true - } - previous_space = true - previous_break = false - } else if is_break(value, i) { - line_breaks = true - if i == 0 { - leading_break = true - } - if i+width(value[i]) == len(value) { - trailing_break = true - } - if previous_space { - space_break = true - } - previous_space = false - previous_break = true - } else { - previous_space = false - previous_break = false - } - - // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. - preceded_by_whitespace = is_blankz(value, i) - } - - emitter.scalar_data.multiline = line_breaks - emitter.scalar_data.flow_plain_allowed = true - emitter.scalar_data.block_plain_allowed = true - emitter.scalar_data.single_quoted_allowed = true - emitter.scalar_data.block_allowed = true - - if leading_space || leading_break || trailing_space || trailing_break { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - } - if trailing_space { - emitter.scalar_data.block_allowed = false - } - if break_space { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - emitter.scalar_data.single_quoted_allowed = false - } - if space_break || tab_characters || special_characters { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - emitter.scalar_data.single_quoted_allowed = false - } - if space_break || special_characters { - emitter.scalar_data.block_allowed = false - } - if line_breaks { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - } - if flow_indicators { - emitter.scalar_data.flow_plain_allowed = false - } - if block_indicators { - emitter.scalar_data.block_plain_allowed = false - } - return true -} - -// Check if the event data is valid. -func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { - - emitter.anchor_data.anchor = nil - emitter.tag_data.handle = nil - emitter.tag_data.suffix = nil - emitter.scalar_data.value = nil - - if len(event.head_comment) > 0 { - emitter.head_comment = event.head_comment - } - if len(event.line_comment) > 0 { - emitter.line_comment = event.line_comment - } - if len(event.foot_comment) > 0 { - emitter.foot_comment = event.foot_comment - } - if len(event.tail_comment) > 0 { - emitter.tail_comment = event.tail_comment - } - - switch event.typ { - case yaml_ALIAS_EVENT: - if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { - return false - } - - case yaml_SCALAR_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - if !yaml_emitter_analyze_scalar(emitter, event.value) { - return false - } - - case yaml_SEQUENCE_START_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - - case yaml_MAPPING_START_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - } - return true -} - -// Write the BOM character. -func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { - if !flush(emitter) { - return false - } - pos := emitter.buffer_pos - emitter.buffer[pos+0] = '\xEF' - emitter.buffer[pos+1] = '\xBB' - emitter.buffer[pos+2] = '\xBF' - emitter.buffer_pos += 3 - return true -} - -func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { - indent := emitter.indent - if indent < 0 { - indent = 0 - } - if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { - if !put_break(emitter) { - return false - } - } - if emitter.foot_indent == indent { - if !put_break(emitter) { - return false - } - } - for emitter.column < indent { - if !put(emitter, ' ') { - return false - } - } - emitter.whitespace = true - //emitter.indention = true - emitter.space_above = false - emitter.foot_indent = -1 - return true -} - -func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { - if need_whitespace && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !write_all(emitter, indicator) { - return false - } - emitter.whitespace = is_whitespace - emitter.indention = (emitter.indention && is_indention) - emitter.open_ended = false - return true -} - -func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { - if !write_all(emitter, value) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { - if !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !write_all(emitter, value) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { - if need_whitespace && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - for i := 0; i < len(value); { - var must_write bool - switch value[i] { - case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': - must_write = true - default: - must_write = is_alpha(value, i) - } - if must_write { - if !write(emitter, value, &i) { - return false - } - } else { - w := width(value[i]) - for k := 0; k < w; k++ { - octet := value[i] - i++ - if !put(emitter, '%') { - return false - } - - c := octet >> 4 - if c < 10 { - c += '0' - } else { - c += 'A' - 10 - } - if !put(emitter, c) { - return false - } - - c = octet & 0x0f - if c < 10 { - c += '0' - } else { - c += 'A' - 10 - } - if !put(emitter, c) { - return false - } - } - } - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - if len(value) > 0 && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - - spaces := false - breaks := false - for i := 0; i < len(value); { - if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - spaces = true - } else if is_break(value, i) { - if !breaks && value[i] == '\n' { - if !put_break(emitter) { - return false - } - } - if !write_break(emitter, value, &i) { - return false - } - //emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - spaces = false - breaks = false - } - } - - if len(value) > 0 { - emitter.whitespace = false - } - emitter.indention = false - if emitter.root_context { - emitter.open_ended = true - } - - return true -} - -func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { - return false - } - - spaces := false - breaks := false - for i := 0; i < len(value); { - if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - spaces = true - } else if is_break(value, i) { - if !breaks && value[i] == '\n' { - if !put_break(emitter) { - return false - } - } - if !write_break(emitter, value, &i) { - return false - } - //emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if value[i] == '\'' { - if !put(emitter, '\'') { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - spaces = false - breaks = false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - spaces := false - if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { - return false - } - - for i := 0; i < len(value); { - if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || - is_bom(value, i) || is_break(value, i) || - value[i] == '"' || value[i] == '\\' { - - octet := value[i] - - var w int - var v rune - switch { - case octet&0x80 == 0x00: - w, v = 1, rune(octet&0x7F) - case octet&0xE0 == 0xC0: - w, v = 2, rune(octet&0x1F) - case octet&0xF0 == 0xE0: - w, v = 3, rune(octet&0x0F) - case octet&0xF8 == 0xF0: - w, v = 4, rune(octet&0x07) - } - for k := 1; k < w; k++ { - octet = value[i+k] - v = (v << 6) + (rune(octet) & 0x3F) - } - i += w - - if !put(emitter, '\\') { - return false - } - - var ok bool - switch v { - case 0x00: - ok = put(emitter, '0') - case 0x07: - ok = put(emitter, 'a') - case 0x08: - ok = put(emitter, 'b') - case 0x09: - ok = put(emitter, 't') - case 0x0A: - ok = put(emitter, 'n') - case 0x0b: - ok = put(emitter, 'v') - case 0x0c: - ok = put(emitter, 'f') - case 0x0d: - ok = put(emitter, 'r') - case 0x1b: - ok = put(emitter, 'e') - case 0x22: - ok = put(emitter, '"') - case 0x5c: - ok = put(emitter, '\\') - case 0x85: - ok = put(emitter, 'N') - case 0xA0: - ok = put(emitter, '_') - case 0x2028: - ok = put(emitter, 'L') - case 0x2029: - ok = put(emitter, 'P') - default: - if v <= 0xFF { - ok = put(emitter, 'x') - w = 2 - } else if v <= 0xFFFF { - ok = put(emitter, 'u') - w = 4 - } else { - ok = put(emitter, 'U') - w = 8 - } - for k := (w - 1) * 4; ok && k >= 0; k -= 4 { - digit := byte((v >> uint(k)) & 0x0F) - if digit < 10 { - ok = put(emitter, digit+'0') - } else { - ok = put(emitter, digit+'A'-10) - } - } - } - if !ok { - return false - } - spaces = false - } else if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { - if !yaml_emitter_write_indent(emitter) { - return false - } - if is_space(value, i+1) { - if !put(emitter, '\\') { - return false - } - } - i += width(value[i]) - } else if !write(emitter, value, &i) { - return false - } - spaces = true - } else { - if !write(emitter, value, &i) { - return false - } - spaces = false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { - if is_space(value, 0) || is_break(value, 0) { - indent_hint := []byte{'0' + byte(emitter.best_indent)} - if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { - return false - } - } - - emitter.open_ended = false - - var chomp_hint [1]byte - if len(value) == 0 { - chomp_hint[0] = '-' - } else { - i := len(value) - 1 - for value[i]&0xC0 == 0x80 { - i-- - } - if !is_break(value, i) { - chomp_hint[0] = '-' - } else if i == 0 { - chomp_hint[0] = '+' - emitter.open_ended = true - } else { - i-- - for value[i]&0xC0 == 0x80 { - i-- - } - if is_break(value, i) { - chomp_hint[0] = '+' - emitter.open_ended = true - } - } - } - if chomp_hint[0] != 0 { - if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { - return false - } - } - return true -} - -func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { - return false - } - if !yaml_emitter_write_block_scalar_hints(emitter, value) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - //emitter.indention = true - emitter.whitespace = true - breaks := true - for i := 0; i < len(value); { - if is_break(value, i) { - if !write_break(emitter, value, &i) { - return false - } - //emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - breaks = false - } - } - - return true -} - -func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { - return false - } - if !yaml_emitter_write_block_scalar_hints(emitter, value) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - - //emitter.indention = true - emitter.whitespace = true - - breaks := true - leading_spaces := true - for i := 0; i < len(value); { - if is_break(value, i) { - if !breaks && !leading_spaces && value[i] == '\n' { - k := 0 - for is_break(value, k) { - k += width(value[k]) - } - if !is_blankz(value, k) { - if !put_break(emitter) { - return false - } - } - } - if !write_break(emitter, value, &i) { - return false - } - //emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - leading_spaces = is_blank(value, i) - } - if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - emitter.indention = false - breaks = false - } - } - return true -} - -func yaml_emitter_write_comment(emitter *yaml_emitter_t, comment []byte) bool { - breaks := false - pound := false - for i := 0; i < len(comment); { - if is_break(comment, i) { - if !write_break(emitter, comment, &i) { - return false - } - //emitter.indention = true - breaks = true - pound = false - } else { - if breaks && !yaml_emitter_write_indent(emitter) { - return false - } - if !pound { - if comment[i] != '#' && (!put(emitter, '#') || !put(emitter, ' ')) { - return false - } - pound = true - } - if !write(emitter, comment, &i) { - return false - } - emitter.indention = false - breaks = false - } - } - if !breaks && !put_break(emitter) { - return false - } - - emitter.whitespace = true - //emitter.indention = true - return true -} diff --git a/api/vendor/gopkg.in/yaml.v3/encode.go b/api/vendor/gopkg.in/yaml.v3/encode.go deleted file mode 100644 index de9e72a3e638..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/encode.go +++ /dev/null @@ -1,577 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package yaml - -import ( - "encoding" - "fmt" - "io" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -type encoder struct { - emitter yaml_emitter_t - event yaml_event_t - out []byte - flow bool - indent int - doneInit bool -} - -func newEncoder() *encoder { - e := &encoder{} - yaml_emitter_initialize(&e.emitter) - yaml_emitter_set_output_string(&e.emitter, &e.out) - yaml_emitter_set_unicode(&e.emitter, true) - return e -} - -func newEncoderWithWriter(w io.Writer) *encoder { - e := &encoder{} - yaml_emitter_initialize(&e.emitter) - yaml_emitter_set_output_writer(&e.emitter, w) - yaml_emitter_set_unicode(&e.emitter, true) - return e -} - -func (e *encoder) init() { - if e.doneInit { - return - } - if e.indent == 0 { - e.indent = 4 - } - e.emitter.best_indent = e.indent - yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) - e.emit() - e.doneInit = true -} - -func (e *encoder) finish() { - e.emitter.open_ended = false - yaml_stream_end_event_initialize(&e.event) - e.emit() -} - -func (e *encoder) destroy() { - yaml_emitter_delete(&e.emitter) -} - -func (e *encoder) emit() { - // This will internally delete the e.event value. - e.must(yaml_emitter_emit(&e.emitter, &e.event)) -} - -func (e *encoder) must(ok bool) { - if !ok { - msg := e.emitter.problem - if msg == "" { - msg = "unknown problem generating YAML content" - } - failf("%s", msg) - } -} - -func (e *encoder) marshalDoc(tag string, in reflect.Value) { - e.init() - var node *Node - if in.IsValid() { - node, _ = in.Interface().(*Node) - } - if node != nil && node.Kind == DocumentNode { - e.nodev(in) - } else { - yaml_document_start_event_initialize(&e.event, nil, nil, true) - e.emit() - e.marshal(tag, in) - yaml_document_end_event_initialize(&e.event, true) - e.emit() - } -} - -func (e *encoder) marshal(tag string, in reflect.Value) { - tag = shortTag(tag) - if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { - e.nilv() - return - } - iface := in.Interface() - switch value := iface.(type) { - case *Node: - e.nodev(in) - return - case Node: - if !in.CanAddr() { - var n = reflect.New(in.Type()).Elem() - n.Set(in) - in = n - } - e.nodev(in.Addr()) - return - case time.Time: - e.timev(tag, in) - return - case *time.Time: - e.timev(tag, in.Elem()) - return - case time.Duration: - e.stringv(tag, reflect.ValueOf(value.String())) - return - case Marshaler: - v, err := value.MarshalYAML() - if err != nil { - fail(err) - } - if v == nil { - e.nilv() - return - } - e.marshal(tag, reflect.ValueOf(v)) - return - case encoding.TextMarshaler: - text, err := value.MarshalText() - if err != nil { - fail(err) - } - in = reflect.ValueOf(string(text)) - case nil: - e.nilv() - return - } - switch in.Kind() { - case reflect.Interface: - e.marshal(tag, in.Elem()) - case reflect.Map: - e.mapv(tag, in) - case reflect.Ptr: - e.marshal(tag, in.Elem()) - case reflect.Struct: - e.structv(tag, in) - case reflect.Slice, reflect.Array: - e.slicev(tag, in) - case reflect.String: - e.stringv(tag, in) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - e.intv(tag, in) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - e.uintv(tag, in) - case reflect.Float32, reflect.Float64: - e.floatv(tag, in) - case reflect.Bool: - e.boolv(tag, in) - default: - panic("cannot marshal type: " + in.Type().String()) - } -} - -func (e *encoder) mapv(tag string, in reflect.Value) { - e.mappingv(tag, func() { - keys := keyList(in.MapKeys()) - sort.Sort(keys) - for _, k := range keys { - e.marshal("", k) - e.marshal("", in.MapIndex(k)) - } - }) -} - -func (e *encoder) fieldByIndex(v reflect.Value, index []int) (field reflect.Value) { - for _, num := range index { - for { - if v.Kind() == reflect.Ptr { - if v.IsNil() { - return reflect.Value{} - } - v = v.Elem() - continue - } - break - } - v = v.Field(num) - } - return v -} - -func (e *encoder) structv(tag string, in reflect.Value) { - sinfo, err := getStructInfo(in.Type()) - if err != nil { - panic(err) - } - e.mappingv(tag, func() { - for _, info := range sinfo.FieldsList { - var value reflect.Value - if info.Inline == nil { - value = in.Field(info.Num) - } else { - value = e.fieldByIndex(in, info.Inline) - if !value.IsValid() { - continue - } - } - if info.OmitEmpty && isZero(value) { - continue - } - e.marshal("", reflect.ValueOf(info.Key)) - e.flow = info.Flow - e.marshal("", value) - } - if sinfo.InlineMap >= 0 { - m := in.Field(sinfo.InlineMap) - if m.Len() > 0 { - e.flow = false - keys := keyList(m.MapKeys()) - sort.Sort(keys) - for _, k := range keys { - if _, found := sinfo.FieldsMap[k.String()]; found { - panic(fmt.Sprintf("cannot have key %q in inlined map: conflicts with struct field", k.String())) - } - e.marshal("", k) - e.flow = false - e.marshal("", m.MapIndex(k)) - } - } - } - }) -} - -func (e *encoder) mappingv(tag string, f func()) { - implicit := tag == "" - style := yaml_BLOCK_MAPPING_STYLE - if e.flow { - e.flow = false - style = yaml_FLOW_MAPPING_STYLE - } - yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) - e.emit() - f() - yaml_mapping_end_event_initialize(&e.event) - e.emit() -} - -func (e *encoder) slicev(tag string, in reflect.Value) { - implicit := tag == "" - style := yaml_BLOCK_SEQUENCE_STYLE - if e.flow { - e.flow = false - style = yaml_FLOW_SEQUENCE_STYLE - } - e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) - e.emit() - n := in.Len() - for i := 0; i < n; i++ { - e.marshal("", in.Index(i)) - } - e.must(yaml_sequence_end_event_initialize(&e.event)) - e.emit() -} - -// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. -// -// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported -// in YAML 1.2 and by this package, but these should be marshalled quoted for -// the time being for compatibility with other parsers. -func isBase60Float(s string) (result bool) { - // Fast path. - if s == "" { - return false - } - c := s[0] - if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { - return false - } - // Do the full match. - return base60float.MatchString(s) -} - -// From http://yaml.org/type/float.html, except the regular expression there -// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. -var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) - -// isOldBool returns whether s is bool notation as defined in YAML 1.1. -// -// We continue to force strings that YAML 1.1 would interpret as booleans to be -// rendered as quotes strings so that the marshalled output valid for YAML 1.1 -// parsing. -func isOldBool(s string) (result bool) { - switch s { - case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", - "n", "N", "no", "No", "NO", "off", "Off", "OFF": - return true - default: - return false - } -} - -func (e *encoder) stringv(tag string, in reflect.Value) { - var style yaml_scalar_style_t - s := in.String() - canUsePlain := true - switch { - case !utf8.ValidString(s): - if tag == binaryTag { - failf("explicitly tagged !!binary data must be base64-encoded") - } - if tag != "" { - failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) - } - // It can't be encoded directly as YAML so use a binary tag - // and encode it as base64. - tag = binaryTag - s = encodeBase64(s) - case tag == "": - // Check to see if it would resolve to a specific - // tag when encoded unquoted. If it doesn't, - // there's no need to quote it. - rtag, _ := resolve("", s) - canUsePlain = rtag == strTag && !(isBase60Float(s) || isOldBool(s)) - } - // Note: it's possible for user code to emit invalid YAML - // if they explicitly specify a tag and a string containing - // text that's incompatible with that tag. - switch { - case strings.Contains(s, "\n"): - if e.flow { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } else { - style = yaml_LITERAL_SCALAR_STYLE - } - case canUsePlain: - style = yaml_PLAIN_SCALAR_STYLE - default: - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - e.emitScalar(s, "", tag, style, nil, nil, nil, nil) -} - -func (e *encoder) boolv(tag string, in reflect.Value) { - var s string - if in.Bool() { - s = "true" - } else { - s = "false" - } - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) intv(tag string, in reflect.Value) { - s := strconv.FormatInt(in.Int(), 10) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) uintv(tag string, in reflect.Value) { - s := strconv.FormatUint(in.Uint(), 10) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) timev(tag string, in reflect.Value) { - t := in.Interface().(time.Time) - s := t.Format(time.RFC3339Nano) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) floatv(tag string, in reflect.Value) { - // Issue #352: When formatting, use the precision of the underlying value - precision := 64 - if in.Kind() == reflect.Float32 { - precision = 32 - } - - s := strconv.FormatFloat(in.Float(), 'g', -1, precision) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) nilv() { - e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t, head, line, foot, tail []byte) { - // TODO Kill this function. Replace all initialize calls by their underlining Go literals. - implicit := tag == "" - if !implicit { - tag = longTag(tag) - } - e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) - e.event.head_comment = head - e.event.line_comment = line - e.event.foot_comment = foot - e.event.tail_comment = tail - e.emit() -} - -func (e *encoder) nodev(in reflect.Value) { - e.node(in.Interface().(*Node), "") -} - -func (e *encoder) node(node *Node, tail string) { - // Zero nodes behave as nil. - if node.Kind == 0 && node.IsZero() { - e.nilv() - return - } - - // If the tag was not explicitly requested, and dropping it won't change the - // implicit tag of the value, don't include it in the presentation. - var tag = node.Tag - var stag = shortTag(tag) - var forceQuoting bool - if tag != "" && node.Style&TaggedStyle == 0 { - if node.Kind == ScalarNode { - if stag == strTag && node.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 { - tag = "" - } else { - rtag, _ := resolve("", node.Value) - if rtag == stag { - tag = "" - } else if stag == strTag { - tag = "" - forceQuoting = true - } - } - } else { - var rtag string - switch node.Kind { - case MappingNode: - rtag = mapTag - case SequenceNode: - rtag = seqTag - } - if rtag == stag { - tag = "" - } - } - } - - switch node.Kind { - case DocumentNode: - yaml_document_start_event_initialize(&e.event, nil, nil, true) - e.event.head_comment = []byte(node.HeadComment) - e.emit() - for _, node := range node.Content { - e.node(node, "") - } - yaml_document_end_event_initialize(&e.event, true) - e.event.foot_comment = []byte(node.FootComment) - e.emit() - - case SequenceNode: - style := yaml_BLOCK_SEQUENCE_STYLE - if node.Style&FlowStyle != 0 { - style = yaml_FLOW_SEQUENCE_STYLE - } - e.must(yaml_sequence_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style)) - e.event.head_comment = []byte(node.HeadComment) - e.emit() - for _, node := range node.Content { - e.node(node, "") - } - e.must(yaml_sequence_end_event_initialize(&e.event)) - e.event.line_comment = []byte(node.LineComment) - e.event.foot_comment = []byte(node.FootComment) - e.emit() - - case MappingNode: - style := yaml_BLOCK_MAPPING_STYLE - if node.Style&FlowStyle != 0 { - style = yaml_FLOW_MAPPING_STYLE - } - yaml_mapping_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style) - e.event.tail_comment = []byte(tail) - e.event.head_comment = []byte(node.HeadComment) - e.emit() - - // The tail logic below moves the foot comment of prior keys to the following key, - // since the value for each key may be a nested structure and the foot needs to be - // processed only the entirety of the value is streamed. The last tail is processed - // with the mapping end event. - var tail string - for i := 0; i+1 < len(node.Content); i += 2 { - k := node.Content[i] - foot := k.FootComment - if foot != "" { - kopy := *k - kopy.FootComment = "" - k = &kopy - } - e.node(k, tail) - tail = foot - - v := node.Content[i+1] - e.node(v, "") - } - - yaml_mapping_end_event_initialize(&e.event) - e.event.tail_comment = []byte(tail) - e.event.line_comment = []byte(node.LineComment) - e.event.foot_comment = []byte(node.FootComment) - e.emit() - - case AliasNode: - yaml_alias_event_initialize(&e.event, []byte(node.Value)) - e.event.head_comment = []byte(node.HeadComment) - e.event.line_comment = []byte(node.LineComment) - e.event.foot_comment = []byte(node.FootComment) - e.emit() - - case ScalarNode: - value := node.Value - if !utf8.ValidString(value) { - if stag == binaryTag { - failf("explicitly tagged !!binary data must be base64-encoded") - } - if stag != "" { - failf("cannot marshal invalid UTF-8 data as %s", stag) - } - // It can't be encoded directly as YAML so use a binary tag - // and encode it as base64. - tag = binaryTag - value = encodeBase64(value) - } - - style := yaml_PLAIN_SCALAR_STYLE - switch { - case node.Style&DoubleQuotedStyle != 0: - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - case node.Style&SingleQuotedStyle != 0: - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - case node.Style&LiteralStyle != 0: - style = yaml_LITERAL_SCALAR_STYLE - case node.Style&FoldedStyle != 0: - style = yaml_FOLDED_SCALAR_STYLE - case strings.Contains(value, "\n"): - style = yaml_LITERAL_SCALAR_STYLE - case forceQuoting: - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - - e.emitScalar(value, node.Anchor, tag, style, []byte(node.HeadComment), []byte(node.LineComment), []byte(node.FootComment), []byte(tail)) - default: - failf("cannot encode node with unknown kind %d", node.Kind) - } -} diff --git a/api/vendor/gopkg.in/yaml.v3/parserc.go b/api/vendor/gopkg.in/yaml.v3/parserc.go deleted file mode 100644 index 268558a0d632..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/parserc.go +++ /dev/null @@ -1,1258 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package yaml - -import ( - "bytes" -) - -// The parser implements the following grammar: -// -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// implicit_document ::= block_node DOCUMENT-END* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// block_node_or_indentless_sequence ::= -// ALIAS -// | properties (block_content | indentless_block_sequence)? -// | block_content -// | indentless_block_sequence -// block_node ::= ALIAS -// | properties block_content? -// | block_content -// flow_node ::= ALIAS -// | properties flow_content? -// | flow_content -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// block_content ::= block_collection | flow_collection | SCALAR -// flow_content ::= flow_collection | SCALAR -// block_collection ::= block_sequence | block_mapping -// flow_collection ::= flow_sequence | flow_mapping -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// block_mapping ::= BLOCK-MAPPING_START -// ((KEY block_node_or_indentless_sequence?)? -// (VALUE block_node_or_indentless_sequence?)?)* -// BLOCK-END -// flow_sequence ::= FLOW-SEQUENCE-START -// (flow_sequence_entry FLOW-ENTRY)* -// flow_sequence_entry? -// FLOW-SEQUENCE-END -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// flow_mapping ::= FLOW-MAPPING-START -// (flow_mapping_entry FLOW-ENTRY)* -// flow_mapping_entry? -// FLOW-MAPPING-END -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? - -// Peek the next token in the token queue. -func peek_token(parser *yaml_parser_t) *yaml_token_t { - if parser.token_available || yaml_parser_fetch_more_tokens(parser) { - token := &parser.tokens[parser.tokens_head] - yaml_parser_unfold_comments(parser, token) - return token - } - return nil -} - -// yaml_parser_unfold_comments walks through the comments queue and joins all -// comments behind the position of the provided token into the respective -// top-level comment slices in the parser. -func yaml_parser_unfold_comments(parser *yaml_parser_t, token *yaml_token_t) { - for parser.comments_head < len(parser.comments) && token.start_mark.index >= parser.comments[parser.comments_head].token_mark.index { - comment := &parser.comments[parser.comments_head] - if len(comment.head) > 0 { - if token.typ == yaml_BLOCK_END_TOKEN { - // No heads on ends, so keep comment.head for a follow up token. - break - } - if len(parser.head_comment) > 0 { - parser.head_comment = append(parser.head_comment, '\n') - } - parser.head_comment = append(parser.head_comment, comment.head...) - } - if len(comment.foot) > 0 { - if len(parser.foot_comment) > 0 { - parser.foot_comment = append(parser.foot_comment, '\n') - } - parser.foot_comment = append(parser.foot_comment, comment.foot...) - } - if len(comment.line) > 0 { - if len(parser.line_comment) > 0 { - parser.line_comment = append(parser.line_comment, '\n') - } - parser.line_comment = append(parser.line_comment, comment.line...) - } - *comment = yaml_comment_t{} - parser.comments_head++ - } -} - -// Remove the next token from the queue (must be called after peek_token). -func skip_token(parser *yaml_parser_t) { - parser.token_available = false - parser.tokens_parsed++ - parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN - parser.tokens_head++ -} - -// Get the next event. -func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { - // Erase the event object. - *event = yaml_event_t{} - - // No events after the end of the stream or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { - return true - } - - // Generate the next event. - return yaml_parser_state_machine(parser, event) -} - -// Set parser error. -func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -// State dispatcher. -func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { - //trace("yaml_parser_state_machine", "state:", parser.state.String()) - - switch parser.state { - case yaml_PARSE_STREAM_START_STATE: - return yaml_parser_parse_stream_start(parser, event) - - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, true) - - case yaml_PARSE_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, false) - - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return yaml_parser_parse_document_content(parser, event) - - case yaml_PARSE_DOCUMENT_END_STATE: - return yaml_parser_parse_document_end(parser, event) - - case yaml_PARSE_BLOCK_NODE_STATE: - return yaml_parser_parse_node(parser, event, true, false) - - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return yaml_parser_parse_node(parser, event, true, true) - - case yaml_PARSE_FLOW_NODE_STATE: - return yaml_parser_parse_node(parser, event, false, false) - - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, true) - - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, false) - - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_indentless_sequence_entry(parser, event) - - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, true) - - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, false) - - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return yaml_parser_parse_block_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, true) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, false) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) - - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, true) - - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, true) - - default: - panic("invalid parser state") - } -} - -// Parse the production: -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// ************ -func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_STREAM_START_TOKEN { - return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) - } - parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - encoding: token.encoding, - } - skip_token(parser) - return true -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// * -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// ************************* -func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { - - token := peek_token(parser) - if token == nil { - return false - } - - // Parse extra document end indicators. - if !implicit { - for token.typ == yaml_DOCUMENT_END_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && - token.typ != yaml_TAG_DIRECTIVE_TOKEN && - token.typ != yaml_DOCUMENT_START_TOKEN && - token.typ != yaml_STREAM_END_TOKEN { - // Parse an implicit document. - if !yaml_parser_process_directives(parser, nil, nil) { - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_BLOCK_NODE_STATE - - var head_comment []byte - if len(parser.head_comment) > 0 { - // [Go] Scan the header comment backwards, and if an empty line is found, break - // the header so the part before the last empty line goes into the - // document header, while the bottom of it goes into a follow up event. - for i := len(parser.head_comment) - 1; i > 0; i-- { - if parser.head_comment[i] == '\n' { - if i == len(parser.head_comment)-1 { - head_comment = parser.head_comment[:i] - parser.head_comment = parser.head_comment[i+1:] - break - } else if parser.head_comment[i-1] == '\n' { - head_comment = parser.head_comment[:i-1] - parser.head_comment = parser.head_comment[i+1:] - break - } - } - } - } - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - - head_comment: head_comment, - } - - } else if token.typ != yaml_STREAM_END_TOKEN { - // Parse an explicit document. - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - start_mark := token.start_mark - if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { - return false - } - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_DOCUMENT_START_TOKEN { - yaml_parser_set_parser_error(parser, - "did not find expected ", token.start_mark) - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE - end_mark := token.end_mark - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: false, - } - skip_token(parser) - - } else { - // Parse the stream end. - parser.state = yaml_PARSE_END_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - } - - return true -} - -// Parse the productions: -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// *********** -// -func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || - token.typ == yaml_TAG_DIRECTIVE_TOKEN || - token.typ == yaml_DOCUMENT_START_TOKEN || - token.typ == yaml_DOCUMENT_END_TOKEN || - token.typ == yaml_STREAM_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - return yaml_parser_process_empty_scalar(parser, event, - token.start_mark) - } - return yaml_parser_parse_node(parser, event, true, false) -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// ************* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - start_mark := token.start_mark - end_mark := token.start_mark - - implicit := true - if token.typ == yaml_DOCUMENT_END_TOKEN { - end_mark = token.end_mark - skip_token(parser) - implicit = false - } - - parser.tag_directives = parser.tag_directives[:0] - - parser.state = yaml_PARSE_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - start_mark: start_mark, - end_mark: end_mark, - implicit: implicit, - } - yaml_parser_set_event_comments(parser, event) - if len(event.head_comment) > 0 && len(event.foot_comment) == 0 { - event.foot_comment = event.head_comment - event.head_comment = nil - } - return true -} - -func yaml_parser_set_event_comments(parser *yaml_parser_t, event *yaml_event_t) { - event.head_comment = parser.head_comment - event.line_comment = parser.line_comment - event.foot_comment = parser.foot_comment - parser.head_comment = nil - parser.line_comment = nil - parser.foot_comment = nil - parser.tail_comment = nil - parser.stem_comment = nil -} - -// Parse the productions: -// block_node_or_indentless_sequence ::= -// ALIAS -// ***** -// | properties (block_content | indentless_block_sequence)? -// ********** * -// | block_content | indentless_block_sequence -// * -// block_node ::= ALIAS -// ***** -// | properties block_content? -// ********** * -// | block_content -// * -// flow_node ::= ALIAS -// ***** -// | properties flow_content? -// ********** * -// | flow_content -// * -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// ************************* -// block_content ::= block_collection | flow_collection | SCALAR -// ****** -// flow_content ::= flow_collection | SCALAR -// ****** -func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { - //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_ALIAS_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - *event = yaml_event_t{ - typ: yaml_ALIAS_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - anchor: token.value, - } - yaml_parser_set_event_comments(parser, event) - skip_token(parser) - return true - } - - start_mark := token.start_mark - end_mark := token.start_mark - - var tag_token bool - var tag_handle, tag_suffix, anchor []byte - var tag_mark yaml_mark_t - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - start_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } else if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - start_mark = token.start_mark - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - var tag []byte - if tag_token { - if len(tag_handle) == 0 { - tag = tag_suffix - tag_suffix = nil - } else { - for i := range parser.tag_directives { - if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { - tag = append([]byte(nil), parser.tag_directives[i].prefix...) - tag = append(tag, tag_suffix...) - break - } - } - if len(tag) == 0 { - yaml_parser_set_parser_error_context(parser, - "while parsing a node", start_mark, - "found undefined tag handle", tag_mark) - return false - } - } - } - - implicit := len(tag) == 0 - if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - return true - } - if token.typ == yaml_SCALAR_TOKEN { - var plain_implicit, quoted_implicit bool - end_mark = token.end_mark - if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { - plain_implicit = true - } else if len(tag) == 0 { - quoted_implicit = true - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - value: token.value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(token.style), - } - yaml_parser_set_event_comments(parser, event) - skip_token(parser) - return true - } - if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { - // [Go] Some of the events below can be merged as they differ only on style. - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), - } - yaml_parser_set_event_comments(parser, event) - return true - } - if token.typ == yaml_FLOW_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - yaml_parser_set_event_comments(parser, event) - return true - } - if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - if parser.stem_comment != nil { - event.head_comment = parser.stem_comment - parser.stem_comment = nil - } - return true - } - if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), - } - if parser.stem_comment != nil { - event.head_comment = parser.stem_comment - parser.stem_comment = nil - } - return true - } - if len(anchor) > 0 || len(tag) > 0 { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - quoted_implicit: false, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true - } - - context := "while parsing a flow node" - if block { - context = "while parsing a block node" - } - yaml_parser_set_parser_error_context(parser, context, start_mark, - "did not find expected node content", token.start_mark) - return false -} - -// Parse the productions: -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// ******************** *********** * ********* -// -func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - if token == nil { - return false - } - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - prior_head_len := len(parser.head_comment) - skip_token(parser) - yaml_parser_split_stem_comment(parser, prior_head_len) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } else { - parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } - if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block collection", context_mark, - "did not find expected '-' indicator", token.start_mark) -} - -// Parse the productions: -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// *********** * -func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - prior_head_len := len(parser.head_comment) - skip_token(parser) - yaml_parser_split_stem_comment(parser, prior_head_len) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && - token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? - } - return true -} - -// Split stem comment from head comment. -// -// When a sequence or map is found under a sequence entry, the former head comment -// is assigned to the underlying sequence or map as a whole, not the individual -// sequence or map entry as would be expected otherwise. To handle this case the -// previous head comment is moved aside as the stem comment. -func yaml_parser_split_stem_comment(parser *yaml_parser_t, stem_len int) { - if stem_len == 0 { - return - } - - token := peek_token(parser) - if token == nil || token.typ != yaml_BLOCK_SEQUENCE_START_TOKEN && token.typ != yaml_BLOCK_MAPPING_START_TOKEN { - return - } - - parser.stem_comment = parser.head_comment[:stem_len] - if len(parser.head_comment) == stem_len { - parser.head_comment = nil - } else { - // Copy suffix to prevent very strange bugs if someone ever appends - // further bytes to the prefix in the stem_comment slice above. - parser.head_comment = append([]byte(nil), parser.head_comment[stem_len+1:]...) - } -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// ******************* -// ((KEY block_node_or_indentless_sequence?)? -// *** * -// (VALUE block_node_or_indentless_sequence?)?)* -// -// BLOCK-END -// ********* -// -func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - if token == nil { - return false - } - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - // [Go] A tail comment was left from the prior mapping value processed. Emit an event - // as it needs to be processed with that value and not the following key. - if len(parser.tail_comment) > 0 { - *event = yaml_event_t{ - typ: yaml_TAIL_COMMENT_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - foot_comment: parser.tail_comment, - } - parser.tail_comment = nil - return true - } - - if token.typ == yaml_KEY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } else { - parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } else if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - yaml_parser_set_event_comments(parser, event) - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block mapping", context_mark, - "did not find expected key", token.start_mark) -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// -// ((KEY block_node_or_indentless_sequence?)? -// -// (VALUE block_node_or_indentless_sequence?)?)* -// ***** * -// BLOCK-END -// -// -func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence ::= FLOW-SEQUENCE-START -// ******************* -// (flow_sequence_entry FLOW-ENTRY)* -// * ********** -// flow_sequence_entry? -// * -// FLOW-SEQUENCE-END -// ***************** -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * -// -func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - if token == nil { - return false - } - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow sequence", context_mark, - "did not find expected ',' or ']'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - implicit: true, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - skip_token(parser) - return true - } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - yaml_parser_set_event_comments(parser, event) - - skip_token(parser) - return true -} - -// -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// *** * -// -func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - mark := token.end_mark - skip_token(parser) - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// ***** * -// -func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * -// -func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? - } - return true -} - -// Parse the productions: -// flow_mapping ::= FLOW-MAPPING-START -// ****************** -// (flow_mapping_entry FLOW-ENTRY)* -// * ********** -// flow_mapping_entry? -// ****************** -// FLOW-MAPPING-END -// **************** -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * *** * -// -func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow mapping", context_mark, - "did not find expected ',' or '}'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } else { - parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - yaml_parser_set_event_comments(parser, event) - skip_token(parser) - return true -} - -// Parse the productions: -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * ***** * -// -func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { - token := peek_token(parser) - if token == nil { - return false - } - if empty { - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Generate an empty scalar event. -func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: mark, - end_mark: mark, - value: nil, // Empty - implicit: true, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true -} - -var default_tag_directives = []yaml_tag_directive_t{ - {[]byte("!"), []byte("!")}, - {[]byte("!!"), []byte("tag:yaml.org,2002:")}, -} - -// Parse directives. -func yaml_parser_process_directives(parser *yaml_parser_t, - version_directive_ref **yaml_version_directive_t, - tag_directives_ref *[]yaml_tag_directive_t) bool { - - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - - token := peek_token(parser) - if token == nil { - return false - } - - for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { - if version_directive != nil { - yaml_parser_set_parser_error(parser, - "found duplicate %YAML directive", token.start_mark) - return false - } - if token.major != 1 || token.minor != 1 { - yaml_parser_set_parser_error(parser, - "found incompatible YAML document", token.start_mark) - return false - } - version_directive = &yaml_version_directive_t{ - major: token.major, - minor: token.minor, - } - } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { - value := yaml_tag_directive_t{ - handle: token.value, - prefix: token.prefix, - } - if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { - return false - } - tag_directives = append(tag_directives, value) - } - - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - - for i := range default_tag_directives { - if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { - return false - } - } - - if version_directive_ref != nil { - *version_directive_ref = version_directive - } - if tag_directives_ref != nil { - *tag_directives_ref = tag_directives - } - return true -} - -// Append a tag directive to the directives stack. -func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { - for i := range parser.tag_directives { - if bytes.Equal(value.handle, parser.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) - } - } - - // [Go] I suspect the copy is unnecessary. This was likely done - // because there was no way to track ownership of the data. - value_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(value_copy.handle, value.handle) - copy(value_copy.prefix, value.prefix) - parser.tag_directives = append(parser.tag_directives, value_copy) - return true -} diff --git a/api/vendor/gopkg.in/yaml.v3/readerc.go b/api/vendor/gopkg.in/yaml.v3/readerc.go deleted file mode 100644 index b7de0a89c462..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/readerc.go +++ /dev/null @@ -1,434 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package yaml - -import ( - "io" -) - -// Set the reader error and return 0. -func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { - parser.error = yaml_READER_ERROR - parser.problem = problem - parser.problem_offset = offset - parser.problem_value = value - return false -} - -// Byte order marks. -const ( - bom_UTF8 = "\xef\xbb\xbf" - bom_UTF16LE = "\xff\xfe" - bom_UTF16BE = "\xfe\xff" -) - -// Determine the input stream encoding by checking the BOM symbol. If no BOM is -// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. -func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { - // Ensure that we had enough bytes in the raw buffer. - for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { - if !yaml_parser_update_raw_buffer(parser) { - return false - } - } - - // Determine the encoding. - buf := parser.raw_buffer - pos := parser.raw_buffer_pos - avail := len(buf) - pos - if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { - parser.encoding = yaml_UTF16LE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { - parser.encoding = yaml_UTF16BE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { - parser.encoding = yaml_UTF8_ENCODING - parser.raw_buffer_pos += 3 - parser.offset += 3 - } else { - parser.encoding = yaml_UTF8_ENCODING - } - return true -} - -// Update the raw buffer. -func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { - size_read := 0 - - // Return if the raw buffer is full. - if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { - return true - } - - // Return on EOF. - if parser.eof { - return true - } - - // Move the remaining bytes in the raw buffer to the beginning. - if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { - copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) - } - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] - parser.raw_buffer_pos = 0 - - // Call the read handler to fill the buffer. - size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] - if err == io.EOF { - parser.eof = true - } else if err != nil { - return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) - } - return true -} - -// Ensure that the buffer contains at least `length` characters. -// Return true on success, false on failure. -// -// The length is supposed to be significantly less that the buffer size. -func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { - if parser.read_handler == nil { - panic("read handler must be set") - } - - // [Go] This function was changed to guarantee the requested length size at EOF. - // The fact we need to do this is pretty awful, but the description above implies - // for that to be the case, and there are tests - - // If the EOF flag is set and the raw buffer is empty, do nothing. - if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { - // [Go] ACTUALLY! Read the documentation of this function above. - // This is just broken. To return true, we need to have the - // given length in the buffer. Not doing that means every single - // check that calls this function to make sure the buffer has a - // given length is Go) panicking; or C) accessing invalid memory. - //return true - } - - // Return if the buffer contains enough characters. - if parser.unread >= length { - return true - } - - // Determine the input encoding if it is not known yet. - if parser.encoding == yaml_ANY_ENCODING { - if !yaml_parser_determine_encoding(parser) { - return false - } - } - - // Move the unread characters to the beginning of the buffer. - buffer_len := len(parser.buffer) - if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { - copy(parser.buffer, parser.buffer[parser.buffer_pos:]) - buffer_len -= parser.buffer_pos - parser.buffer_pos = 0 - } else if parser.buffer_pos == buffer_len { - buffer_len = 0 - parser.buffer_pos = 0 - } - - // Open the whole buffer for writing, and cut it before returning. - parser.buffer = parser.buffer[:cap(parser.buffer)] - - // Fill the buffer until it has enough characters. - first := true - for parser.unread < length { - - // Fill the raw buffer if necessary. - if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { - if !yaml_parser_update_raw_buffer(parser) { - parser.buffer = parser.buffer[:buffer_len] - return false - } - } - first = false - - // Decode the raw buffer. - inner: - for parser.raw_buffer_pos != len(parser.raw_buffer) { - var value rune - var width int - - raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos - - // Decode the next character. - switch parser.encoding { - case yaml_UTF8_ENCODING: - // Decode a UTF-8 character. Check RFC 3629 - // (http://www.ietf.org/rfc/rfc3629.txt) for more details. - // - // The following table (taken from the RFC) is used for - // decoding. - // - // Char. number range | UTF-8 octet sequence - // (hexadecimal) | (binary) - // --------------------+------------------------------------ - // 0000 0000-0000 007F | 0xxxxxxx - // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx - // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx - // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - // - // Additionally, the characters in the range 0xD800-0xDFFF - // are prohibited as they are reserved for use with UTF-16 - // surrogate pairs. - - // Determine the length of the UTF-8 sequence. - octet := parser.raw_buffer[parser.raw_buffer_pos] - switch { - case octet&0x80 == 0x00: - width = 1 - case octet&0xE0 == 0xC0: - width = 2 - case octet&0xF0 == 0xE0: - width = 3 - case octet&0xF8 == 0xF0: - width = 4 - default: - // The leading octet is invalid. - return yaml_parser_set_reader_error(parser, - "invalid leading UTF-8 octet", - parser.offset, int(octet)) - } - - // Check if the raw buffer contains an incomplete character. - if width > raw_unread { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-8 octet sequence", - parser.offset, -1) - } - break inner - } - - // Decode the leading octet. - switch { - case octet&0x80 == 0x00: - value = rune(octet & 0x7F) - case octet&0xE0 == 0xC0: - value = rune(octet & 0x1F) - case octet&0xF0 == 0xE0: - value = rune(octet & 0x0F) - case octet&0xF8 == 0xF0: - value = rune(octet & 0x07) - default: - value = 0 - } - - // Check and decode the trailing octets. - for k := 1; k < width; k++ { - octet = parser.raw_buffer[parser.raw_buffer_pos+k] - - // Check if the octet is valid. - if (octet & 0xC0) != 0x80 { - return yaml_parser_set_reader_error(parser, - "invalid trailing UTF-8 octet", - parser.offset+k, int(octet)) - } - - // Decode the octet. - value = (value << 6) + rune(octet&0x3F) - } - - // Check the length of the sequence against the value. - switch { - case width == 1: - case width == 2 && value >= 0x80: - case width == 3 && value >= 0x800: - case width == 4 && value >= 0x10000: - default: - return yaml_parser_set_reader_error(parser, - "invalid length of a UTF-8 sequence", - parser.offset, -1) - } - - // Check the range of the value. - if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { - return yaml_parser_set_reader_error(parser, - "invalid Unicode character", - parser.offset, int(value)) - } - - case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: - var low, high int - if parser.encoding == yaml_UTF16LE_ENCODING { - low, high = 0, 1 - } else { - low, high = 1, 0 - } - - // The UTF-16 encoding is not as simple as one might - // naively think. Check RFC 2781 - // (http://www.ietf.org/rfc/rfc2781.txt). - // - // Normally, two subsequent bytes describe a Unicode - // character. However a special technique (called a - // surrogate pair) is used for specifying character - // values larger than 0xFFFF. - // - // A surrogate pair consists of two pseudo-characters: - // high surrogate area (0xD800-0xDBFF) - // low surrogate area (0xDC00-0xDFFF) - // - // The following formulas are used for decoding - // and encoding characters using surrogate pairs: - // - // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) - // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) - // W1 = 110110yyyyyyyyyy - // W2 = 110111xxxxxxxxxx - // - // where U is the character value, W1 is the high surrogate - // area, W2 is the low surrogate area. - - // Check for incomplete UTF-16 character. - if raw_unread < 2 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 character", - parser.offset, -1) - } - break inner - } - - // Get the character. - value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) - - // Check for unexpected low surrogate area. - if value&0xFC00 == 0xDC00 { - return yaml_parser_set_reader_error(parser, - "unexpected low surrogate area", - parser.offset, int(value)) - } - - // Check for a high surrogate area. - if value&0xFC00 == 0xD800 { - width = 4 - - // Check for incomplete surrogate pair. - if raw_unread < 4 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 surrogate pair", - parser.offset, -1) - } - break inner - } - - // Get the next character. - value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) - - // Check for a low surrogate area. - if value2&0xFC00 != 0xDC00 { - return yaml_parser_set_reader_error(parser, - "expected low surrogate area", - parser.offset+2, int(value2)) - } - - // Generate the value of the surrogate pair. - value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) - } else { - width = 2 - } - - default: - panic("impossible") - } - - // Check if the character is in the allowed range: - // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) - // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) - // | [#x10000-#x10FFFF] (32 bit) - switch { - case value == 0x09: - case value == 0x0A: - case value == 0x0D: - case value >= 0x20 && value <= 0x7E: - case value == 0x85: - case value >= 0xA0 && value <= 0xD7FF: - case value >= 0xE000 && value <= 0xFFFD: - case value >= 0x10000 && value <= 0x10FFFF: - default: - return yaml_parser_set_reader_error(parser, - "control characters are not allowed", - parser.offset, int(value)) - } - - // Move the raw pointers. - parser.raw_buffer_pos += width - parser.offset += width - - // Finally put the character into the buffer. - if value <= 0x7F { - // 0000 0000-0000 007F . 0xxxxxxx - parser.buffer[buffer_len+0] = byte(value) - buffer_len += 1 - } else if value <= 0x7FF { - // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) - parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) - buffer_len += 2 - } else if value <= 0xFFFF { - // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) - buffer_len += 3 - } else { - // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) - buffer_len += 4 - } - - parser.unread++ - } - - // On EOF, put NUL into the buffer and return. - if parser.eof { - parser.buffer[buffer_len] = 0 - buffer_len++ - parser.unread++ - break - } - } - // [Go] Read the documentation of this function above. To return true, - // we need to have the given length in the buffer. Not doing that means - // every single check that calls this function to make sure the buffer - // has a given length is Go) panicking; or C) accessing invalid memory. - // This happens here due to the EOF above breaking early. - for buffer_len < length { - parser.buffer[buffer_len] = 0 - buffer_len++ - } - parser.buffer = parser.buffer[:buffer_len] - return true -} diff --git a/api/vendor/gopkg.in/yaml.v3/resolve.go b/api/vendor/gopkg.in/yaml.v3/resolve.go deleted file mode 100644 index 64ae888057a5..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/resolve.go +++ /dev/null @@ -1,326 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package yaml - -import ( - "encoding/base64" - "math" - "regexp" - "strconv" - "strings" - "time" -) - -type resolveMapItem struct { - value interface{} - tag string -} - -var resolveTable = make([]byte, 256) -var resolveMap = make(map[string]resolveMapItem) - -func init() { - t := resolveTable - t[int('+')] = 'S' // Sign - t[int('-')] = 'S' - for _, c := range "0123456789" { - t[int(c)] = 'D' // Digit - } - for _, c := range "yYnNtTfFoO~" { - t[int(c)] = 'M' // In map - } - t[int('.')] = '.' // Float (potentially in map) - - var resolveMapList = []struct { - v interface{} - tag string - l []string - }{ - {true, boolTag, []string{"true", "True", "TRUE"}}, - {false, boolTag, []string{"false", "False", "FALSE"}}, - {nil, nullTag, []string{"", "~", "null", "Null", "NULL"}}, - {math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}}, - {math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}}, - {math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}}, - {math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}}, - {"<<", mergeTag, []string{"<<"}}, - } - - m := resolveMap - for _, item := range resolveMapList { - for _, s := range item.l { - m[s] = resolveMapItem{item.v, item.tag} - } - } -} - -const ( - nullTag = "!!null" - boolTag = "!!bool" - strTag = "!!str" - intTag = "!!int" - floatTag = "!!float" - timestampTag = "!!timestamp" - seqTag = "!!seq" - mapTag = "!!map" - binaryTag = "!!binary" - mergeTag = "!!merge" -) - -var longTags = make(map[string]string) -var shortTags = make(map[string]string) - -func init() { - for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} { - ltag := longTag(stag) - longTags[stag] = ltag - shortTags[ltag] = stag - } -} - -const longTagPrefix = "tag:yaml.org,2002:" - -func shortTag(tag string) string { - if strings.HasPrefix(tag, longTagPrefix) { - if stag, ok := shortTags[tag]; ok { - return stag - } - return "!!" + tag[len(longTagPrefix):] - } - return tag -} - -func longTag(tag string) string { - if strings.HasPrefix(tag, "!!") { - if ltag, ok := longTags[tag]; ok { - return ltag - } - return longTagPrefix + tag[2:] - } - return tag -} - -func resolvableTag(tag string) bool { - switch tag { - case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag: - return true - } - return false -} - -var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) - -func resolve(tag string, in string) (rtag string, out interface{}) { - tag = shortTag(tag) - if !resolvableTag(tag) { - return tag, in - } - - defer func() { - switch tag { - case "", rtag, strTag, binaryTag: - return - case floatTag: - if rtag == intTag { - switch v := out.(type) { - case int64: - rtag = floatTag - out = float64(v) - return - case int: - rtag = floatTag - out = float64(v) - return - } - } - } - failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) - }() - - // Any data is accepted as a !!str or !!binary. - // Otherwise, the prefix is enough of a hint about what it might be. - hint := byte('N') - if in != "" { - hint = resolveTable[in[0]] - } - if hint != 0 && tag != strTag && tag != binaryTag { - // Handle things we can lookup in a map. - if item, ok := resolveMap[in]; ok { - return item.tag, item.value - } - - // Base 60 floats are a bad idea, were dropped in YAML 1.2, and - // are purposefully unsupported here. They're still quoted on - // the way out for compatibility with other parser, though. - - switch hint { - case 'M': - // We've already checked the map above. - - case '.': - // Not in the map, so maybe a normal float. - floatv, err := strconv.ParseFloat(in, 64) - if err == nil { - return floatTag, floatv - } - - case 'D', 'S': - // Int, float, or timestamp. - // Only try values as a timestamp if the value is unquoted or there's an explicit - // !!timestamp tag. - if tag == "" || tag == timestampTag { - t, ok := parseTimestamp(in) - if ok { - return timestampTag, t - } - } - - plain := strings.Replace(in, "_", "", -1) - intv, err := strconv.ParseInt(plain, 0, 64) - if err == nil { - if intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - uintv, err := strconv.ParseUint(plain, 0, 64) - if err == nil { - return intTag, uintv - } - if yamlStyleFloat.MatchString(plain) { - floatv, err := strconv.ParseFloat(plain, 64) - if err == nil { - return floatTag, floatv - } - } - if strings.HasPrefix(plain, "0b") { - intv, err := strconv.ParseInt(plain[2:], 2, 64) - if err == nil { - if intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - uintv, err := strconv.ParseUint(plain[2:], 2, 64) - if err == nil { - return intTag, uintv - } - } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) - if err == nil { - if true || intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - } - // Octals as introduced in version 1.2 of the spec. - // Octals from the 1.1 spec, spelled as 0777, are still - // decoded by default in v3 as well for compatibility. - // May be dropped in v4 depending on how usage evolves. - if strings.HasPrefix(plain, "0o") { - intv, err := strconv.ParseInt(plain[2:], 8, 64) - if err == nil { - if intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - uintv, err := strconv.ParseUint(plain[2:], 8, 64) - if err == nil { - return intTag, uintv - } - } else if strings.HasPrefix(plain, "-0o") { - intv, err := strconv.ParseInt("-"+plain[3:], 8, 64) - if err == nil { - if true || intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - } - default: - panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")") - } - } - return strTag, in -} - -// encodeBase64 encodes s as base64 that is broken up into multiple lines -// as appropriate for the resulting length. -func encodeBase64(s string) string { - const lineLen = 70 - encLen := base64.StdEncoding.EncodedLen(len(s)) - lines := encLen/lineLen + 1 - buf := make([]byte, encLen*2+lines) - in := buf[0:encLen] - out := buf[encLen:] - base64.StdEncoding.Encode(in, []byte(s)) - k := 0 - for i := 0; i < len(in); i += lineLen { - j := i + lineLen - if j > len(in) { - j = len(in) - } - k += copy(out[k:], in[i:j]) - if lines > 1 { - out[k] = '\n' - k++ - } - } - return string(out[:k]) -} - -// This is a subset of the formats allowed by the regular expression -// defined at http://yaml.org/type/timestamp.html. -var allowedTimestampFormats = []string{ - "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. - "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". - "2006-1-2 15:4:5.999999999", // space separated with no time zone - "2006-1-2", // date only - // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" - // from the set of examples. -} - -// parseTimestamp parses s as a timestamp string and -// returns the timestamp and reports whether it succeeded. -// Timestamp formats are defined at http://yaml.org/type/timestamp.html -func parseTimestamp(s string) (time.Time, bool) { - // TODO write code to check all the formats supported by - // http://yaml.org/type/timestamp.html instead of using time.Parse. - - // Quick check: all date formats start with YYYY-. - i := 0 - for ; i < len(s); i++ { - if c := s[i]; c < '0' || c > '9' { - break - } - } - if i != 4 || i == len(s) || s[i] != '-' { - return time.Time{}, false - } - for _, format := range allowedTimestampFormats { - if t, err := time.Parse(format, s); err == nil { - return t, true - } - } - return time.Time{}, false -} diff --git a/api/vendor/gopkg.in/yaml.v3/scannerc.go b/api/vendor/gopkg.in/yaml.v3/scannerc.go deleted file mode 100644 index ca0070108f4e..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/scannerc.go +++ /dev/null @@ -1,3038 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package yaml - -import ( - "bytes" - "fmt" -) - -// Introduction -// ************ -// -// The following notes assume that you are familiar with the YAML specification -// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in -// some cases we are less restrictive that it requires. -// -// The process of transforming a YAML stream into a sequence of events is -// divided on two steps: Scanning and Parsing. -// -// The Scanner transforms the input stream into a sequence of tokens, while the -// parser transform the sequence of tokens produced by the Scanner into a -// sequence of parsing events. -// -// The Scanner is rather clever and complicated. The Parser, on the contrary, -// is a straightforward implementation of a recursive-descendant parser (or, -// LL(1) parser, as it is usually called). -// -// Actually there are two issues of Scanning that might be called "clever", the -// rest is quite straightforward. The issues are "block collection start" and -// "simple keys". Both issues are explained below in details. -// -// Here the Scanning step is explained and implemented. We start with the list -// of all the tokens produced by the Scanner together with short descriptions. -// -// Now, tokens: -// -// STREAM-START(encoding) # The stream start. -// STREAM-END # The stream end. -// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. -// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. -// DOCUMENT-START # '---' -// DOCUMENT-END # '...' -// BLOCK-SEQUENCE-START # Indentation increase denoting a block -// BLOCK-MAPPING-START # sequence or a block mapping. -// BLOCK-END # Indentation decrease. -// FLOW-SEQUENCE-START # '[' -// FLOW-SEQUENCE-END # ']' -// BLOCK-SEQUENCE-START # '{' -// BLOCK-SEQUENCE-END # '}' -// BLOCK-ENTRY # '-' -// FLOW-ENTRY # ',' -// KEY # '?' or nothing (simple keys). -// VALUE # ':' -// ALIAS(anchor) # '*anchor' -// ANCHOR(anchor) # '&anchor' -// TAG(handle,suffix) # '!handle!suffix' -// SCALAR(value,style) # A scalar. -// -// The following two tokens are "virtual" tokens denoting the beginning and the -// end of the stream: -// -// STREAM-START(encoding) -// STREAM-END -// -// We pass the information about the input stream encoding with the -// STREAM-START token. -// -// The next two tokens are responsible for tags: -// -// VERSION-DIRECTIVE(major,minor) -// TAG-DIRECTIVE(handle,prefix) -// -// Example: -// -// %YAML 1.1 -// %TAG ! !foo -// %TAG !yaml! tag:yaml.org,2002: -// --- -// -// The correspoding sequence of tokens: -// -// STREAM-START(utf-8) -// VERSION-DIRECTIVE(1,1) -// TAG-DIRECTIVE("!","!foo") -// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") -// DOCUMENT-START -// STREAM-END -// -// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole -// line. -// -// The document start and end indicators are represented by: -// -// DOCUMENT-START -// DOCUMENT-END -// -// Note that if a YAML stream contains an implicit document (without '---' -// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be -// produced. -// -// In the following examples, we present whole documents together with the -// produced tokens. -// -// 1. An implicit document: -// -// 'a scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// STREAM-END -// -// 2. An explicit document: -// -// --- -// 'a scalar' -// ... -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// SCALAR("a scalar",single-quoted) -// DOCUMENT-END -// STREAM-END -// -// 3. Several documents in a stream: -// -// 'a scalar' -// --- -// 'another scalar' -// --- -// 'yet another scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// DOCUMENT-START -// SCALAR("another scalar",single-quoted) -// DOCUMENT-START -// SCALAR("yet another scalar",single-quoted) -// STREAM-END -// -// We have already introduced the SCALAR token above. The following tokens are -// used to describe aliases, anchors, tag, and scalars: -// -// ALIAS(anchor) -// ANCHOR(anchor) -// TAG(handle,suffix) -// SCALAR(value,style) -// -// The following series of examples illustrate the usage of these tokens: -// -// 1. A recursive sequence: -// -// &A [ *A ] -// -// Tokens: -// -// STREAM-START(utf-8) -// ANCHOR("A") -// FLOW-SEQUENCE-START -// ALIAS("A") -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A tagged scalar: -// -// !!float "3.14" # A good approximation. -// -// Tokens: -// -// STREAM-START(utf-8) -// TAG("!!","float") -// SCALAR("3.14",double-quoted) -// STREAM-END -// -// 3. Various scalar styles: -// -// --- # Implicit empty plain scalars do not produce tokens. -// --- a plain scalar -// --- 'a single-quoted scalar' -// --- "a double-quoted scalar" -// --- |- -// a literal scalar -// --- >- -// a folded -// scalar -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// DOCUMENT-START -// SCALAR("a plain scalar",plain) -// DOCUMENT-START -// SCALAR("a single-quoted scalar",single-quoted) -// DOCUMENT-START -// SCALAR("a double-quoted scalar",double-quoted) -// DOCUMENT-START -// SCALAR("a literal scalar",literal) -// DOCUMENT-START -// SCALAR("a folded scalar",folded) -// STREAM-END -// -// Now it's time to review collection-related tokens. We will start with -// flow collections: -// -// FLOW-SEQUENCE-START -// FLOW-SEQUENCE-END -// FLOW-MAPPING-START -// FLOW-MAPPING-END -// FLOW-ENTRY -// KEY -// VALUE -// -// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and -// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' -// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the -// indicators '?' and ':', which are used for denoting mapping keys and values, -// are represented by the KEY and VALUE tokens. -// -// The following examples show flow collections: -// -// 1. A flow sequence: -// -// [item 1, item 2, item 3] -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-SEQUENCE-START -// SCALAR("item 1",plain) -// FLOW-ENTRY -// SCALAR("item 2",plain) -// FLOW-ENTRY -// SCALAR("item 3",plain) -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A flow mapping: -// -// { -// a simple key: a value, # Note that the KEY token is produced. -// ? a complex key: another value, -// } -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// FLOW-ENTRY -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// FLOW-ENTRY -// FLOW-MAPPING-END -// STREAM-END -// -// A simple key is a key which is not denoted by the '?' indicator. Note that -// the Scanner still produce the KEY token whenever it encounters a simple key. -// -// For scanning block collections, the following tokens are used (note that we -// repeat KEY and VALUE here): -// -// BLOCK-SEQUENCE-START -// BLOCK-MAPPING-START -// BLOCK-END -// BLOCK-ENTRY -// KEY -// VALUE -// -// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation -// increase that precedes a block collection (cf. the INDENT token in Python). -// The token BLOCK-END denote indentation decrease that ends a block collection -// (cf. the DEDENT token in Python). However YAML has some syntax pecularities -// that makes detections of these tokens more complex. -// -// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators -// '-', '?', and ':' correspondingly. -// -// The following examples show how the tokens BLOCK-SEQUENCE-START, -// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: -// -// 1. Block sequences: -// -// - item 1 -// - item 2 -// - -// - item 3.1 -// - item 3.2 -// - -// key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 3.1",plain) -// BLOCK-ENTRY -// SCALAR("item 3.2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Block mappings: -// -// a simple key: a value # The KEY token is produced here. -// ? a complex key -// : another value -// a mapping: -// key 1: value 1 -// key 2: value 2 -// a sequence: -// - item 1 -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// KEY -// SCALAR("a mapping",plain) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML does not always require to start a new block collection from a new -// line. If the current line contains only '-', '?', and ':' indicators, a new -// block collection may start at the current line. The following examples -// illustrate this case: -// -// 1. Collections in a sequence: -// -// - - item 1 -// - item 2 -// - key 1: value 1 -// key 2: value 2 -// - ? complex key -// : complex value -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("complex key") -// VALUE -// SCALAR("complex value") -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Collections in a mapping: -// -// ? a sequence -// : - item 1 -// - item 2 -// ? a mapping -// : key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// KEY -// SCALAR("a mapping",plain) -// VALUE -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML also permits non-indented sequences if they are included into a block -// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: -// -// key: -// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key",plain) -// VALUE -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// - -// Ensure that the buffer contains the required number of characters. -// Return true on success, false on failure (reader error or memory error). -func cache(parser *yaml_parser_t, length int) bool { - // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) - return parser.unread >= length || yaml_parser_update_buffer(parser, length) -} - -// Advance the buffer pointer. -func skip(parser *yaml_parser_t) { - if !is_blank(parser.buffer, parser.buffer_pos) { - parser.newlines = 0 - } - parser.mark.index++ - parser.mark.column++ - parser.unread-- - parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) -} - -func skip_line(parser *yaml_parser_t) { - if is_crlf(parser.buffer, parser.buffer_pos) { - parser.mark.index += 2 - parser.mark.column = 0 - parser.mark.line++ - parser.unread -= 2 - parser.buffer_pos += 2 - parser.newlines++ - } else if is_break(parser.buffer, parser.buffer_pos) { - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) - parser.newlines++ - } -} - -// Copy a character to a string buffer and advance pointers. -func read(parser *yaml_parser_t, s []byte) []byte { - if !is_blank(parser.buffer, parser.buffer_pos) { - parser.newlines = 0 - } - w := width(parser.buffer[parser.buffer_pos]) - if w == 0 { - panic("invalid character sequence") - } - if len(s) == 0 { - s = make([]byte, 0, 32) - } - if w == 1 && len(s)+w <= cap(s) { - s = s[:len(s)+1] - s[len(s)-1] = parser.buffer[parser.buffer_pos] - parser.buffer_pos++ - } else { - s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) - parser.buffer_pos += w - } - parser.mark.index++ - parser.mark.column++ - parser.unread-- - return s -} - -// Copy a line break character to a string buffer and advance pointers. -func read_line(parser *yaml_parser_t, s []byte) []byte { - buf := parser.buffer - pos := parser.buffer_pos - switch { - case buf[pos] == '\r' && buf[pos+1] == '\n': - // CR LF . LF - s = append(s, '\n') - parser.buffer_pos += 2 - parser.mark.index++ - parser.unread-- - case buf[pos] == '\r' || buf[pos] == '\n': - // CR|LF . LF - s = append(s, '\n') - parser.buffer_pos += 1 - case buf[pos] == '\xC2' && buf[pos+1] == '\x85': - // NEL . LF - s = append(s, '\n') - parser.buffer_pos += 2 - case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): - // LS|PS . LS|PS - s = append(s, buf[parser.buffer_pos:pos+3]...) - parser.buffer_pos += 3 - default: - return s - } - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - parser.newlines++ - return s -} - -// Get the next token. -func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { - // Erase the token object. - *token = yaml_token_t{} // [Go] Is this necessary? - - // No tokens after STREAM-END or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR { - return true - } - - // Ensure that the tokens queue contains enough tokens. - if !parser.token_available { - if !yaml_parser_fetch_more_tokens(parser) { - return false - } - } - - // Fetch the next token from the queue. - *token = parser.tokens[parser.tokens_head] - parser.tokens_head++ - parser.tokens_parsed++ - parser.token_available = false - - if token.typ == yaml_STREAM_END_TOKEN { - parser.stream_end_produced = true - } - return true -} - -// Set the scanner error and return false. -func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { - parser.error = yaml_SCANNER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = parser.mark - return false -} - -func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { - context := "while parsing a tag" - if directive { - context = "while parsing a %TAG directive" - } - return yaml_parser_set_scanner_error(parser, context, context_mark, problem) -} - -func trace(args ...interface{}) func() { - pargs := append([]interface{}{"+++"}, args...) - fmt.Println(pargs...) - pargs = append([]interface{}{"---"}, args...) - return func() { fmt.Println(pargs...) } -} - -// Ensure that the tokens queue contains at least one token which can be -// returned to the Parser. -func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { - // While we need more tokens to fetch, do it. - for { - // [Go] The comment parsing logic requires a lookahead of two tokens - // so that foot comments may be parsed in time of associating them - // with the tokens that are parsed before them, and also for line - // comments to be transformed into head comments in some edge cases. - if parser.tokens_head < len(parser.tokens)-2 { - // If a potential simple key is at the head position, we need to fetch - // the next token to disambiguate it. - head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] - if !ok { - break - } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { - return false - } else if !valid { - break - } - } - // Fetch the next token. - if !yaml_parser_fetch_next_token(parser) { - return false - } - } - - parser.token_available = true - return true -} - -// The dispatcher for token fetchers. -func yaml_parser_fetch_next_token(parser *yaml_parser_t) (ok bool) { - // Ensure that the buffer is initialized. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we just started scanning. Fetch STREAM-START then. - if !parser.stream_start_produced { - return yaml_parser_fetch_stream_start(parser) - } - - scan_mark := parser.mark - - // Eat whitespaces and comments until we reach the next token. - if !yaml_parser_scan_to_next_token(parser) { - return false - } - - // [Go] While unrolling indents, transform the head comments of prior - // indentation levels observed after scan_start into foot comments at - // the respective indexes. - - // Check the indentation level against the current column. - if !yaml_parser_unroll_indent(parser, parser.mark.column, scan_mark) { - return false - } - - // Ensure that the buffer contains at least 4 characters. 4 is the length - // of the longest indicators ('--- ' and '... '). - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - // Is it the end of the stream? - if is_z(parser.buffer, parser.buffer_pos) { - return yaml_parser_fetch_stream_end(parser) - } - - // Is it a directive? - if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { - return yaml_parser_fetch_directive(parser) - } - - buf := parser.buffer - pos := parser.buffer_pos - - // Is it the document start indicator? - if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) - } - - // Is it the document end indicator? - if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) - } - - comment_mark := parser.mark - if len(parser.tokens) > 0 && (parser.flow_level == 0 && buf[pos] == ':' || parser.flow_level > 0 && buf[pos] == ',') { - // Associate any following comments with the prior token. - comment_mark = parser.tokens[len(parser.tokens)-1].start_mark - } - defer func() { - if !ok { - return - } - if len(parser.tokens) > 0 && parser.tokens[len(parser.tokens)-1].typ == yaml_BLOCK_ENTRY_TOKEN { - // Sequence indicators alone have no line comments. It becomes - // a head comment for whatever follows. - return - } - if !yaml_parser_scan_line_comment(parser, comment_mark) { - ok = false - return - } - }() - - // Is it the flow sequence start indicator? - if buf[pos] == '[' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) - } - - // Is it the flow mapping start indicator? - if parser.buffer[parser.buffer_pos] == '{' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) - } - - // Is it the flow sequence end indicator? - if parser.buffer[parser.buffer_pos] == ']' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_SEQUENCE_END_TOKEN) - } - - // Is it the flow mapping end indicator? - if parser.buffer[parser.buffer_pos] == '}' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_MAPPING_END_TOKEN) - } - - // Is it the flow entry indicator? - if parser.buffer[parser.buffer_pos] == ',' { - return yaml_parser_fetch_flow_entry(parser) - } - - // Is it the block entry indicator? - if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { - return yaml_parser_fetch_block_entry(parser) - } - - // Is it the key indicator? - if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_key(parser) - } - - // Is it the value indicator? - if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_value(parser) - } - - // Is it an alias? - if parser.buffer[parser.buffer_pos] == '*' { - return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) - } - - // Is it an anchor? - if parser.buffer[parser.buffer_pos] == '&' { - return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) - } - - // Is it a tag? - if parser.buffer[parser.buffer_pos] == '!' { - return yaml_parser_fetch_tag(parser) - } - - // Is it a literal scalar? - if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, true) - } - - // Is it a folded scalar? - if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, false) - } - - // Is it a single-quoted scalar? - if parser.buffer[parser.buffer_pos] == '\'' { - return yaml_parser_fetch_flow_scalar(parser, true) - } - - // Is it a double-quoted scalar? - if parser.buffer[parser.buffer_pos] == '"' { - return yaml_parser_fetch_flow_scalar(parser, false) - } - - // Is it a plain scalar? - // - // A plain scalar may start with any non-blank characters except - // - // '-', '?', ':', ',', '[', ']', '{', '}', - // '#', '&', '*', '!', '|', '>', '\'', '\"', - // '%', '@', '`'. - // - // In the block context (and, for the '-' indicator, in the flow context - // too), it may also start with the characters - // - // '-', '?', ':' - // - // if it is followed by a non-space character. - // - // The last rule is more restrictive than the specification requires. - // [Go] TODO Make this logic more reasonable. - //switch parser.buffer[parser.buffer_pos] { - //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': - //} - if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || - parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || - parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || - (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level == 0 && - (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && - !is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_plain_scalar(parser) - } - - // If we don't determine the token type so far, it is an error. - return yaml_parser_set_scanner_error(parser, - "while scanning for the next token", parser.mark, - "found character that cannot start any token") -} - -func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { - if !simple_key.possible { - return false, true - } - - // The 1.2 specification says: - // - // "If the ? indicator is omitted, parsing needs to see past the - // implicit key to recognize it as such. To limit the amount of - // lookahead required, the “:” indicator must appear at most 1024 - // Unicode characters beyond the start of the key. In addition, the key - // is restricted to a single line." - // - if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { - // Check if the potential simple key to be removed is required. - if simple_key.required { - return false, yaml_parser_set_scanner_error(parser, - "while scanning a simple key", simple_key.mark, - "could not find expected ':'") - } - simple_key.possible = false - return false, true - } - return true, true -} - -// Check if a simple key may start at the current position and add it if -// needed. -func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { - // A simple key is required at the current position if the scanner is in - // the block context and the current column coincides with the indentation - // level. - - required := parser.flow_level == 0 && parser.indent == parser.mark.column - - // - // If the current position may start a simple key, save it. - // - if parser.simple_key_allowed { - simple_key := yaml_simple_key_t{ - possible: true, - required: required, - token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - mark: parser.mark, - } - - if !yaml_parser_remove_simple_key(parser) { - return false - } - parser.simple_keys[len(parser.simple_keys)-1] = simple_key - parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 - } - return true -} - -// Remove a potential simple key at the current flow level. -func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { - i := len(parser.simple_keys) - 1 - if parser.simple_keys[i].possible { - // If the key is required, it is an error. - if parser.simple_keys[i].required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", parser.simple_keys[i].mark, - "could not find expected ':'") - } - // Remove the key from the stack. - parser.simple_keys[i].possible = false - delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) - } - return true -} - -// max_flow_level limits the flow_level -const max_flow_level = 10000 - -// Increase the flow level and resize the simple key list if needed. -func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { - // Reset the simple key on the next level. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ - possible: false, - required: false, - token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - mark: parser.mark, - }) - - // Increase the flow level. - parser.flow_level++ - if parser.flow_level > max_flow_level { - return yaml_parser_set_scanner_error(parser, - "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, - fmt.Sprintf("exceeded max depth of %d", max_flow_level)) - } - return true -} - -// Decrease the flow level. -func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { - if parser.flow_level > 0 { - parser.flow_level-- - last := len(parser.simple_keys) - 1 - delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) - parser.simple_keys = parser.simple_keys[:last] - } - return true -} - -// max_indents limits the indents stack size -const max_indents = 10000 - -// Push the current indentation level to the stack and set the new level -// the current column is greater than the indentation level. In this case, -// append or insert the specified token into the token queue. -func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - if parser.indent < column { - // Push the current indentation level to the stack and set the new - // indentation level. - parser.indents = append(parser.indents, parser.indent) - parser.indent = column - if len(parser.indents) > max_indents { - return yaml_parser_set_scanner_error(parser, - "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, - fmt.Sprintf("exceeded max depth of %d", max_indents)) - } - - // Create a token and insert it into the queue. - token := yaml_token_t{ - typ: typ, - start_mark: mark, - end_mark: mark, - } - if number > -1 { - number -= parser.tokens_parsed - } - yaml_insert_token(parser, number, &token) - } - return true -} - -// Pop indentation levels from the indents stack until the current level -// becomes less or equal to the column. For each indentation level, append -// the BLOCK-END token. -func yaml_parser_unroll_indent(parser *yaml_parser_t, column int, scan_mark yaml_mark_t) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - block_mark := scan_mark - block_mark.index-- - - // Loop through the indentation levels in the stack. - for parser.indent > column { - - // [Go] Reposition the end token before potential following - // foot comments of parent blocks. For that, search - // backwards for recent comments that were at the same - // indent as the block that is ending now. - stop_index := block_mark.index - for i := len(parser.comments) - 1; i >= 0; i-- { - comment := &parser.comments[i] - - if comment.end_mark.index < stop_index { - // Don't go back beyond the start of the comment/whitespace scan, unless column < 0. - // If requested indent column is < 0, then the document is over and everything else - // is a foot anyway. - break - } - if comment.start_mark.column == parser.indent+1 { - // This is a good match. But maybe there's a former comment - // at that same indent level, so keep searching. - block_mark = comment.start_mark - } - - // While the end of the former comment matches with - // the start of the following one, we know there's - // nothing in between and scanning is still safe. - stop_index = comment.scan_mark.index - } - - // Create a token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_END_TOKEN, - start_mark: block_mark, - end_mark: block_mark, - } - yaml_insert_token(parser, -1, &token) - - // Pop the indentation level. - parser.indent = parser.indents[len(parser.indents)-1] - parser.indents = parser.indents[:len(parser.indents)-1] - } - return true -} - -// Initialize the scanner and produce the STREAM-START token. -func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { - - // Set the initial indentation. - parser.indent = -1 - - // Initialize the simple key stack. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) - - parser.simple_keys_by_tok = make(map[int]int) - - // A simple key is allowed at the beginning of the stream. - parser.simple_key_allowed = true - - // We have started. - parser.stream_start_produced = true - - // Create the STREAM-START token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_START_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - encoding: parser.encoding, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the STREAM-END token and shut down the scanner. -func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { - - // Force new line. - if parser.mark.column != 0 { - parser.mark.column = 0 - parser.mark.line++ - } - - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1, parser.mark) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the STREAM-END token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. -func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1, parser.mark) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. - token := yaml_token_t{} - if !yaml_parser_scan_directive(parser, &token) { - return false - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the DOCUMENT-START or DOCUMENT-END token. -func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1, parser.mark) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Consume the token. - start_mark := parser.mark - - skip(parser) - skip(parser) - skip(parser) - - end_mark := parser.mark - - // Create the DOCUMENT-START or DOCUMENT-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. -func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { - - // The indicators '[' and '{' may start a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // Increase the flow level. - if !yaml_parser_increase_flow_level(parser) { - return false - } - - // A simple key may follow the indicators '[' and '{'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. -func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset any potential simple key on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Decrease the flow level. - if !yaml_parser_decrease_flow_level(parser) { - return false - } - - // No simple keys after the indicators ']' and '}'. - parser.simple_key_allowed = false - - // Consume the token. - - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-ENTRY token. -func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after ','. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_FLOW_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the BLOCK-ENTRY token. -func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { - // Check if the scanner is in the block context. - if parser.flow_level == 0 { - // Check if we are allowed to start a new entry. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "block sequence entries are not allowed in this context") - } - // Add the BLOCK-SEQUENCE-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { - return false - } - } else { - // It is an error for the '-' indicator to occur in the flow context, - // but we let the Parser detect and report about it because the Parser - // is able to point to the context. - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '-'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the BLOCK-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the KEY token. -func yaml_parser_fetch_key(parser *yaml_parser_t) bool { - - // In the block context, additional checks are required. - if parser.flow_level == 0 { - // Check if we are allowed to start a new key (not nessesary simple). - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping keys are not allowed in this context") - } - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '?' in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the KEY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the VALUE token. -func yaml_parser_fetch_value(parser *yaml_parser_t) bool { - - simple_key := &parser.simple_keys[len(parser.simple_keys)-1] - - // Have we found a simple key? - if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { - return false - - } else if valid { - - // Create the KEY token and insert it into the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: simple_key.mark, - end_mark: simple_key.mark, - } - yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) - - // In the block context, we may need to add the BLOCK-MAPPING-START token. - if !yaml_parser_roll_indent(parser, simple_key.mark.column, - simple_key.token_number, - yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { - return false - } - - // Remove the simple key. - simple_key.possible = false - delete(parser.simple_keys_by_tok, simple_key.token_number) - - // A simple key cannot follow another simple key. - parser.simple_key_allowed = false - - } else { - // The ':' indicator follows a complex key. - - // In the block context, extra checks are required. - if parser.flow_level == 0 { - - // Check if we are allowed to start a complex value. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping values are not allowed in this context") - } - - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Simple keys after ':' are allowed in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - } - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the VALUE token and append it to the queue. - token := yaml_token_t{ - typ: yaml_VALUE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the ALIAS or ANCHOR token. -func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // An anchor or an alias could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow an anchor or an alias. - parser.simple_key_allowed = false - - // Create the ALIAS or ANCHOR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_anchor(parser, &token, typ) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the TAG token. -func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { - // A tag could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a tag. - parser.simple_key_allowed = false - - // Create the TAG token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_tag(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. -func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { - // Remove any potential simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // A simple key may follow a block scalar. - parser.simple_key_allowed = true - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_block_scalar(parser, &token, literal) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. -func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_flow_scalar(parser, &token, single) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,plain) token. -func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_plain_scalar(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Eat whitespaces and comments until the next token is found. -func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { - - scan_mark := parser.mark - - // Until the next token is not found. - for { - // Allow the BOM mark to start a line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { - skip(parser) - } - - // Eat whitespaces. - // Tabs are allowed: - // - in the flow context - // - in the block context, but not at the beginning of the line or - // after '-', '?', or ':' (complex value). - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if we just had a line comment under a sequence entry that - // looks more like a header to the following content. Similar to this: - // - // - # The comment - // - Some data - // - // If so, transform the line comment to a head comment and reposition. - if len(parser.comments) > 0 && len(parser.tokens) > 1 { - tokenA := parser.tokens[len(parser.tokens)-2] - tokenB := parser.tokens[len(parser.tokens)-1] - comment := &parser.comments[len(parser.comments)-1] - if tokenA.typ == yaml_BLOCK_SEQUENCE_START_TOKEN && tokenB.typ == yaml_BLOCK_ENTRY_TOKEN && len(comment.line) > 0 && !is_break(parser.buffer, parser.buffer_pos) { - // If it was in the prior line, reposition so it becomes a - // header of the follow up token. Otherwise, keep it in place - // so it becomes a header of the former. - comment.head = comment.line - comment.line = nil - if comment.start_mark.line == parser.mark.line-1 { - comment.token_mark = parser.mark - } - } - } - - // Eat a comment until a line break. - if parser.buffer[parser.buffer_pos] == '#' { - if !yaml_parser_scan_comments(parser, scan_mark) { - return false - } - } - - // If it is a line break, eat it. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - - // In the block context, a new line may start a simple key. - if parser.flow_level == 0 { - parser.simple_key_allowed = true - } - } else { - break // We have found a token. - } - } - - return true -} - -// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// -func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { - // Eat '%'. - start_mark := parser.mark - skip(parser) - - // Scan the directive name. - var name []byte - if !yaml_parser_scan_directive_name(parser, start_mark, &name) { - return false - } - - // Is it a YAML directive? - if bytes.Equal(name, []byte("YAML")) { - // Scan the VERSION directive value. - var major, minor int8 - if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { - return false - } - end_mark := parser.mark - - // Create a VERSION-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_VERSION_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - major: major, - minor: minor, - } - - // Is it a TAG directive? - } else if bytes.Equal(name, []byte("TAG")) { - // Scan the TAG directive value. - var handle, prefix []byte - if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { - return false - } - end_mark := parser.mark - - // Create a TAG-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_TAG_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - prefix: prefix, - } - - // Unknown directive. - } else { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unknown directive name") - return false - } - - // Eat the rest of the line including any comments. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - if parser.buffer[parser.buffer_pos] == '#' { - // [Go] Discard this inline comment for the time being. - //if !yaml_parser_scan_line_comment(parser, start_mark) { - // return false - //} - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - return true -} - -// Scan the directive name. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^ -// -func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { - // Consume the directive name. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - var s []byte - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the name is empty. - if len(s) == 0 { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "could not find expected directive name") - return false - } - - // Check for an blank character after the name. - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unexpected non-alphabetical character") - return false - } - *name = s - return true -} - -// Scan the value of VERSION-DIRECTIVE. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^^^ -func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the major version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { - return false - } - - // Eat '.'. - if parser.buffer[parser.buffer_pos] != '.' { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected digit or '.' character") - } - - skip(parser) - - // Consume the minor version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { - return false - } - return true -} - -const max_number_length = 2 - -// Scan the version number of VERSION-DIRECTIVE. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^ -// %YAML 1.1 # a comment \n -// ^ -func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { - - // Repeat while the next character is digit. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var value, length int8 - for is_digit(parser.buffer, parser.buffer_pos) { - // Check if the number is too long. - length++ - if length > max_number_length { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "found extremely long version number") - } - value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the number was present. - if length == 0 { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected version number") - } - *number = value - return true -} - -// Scan the value of a TAG-DIRECTIVE token. -// -// Scope: -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// -func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { - var handle_value, prefix_value []byte - - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a handle. - if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { - return false - } - - // Expect a whitespace. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blank(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace") - return false - } - - // Eat whitespaces. - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a prefix. - if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { - return false - } - - // Expect a whitespace or line break. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace or line break") - return false - } - - *handle = handle_value - *prefix = prefix_value - return true -} - -func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { - var s []byte - - // Eat the indicator character. - start_mark := parser.mark - skip(parser) - - // Consume the value. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - end_mark := parser.mark - - /* - * Check if length of the anchor is greater than 0 and it is followed by - * a whitespace character or one of the indicators: - * - * '?', ':', ',', ']', '}', '%', '@', '`'. - */ - - if len(s) == 0 || - !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || - parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '`') { - context := "while scanning an alias" - if typ == yaml_ANCHOR_TOKEN { - context = "while scanning an anchor" - } - yaml_parser_set_scanner_error(parser, context, start_mark, - "did not find expected alphabetic or numeric character") - return false - } - - // Create a token. - *token = yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - value: s, - } - - return true -} - -/* - * Scan a TAG token. - */ - -func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { - var handle, suffix []byte - - start_mark := parser.mark - - // Check if the tag is in the canonical form. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - if parser.buffer[parser.buffer_pos+1] == '<' { - // Keep the handle as '' - - // Eat '!<' - skip(parser) - skip(parser) - - // Consume the tag value. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - - // Check for '>' and eat it. - if parser.buffer[parser.buffer_pos] != '>' { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find the expected '>'") - return false - } - - skip(parser) - } else { - // The tag has either the '!suffix' or the '!handle!suffix' form. - - // First, try to scan a handle. - if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { - return false - } - - // Check if it is, indeed, handle. - if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { - // Scan the suffix now. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - } else { - // It wasn't a handle after all. Scan the rest of the tag. - if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { - return false - } - - // Set the handle to '!'. - handle = []byte{'!'} - - // A special case: the '!' tag. Set the handle to '' and the - // suffix to '!'. - if len(suffix) == 0 { - handle, suffix = suffix, handle - } - } - } - - // Check the character which ends the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find expected whitespace or line break") - return false - } - - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_TAG_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - suffix: suffix, - } - return true -} - -// Scan a tag handle. -func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { - // Check the initial '!' character. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] != '!' { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - - var s []byte - - // Copy the '!' character. - s = read(parser, s) - - // Copy all subsequent alphabetical and numerical characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the trailing character is '!' and copy it. - if parser.buffer[parser.buffer_pos] == '!' { - s = read(parser, s) - } else { - // It's either the '!' tag or not really a tag handle. If it's a %TAG - // directive, it's an error. If it's a tag token, it must be a part of URI. - if directive && string(s) != "!" { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - } - - *handle = s - return true -} - -// Scan a tag. -func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { - //size_t length = head ? strlen((char *)head) : 0 - var s []byte - hasTag := len(head) > 0 - - // Copy the head if needed. - // - // Note that we don't copy the leading '!' character. - if len(head) > 1 { - s = append(s, head[1:]...) - } - - // Scan the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // The set of characters that may appear in URI is as follows: - // - // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', - // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', - // '%'. - // [Go] TODO Convert this into more reasonable logic. - for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || - parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || - parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || - parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || - parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || - parser.buffer[parser.buffer_pos] == '%' { - // Check if it is a URI-escape sequence. - if parser.buffer[parser.buffer_pos] == '%' { - if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { - return false - } - } else { - s = read(parser, s) - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - hasTag = true - } - - if !hasTag { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected tag URI") - return false - } - *uri = s - return true -} - -// Decode an URI-escape sequence corresponding to a single UTF-8 character. -func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { - - // Decode the required number of characters. - w := 1024 - for w > 0 { - // Check for a URI-escaped octet. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - - if !(parser.buffer[parser.buffer_pos] == '%' && - is_hex(parser.buffer, parser.buffer_pos+1) && - is_hex(parser.buffer, parser.buffer_pos+2)) { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find URI escaped octet") - } - - // Get the octet. - octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) - - // If it is the leading octet, determine the length of the UTF-8 sequence. - if w == 1024 { - w = width(octet) - if w == 0 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect leading UTF-8 octet") - } - } else { - // Check if the trailing octet is correct. - if octet&0xC0 != 0x80 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect trailing UTF-8 octet") - } - } - - // Copy the octet and move the pointers. - *s = append(*s, octet) - skip(parser) - skip(parser) - skip(parser) - w-- - } - return true -} - -// Scan a block scalar. -func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { - // Eat the indicator '|' or '>'. - start_mark := parser.mark - skip(parser) - - // Scan the additional block scalar indicators. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check for a chomping indicator. - var chomping, increment int - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - // Set the chomping method and eat the indicator. - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - - // Check for an indentation indicator. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_digit(parser.buffer, parser.buffer_pos) { - // Check that the indentation is greater than 0. - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - - // Get the indentation level and eat the indicator. - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - } - - } else if is_digit(parser.buffer, parser.buffer_pos) { - // Do the same as above, but in the opposite order. - - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - } - } - - // Eat whitespaces and comments to the end of the line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.buffer[parser.buffer_pos] == '#' { - if !yaml_parser_scan_line_comment(parser, start_mark) { - return false - } - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - end_mark := parser.mark - - // Set the indentation level if it was specified. - var indent int - if increment > 0 { - if parser.indent >= 0 { - indent = parser.indent + increment - } else { - indent = increment - } - } - - // Scan the leading line breaks and determine the indentation level if needed. - var s, leading_break, trailing_breaks []byte - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - - // Scan the block scalar content. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var leading_blank, trailing_blank bool - for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { - // We are at the beginning of a non-empty line. - - // Is it a trailing whitespace? - trailing_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Check if we need to fold the leading line break. - if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { - // Do we need to join the lines by space? - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } - } else { - s = append(s, leading_break...) - } - leading_break = leading_break[:0] - - // Append the remaining line breaks. - s = append(s, trailing_breaks...) - trailing_breaks = trailing_breaks[:0] - - // Is it a leading whitespace? - leading_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Consume the current line. - for !is_breakz(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - leading_break = read_line(parser, leading_break) - - // Eat the following indentation spaces and line breaks. - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - } - - // Chomp the tail. - if chomping != -1 { - s = append(s, leading_break...) - } - if chomping == 1 { - s = append(s, trailing_breaks...) - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_LITERAL_SCALAR_STYLE, - } - if !literal { - token.style = yaml_FOLDED_SCALAR_STYLE - } - return true -} - -// Scan indentation spaces and line breaks for a block scalar. Determine the -// indentation level if needed. -func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { - *end_mark = parser.mark - - // Eat the indentation spaces and line breaks. - max_indent := 0 - for { - // Eat the indentation spaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.mark.column > max_indent { - max_indent = parser.mark.column - } - - // Check for a tab character messing the indentation. - if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { - return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found a tab character where an indentation space is expected") - } - - // Have we found a non-empty line? - if !is_break(parser.buffer, parser.buffer_pos) { - break - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - // [Go] Should really be returning breaks instead. - *breaks = read_line(parser, *breaks) - *end_mark = parser.mark - } - - // Determine the indentation level if needed. - if *indent == 0 { - *indent = max_indent - if *indent < parser.indent+1 { - *indent = parser.indent + 1 - } - if *indent < 1 { - *indent = 1 - } - } - return true -} - -// Scan a quoted scalar. -func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { - // Eat the left quote. - start_mark := parser.mark - skip(parser) - - // Consume the content of the quoted scalar. - var s, leading_break, trailing_breaks, whitespaces []byte - for { - // Check that there are no document indicators at the beginning of the line. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected document indicator") - return false - } - - // Check for EOF. - if is_z(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected end of stream") - return false - } - - // Consume non-blank characters. - leading_blanks := false - for !is_blankz(parser.buffer, parser.buffer_pos) { - if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { - // Is is an escaped single quote. - s = append(s, '\'') - skip(parser) - skip(parser) - - } else if single && parser.buffer[parser.buffer_pos] == '\'' { - // It is a right single quote. - break - } else if !single && parser.buffer[parser.buffer_pos] == '"' { - // It is a right double quote. - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { - // It is an escaped line break. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - skip(parser) - skip_line(parser) - leading_blanks = true - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' { - // It is an escape sequence. - code_length := 0 - - // Check the escape character. - switch parser.buffer[parser.buffer_pos+1] { - case '0': - s = append(s, 0) - case 'a': - s = append(s, '\x07') - case 'b': - s = append(s, '\x08') - case 't', '\t': - s = append(s, '\x09') - case 'n': - s = append(s, '\x0A') - case 'v': - s = append(s, '\x0B') - case 'f': - s = append(s, '\x0C') - case 'r': - s = append(s, '\x0D') - case 'e': - s = append(s, '\x1B') - case ' ': - s = append(s, '\x20') - case '"': - s = append(s, '"') - case '\'': - s = append(s, '\'') - case '\\': - s = append(s, '\\') - case 'N': // NEL (#x85) - s = append(s, '\xC2') - s = append(s, '\x85') - case '_': // #xA0 - s = append(s, '\xC2') - s = append(s, '\xA0') - case 'L': // LS (#x2028) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA8') - case 'P': // PS (#x2029) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA9') - case 'x': - code_length = 2 - case 'u': - code_length = 4 - case 'U': - code_length = 8 - default: - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found unknown escape character") - return false - } - - skip(parser) - skip(parser) - - // Consume an arbitrary escape code. - if code_length > 0 { - var value int - - // Scan the character value. - if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { - return false - } - for k := 0; k < code_length; k++ { - if !is_hex(parser.buffer, parser.buffer_pos+k) { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "did not find expected hexdecimal number") - return false - } - value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) - } - - // Check the value and write the character. - if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found invalid Unicode character escape code") - return false - } - if value <= 0x7F { - s = append(s, byte(value)) - } else if value <= 0x7FF { - s = append(s, byte(0xC0+(value>>6))) - s = append(s, byte(0x80+(value&0x3F))) - } else if value <= 0xFFFF { - s = append(s, byte(0xE0+(value>>12))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } else { - s = append(s, byte(0xF0+(value>>18))) - s = append(s, byte(0x80+((value>>12)&0x3F))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } - - // Advance the pointer. - for k := 0; k < code_length; k++ { - skip(parser) - } - } - } else { - // It is a non-escaped non-blank character. - s = read(parser, s) - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we are at the end of the scalar. - if single { - if parser.buffer[parser.buffer_pos] == '\'' { - break - } - } else { - if parser.buffer[parser.buffer_pos] == '"' { - break - } - } - - // Consume blank characters. - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Join the whitespaces or fold line breaks. - if leading_blanks { - // Do we need to fold line breaks? - if len(leading_break) > 0 && leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Eat the right quote. - skip(parser) - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_SINGLE_QUOTED_SCALAR_STYLE, - } - if !single { - token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - return true -} - -// Scan a plain scalar. -func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { - - var s, leading_break, trailing_breaks, whitespaces []byte - var leading_blanks bool - var indent = parser.indent + 1 - - start_mark := parser.mark - end_mark := parser.mark - - // Consume the content of the plain scalar. - for { - // Check for a document indicator. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - break - } - - // Check for a comment. - if parser.buffer[parser.buffer_pos] == '#' { - break - } - - // Consume non-blank characters. - for !is_blankz(parser.buffer, parser.buffer_pos) { - - // Check for indicators that may end a plain scalar. - if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level > 0 && - (parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}')) { - break - } - - // Check if we need to join whitespaces and breaks. - if leading_blanks || len(whitespaces) > 0 { - if leading_blanks { - // Do we need to fold line breaks? - if leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - leading_blanks = false - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Copy the character. - s = read(parser, s) - - end_mark = parser.mark - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - // Is it the end? - if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { - break - } - - // Consume blank characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - - // Check for tab characters that abuse indentation. - if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", - start_mark, "found a tab character that violates indentation") - return false - } - - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check indentation level. - if parser.flow_level == 0 && parser.mark.column < indent { - break - } - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_PLAIN_SCALAR_STYLE, - } - - // Note that we change the 'simple_key_allowed' flag. - if leading_blanks { - parser.simple_key_allowed = true - } - return true -} - -func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t) bool { - if parser.newlines > 0 { - return true - } - - var start_mark yaml_mark_t - var text []byte - - for peek := 0; peek < 512; peek++ { - if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { - break - } - if is_blank(parser.buffer, parser.buffer_pos+peek) { - continue - } - if parser.buffer[parser.buffer_pos+peek] == '#' { - seen := parser.mark.index+peek - for { - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_breakz(parser.buffer, parser.buffer_pos) { - if parser.mark.index >= seen { - break - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } else if parser.mark.index >= seen { - if len(text) == 0 { - start_mark = parser.mark - } - text = read(parser, text) - } else { - skip(parser) - } - } - } - break - } - if len(text) > 0 { - parser.comments = append(parser.comments, yaml_comment_t{ - token_mark: token_mark, - start_mark: start_mark, - line: text, - }) - } - return true -} - -func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) bool { - token := parser.tokens[len(parser.tokens)-1] - - if token.typ == yaml_FLOW_ENTRY_TOKEN && len(parser.tokens) > 1 { - token = parser.tokens[len(parser.tokens)-2] - } - - var token_mark = token.start_mark - var start_mark yaml_mark_t - var next_indent = parser.indent - if next_indent < 0 { - next_indent = 0 - } - - var recent_empty = false - var first_empty = parser.newlines <= 1 - - var line = parser.mark.line - var column = parser.mark.column - - var text []byte - - // The foot line is the place where a comment must start to - // still be considered as a foot of the prior content. - // If there's some content in the currently parsed line, then - // the foot is the line below it. - var foot_line = -1 - if scan_mark.line > 0 { - foot_line = parser.mark.line-parser.newlines+1 - if parser.newlines == 0 && parser.mark.column > 1 { - foot_line++ - } - } - - var peek = 0 - for ; peek < 512; peek++ { - if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { - break - } - column++ - if is_blank(parser.buffer, parser.buffer_pos+peek) { - continue - } - c := parser.buffer[parser.buffer_pos+peek] - var close_flow = parser.flow_level > 0 && (c == ']' || c == '}') - if close_flow || is_breakz(parser.buffer, parser.buffer_pos+peek) { - // Got line break or terminator. - if close_flow || !recent_empty { - if close_flow || first_empty && (start_mark.line == foot_line && token.typ != yaml_VALUE_TOKEN || start_mark.column-1 < next_indent) { - // This is the first empty line and there were no empty lines before, - // so this initial part of the comment is a foot of the prior token - // instead of being a head for the following one. Split it up. - // Alternatively, this might also be the last comment inside a flow - // scope, so it must be a footer. - if len(text) > 0 { - if start_mark.column-1 < next_indent { - // If dedented it's unrelated to the prior token. - token_mark = start_mark - } - parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, - token_mark: token_mark, - start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, - foot: text, - }) - scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} - token_mark = scan_mark - text = nil - } - } else { - if len(text) > 0 && parser.buffer[parser.buffer_pos+peek] != 0 { - text = append(text, '\n') - } - } - } - if !is_break(parser.buffer, parser.buffer_pos+peek) { - break - } - first_empty = false - recent_empty = true - column = 0 - line++ - continue - } - - if len(text) > 0 && (close_flow || column-1 < next_indent && column != start_mark.column) { - // The comment at the different indentation is a foot of the - // preceding data rather than a head of the upcoming one. - parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, - token_mark: token_mark, - start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, - foot: text, - }) - scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} - token_mark = scan_mark - text = nil - } - - if parser.buffer[parser.buffer_pos+peek] != '#' { - break - } - - if len(text) == 0 { - start_mark = yaml_mark_t{parser.mark.index + peek, line, column} - } else { - text = append(text, '\n') - } - - recent_empty = false - - // Consume until after the consumed comment line. - seen := parser.mark.index+peek - for { - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_breakz(parser.buffer, parser.buffer_pos) { - if parser.mark.index >= seen { - break - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } else if parser.mark.index >= seen { - text = read(parser, text) - } else { - skip(parser) - } - } - - peek = 0 - column = 0 - line = parser.mark.line - next_indent = parser.indent - if next_indent < 0 { - next_indent = 0 - } - } - - if len(text) > 0 { - parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, - token_mark: start_mark, - start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek - 1, line, column}, - head: text, - }) - } - return true -} diff --git a/api/vendor/gopkg.in/yaml.v3/sorter.go b/api/vendor/gopkg.in/yaml.v3/sorter.go deleted file mode 100644 index 9210ece7e972..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/sorter.go +++ /dev/null @@ -1,134 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package yaml - -import ( - "reflect" - "unicode" -) - -type keyList []reflect.Value - -func (l keyList) Len() int { return len(l) } -func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } -func (l keyList) Less(i, j int) bool { - a := l[i] - b := l[j] - ak := a.Kind() - bk := b.Kind() - for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { - a = a.Elem() - ak = a.Kind() - } - for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { - b = b.Elem() - bk = b.Kind() - } - af, aok := keyFloat(a) - bf, bok := keyFloat(b) - if aok && bok { - if af != bf { - return af < bf - } - if ak != bk { - return ak < bk - } - return numLess(a, b) - } - if ak != reflect.String || bk != reflect.String { - return ak < bk - } - ar, br := []rune(a.String()), []rune(b.String()) - digits := false - for i := 0; i < len(ar) && i < len(br); i++ { - if ar[i] == br[i] { - digits = unicode.IsDigit(ar[i]) - continue - } - al := unicode.IsLetter(ar[i]) - bl := unicode.IsLetter(br[i]) - if al && bl { - return ar[i] < br[i] - } - if al || bl { - if digits { - return al - } else { - return bl - } - } - var ai, bi int - var an, bn int64 - if ar[i] == '0' || br[i] == '0' { - for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { - if ar[j] != '0' { - an = 1 - bn = 1 - break - } - } - } - for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { - an = an*10 + int64(ar[ai]-'0') - } - for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { - bn = bn*10 + int64(br[bi]-'0') - } - if an != bn { - return an < bn - } - if ai != bi { - return ai < bi - } - return ar[i] < br[i] - } - return len(ar) < len(br) -} - -// keyFloat returns a float value for v if it is a number/bool -// and whether it is a number/bool or not. -func keyFloat(v reflect.Value) (f float64, ok bool) { - switch v.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return float64(v.Int()), true - case reflect.Float32, reflect.Float64: - return v.Float(), true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return float64(v.Uint()), true - case reflect.Bool: - if v.Bool() { - return 1, true - } - return 0, true - } - return 0, false -} - -// numLess returns whether a < b. -// a and b must necessarily have the same kind. -func numLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return a.Int() < b.Int() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Bool: - return !a.Bool() && b.Bool() - } - panic("not a number") -} diff --git a/api/vendor/gopkg.in/yaml.v3/writerc.go b/api/vendor/gopkg.in/yaml.v3/writerc.go deleted file mode 100644 index b8a116bf9a22..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/writerc.go +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package yaml - -// Set the writer error and return false. -func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_WRITER_ERROR - emitter.problem = problem - return false -} - -// Flush the output buffer. -func yaml_emitter_flush(emitter *yaml_emitter_t) bool { - if emitter.write_handler == nil { - panic("write handler not set") - } - - // Check if the buffer is empty. - if emitter.buffer_pos == 0 { - return true - } - - if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { - return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) - } - emitter.buffer_pos = 0 - return true -} diff --git a/api/vendor/gopkg.in/yaml.v3/yaml.go b/api/vendor/gopkg.in/yaml.v3/yaml.go deleted file mode 100644 index 8cec6da48d3e..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/yaml.go +++ /dev/null @@ -1,698 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package yaml implements YAML support for the Go language. -// -// Source code and other details for the project are available at GitHub: -// -// https://github.com/go-yaml/yaml -// -package yaml - -import ( - "errors" - "fmt" - "io" - "reflect" - "strings" - "sync" - "unicode/utf8" -) - -// The Unmarshaler interface may be implemented by types to customize their -// behavior when being unmarshaled from a YAML document. -type Unmarshaler interface { - UnmarshalYAML(value *Node) error -} - -type obsoleteUnmarshaler interface { - UnmarshalYAML(unmarshal func(interface{}) error) error -} - -// The Marshaler interface may be implemented by types to customize their -// behavior when being marshaled into a YAML document. The returned value -// is marshaled in place of the original value implementing Marshaler. -// -// If an error is returned by MarshalYAML, the marshaling procedure stops -// and returns with the provided error. -type Marshaler interface { - MarshalYAML() (interface{}, error) -} - -// Unmarshal decodes the first document found within the in byte slice -// and assigns decoded values into the out value. -// -// Maps and pointers (to a struct, string, int, etc) are accepted as out -// values. If an internal pointer within a struct is not initialized, -// the yaml package will initialize it if necessary for unmarshalling -// the provided data. The out parameter must not be nil. -// -// The type of the decoded values should be compatible with the respective -// values in out. If one or more values cannot be decoded due to a type -// mismatches, decoding continues partially until the end of the YAML -// content, and a *yaml.TypeError is returned with details for all -// missed values. -// -// Struct fields are only unmarshalled if they are exported (have an -// upper case first letter), and are unmarshalled using the field name -// lowercased as the default key. Custom keys may be defined via the -// "yaml" name in the field tag: the content preceding the first comma -// is used as the key, and the following comma-separated options are -// used to tweak the marshalling process (see Marshal). -// Conflicting names result in a runtime error. -// -// For example: -// -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// var t T -// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) -// -// See the documentation of Marshal for the format of tags and a list of -// supported tag options. -// -func Unmarshal(in []byte, out interface{}) (err error) { - return unmarshal(in, out, false) -} - -// A Decoder reads and decodes YAML values from an input stream. -type Decoder struct { - parser *parser - knownFields bool -} - -// NewDecoder returns a new decoder that reads from r. -// -// The decoder introduces its own buffering and may read -// data from r beyond the YAML values requested. -func NewDecoder(r io.Reader) *Decoder { - return &Decoder{ - parser: newParserFromReader(r), - } -} - -// KnownFields ensures that the keys in decoded mappings to -// exist as fields in the struct being decoded into. -func (dec *Decoder) KnownFields(enable bool) { - dec.knownFields = enable -} - -// Decode reads the next YAML-encoded value from its input -// and stores it in the value pointed to by v. -// -// See the documentation for Unmarshal for details about the -// conversion of YAML into a Go value. -func (dec *Decoder) Decode(v interface{}) (err error) { - d := newDecoder() - d.knownFields = dec.knownFields - defer handleErr(&err) - node := dec.parser.parse() - if node == nil { - return io.EOF - } - out := reflect.ValueOf(v) - if out.Kind() == reflect.Ptr && !out.IsNil() { - out = out.Elem() - } - d.unmarshal(node, out) - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -// Decode decodes the node and stores its data into the value pointed to by v. -// -// See the documentation for Unmarshal for details about the -// conversion of YAML into a Go value. -func (n *Node) Decode(v interface{}) (err error) { - d := newDecoder() - defer handleErr(&err) - out := reflect.ValueOf(v) - if out.Kind() == reflect.Ptr && !out.IsNil() { - out = out.Elem() - } - d.unmarshal(n, out) - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -func unmarshal(in []byte, out interface{}, strict bool) (err error) { - defer handleErr(&err) - d := newDecoder() - p := newParser(in) - defer p.destroy() - node := p.parse() - if node != nil { - v := reflect.ValueOf(out) - if v.Kind() == reflect.Ptr && !v.IsNil() { - v = v.Elem() - } - d.unmarshal(node, v) - } - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -// Marshal serializes the value provided into a YAML document. The structure -// of the generated document will reflect the structure of the value itself. -// Maps and pointers (to struct, string, int, etc) are accepted as the in value. -// -// Struct fields are only marshalled if they are exported (have an upper case -// first letter), and are marshalled using the field name lowercased as the -// default key. Custom keys may be defined via the "yaml" name in the field -// tag: the content preceding the first comma is used as the key, and the -// following comma-separated options are used to tweak the marshalling process. -// Conflicting names result in a runtime error. -// -// The field tag format accepted is: -// -// `(...) yaml:"[][,[,]]" (...)` -// -// The following flags are currently supported: -// -// omitempty Only include the field if it's not set to the zero -// value for the type or to empty slices or maps. -// Zero valued structs will be omitted if all their public -// fields are zero, unless they implement an IsZero -// method (see the IsZeroer interface type), in which -// case the field will be excluded if IsZero returns true. -// -// flow Marshal using a flow style (useful for structs, -// sequences and maps). -// -// inline Inline the field, which must be a struct or a map, -// causing all of its fields or keys to be processed as if -// they were part of the outer struct. For maps, keys must -// not conflict with the yaml keys of other struct fields. -// -// In addition, if the key is "-", the field is ignored. -// -// For example: -// -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" -// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" -// -func Marshal(in interface{}) (out []byte, err error) { - defer handleErr(&err) - e := newEncoder() - defer e.destroy() - e.marshalDoc("", reflect.ValueOf(in)) - e.finish() - out = e.out - return -} - -// An Encoder writes YAML values to an output stream. -type Encoder struct { - encoder *encoder -} - -// NewEncoder returns a new encoder that writes to w. -// The Encoder should be closed after use to flush all data -// to w. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{ - encoder: newEncoderWithWriter(w), - } -} - -// Encode writes the YAML encoding of v to the stream. -// If multiple items are encoded to the stream, the -// second and subsequent document will be preceded -// with a "---" document separator, but the first will not. -// -// See the documentation for Marshal for details about the conversion of Go -// values to YAML. -func (e *Encoder) Encode(v interface{}) (err error) { - defer handleErr(&err) - e.encoder.marshalDoc("", reflect.ValueOf(v)) - return nil -} - -// Encode encodes value v and stores its representation in n. -// -// See the documentation for Marshal for details about the -// conversion of Go values into YAML. -func (n *Node) Encode(v interface{}) (err error) { - defer handleErr(&err) - e := newEncoder() - defer e.destroy() - e.marshalDoc("", reflect.ValueOf(v)) - e.finish() - p := newParser(e.out) - p.textless = true - defer p.destroy() - doc := p.parse() - *n = *doc.Content[0] - return nil -} - -// SetIndent changes the used indentation used when encoding. -func (e *Encoder) SetIndent(spaces int) { - if spaces < 0 { - panic("yaml: cannot indent to a negative number of spaces") - } - e.encoder.indent = spaces -} - -// Close closes the encoder by writing any remaining data. -// It does not write a stream terminating string "...". -func (e *Encoder) Close() (err error) { - defer handleErr(&err) - e.encoder.finish() - return nil -} - -func handleErr(err *error) { - if v := recover(); v != nil { - if e, ok := v.(yamlError); ok { - *err = e.err - } else { - panic(v) - } - } -} - -type yamlError struct { - err error -} - -func fail(err error) { - panic(yamlError{err}) -} - -func failf(format string, args ...interface{}) { - panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) -} - -// A TypeError is returned by Unmarshal when one or more fields in -// the YAML document cannot be properly decoded into the requested -// types. When this error is returned, the value is still -// unmarshaled partially. -type TypeError struct { - Errors []string -} - -func (e *TypeError) Error() string { - return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) -} - -type Kind uint32 - -const ( - DocumentNode Kind = 1 << iota - SequenceNode - MappingNode - ScalarNode - AliasNode -) - -type Style uint32 - -const ( - TaggedStyle Style = 1 << iota - DoubleQuotedStyle - SingleQuotedStyle - LiteralStyle - FoldedStyle - FlowStyle -) - -// Node represents an element in the YAML document hierarchy. While documents -// are typically encoded and decoded into higher level types, such as structs -// and maps, Node is an intermediate representation that allows detailed -// control over the content being decoded or encoded. -// -// It's worth noting that although Node offers access into details such as -// line numbers, colums, and comments, the content when re-encoded will not -// have its original textual representation preserved. An effort is made to -// render the data plesantly, and to preserve comments near the data they -// describe, though. -// -// Values that make use of the Node type interact with the yaml package in the -// same way any other type would do, by encoding and decoding yaml data -// directly or indirectly into them. -// -// For example: -// -// var person struct { -// Name string -// Address yaml.Node -// } -// err := yaml.Unmarshal(data, &person) -// -// Or by itself: -// -// var person Node -// err := yaml.Unmarshal(data, &person) -// -type Node struct { - // Kind defines whether the node is a document, a mapping, a sequence, - // a scalar value, or an alias to another node. The specific data type of - // scalar nodes may be obtained via the ShortTag and LongTag methods. - Kind Kind - - // Style allows customizing the apperance of the node in the tree. - Style Style - - // Tag holds the YAML tag defining the data type for the value. - // When decoding, this field will always be set to the resolved tag, - // even when it wasn't explicitly provided in the YAML content. - // When encoding, if this field is unset the value type will be - // implied from the node properties, and if it is set, it will only - // be serialized into the representation if TaggedStyle is used or - // the implicit tag diverges from the provided one. - Tag string - - // Value holds the unescaped and unquoted represenation of the value. - Value string - - // Anchor holds the anchor name for this node, which allows aliases to point to it. - Anchor string - - // Alias holds the node that this alias points to. Only valid when Kind is AliasNode. - Alias *Node - - // Content holds contained nodes for documents, mappings, and sequences. - Content []*Node - - // HeadComment holds any comments in the lines preceding the node and - // not separated by an empty line. - HeadComment string - - // LineComment holds any comments at the end of the line where the node is in. - LineComment string - - // FootComment holds any comments following the node and before empty lines. - FootComment string - - // Line and Column hold the node position in the decoded YAML text. - // These fields are not respected when encoding the node. - Line int - Column int -} - -// IsZero returns whether the node has all of its fields unset. -func (n *Node) IsZero() bool { - return n.Kind == 0 && n.Style == 0 && n.Tag == "" && n.Value == "" && n.Anchor == "" && n.Alias == nil && n.Content == nil && - n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" && n.Line == 0 && n.Column == 0 -} - - -// LongTag returns the long form of the tag that indicates the data type for -// the node. If the Tag field isn't explicitly defined, one will be computed -// based on the node properties. -func (n *Node) LongTag() string { - return longTag(n.ShortTag()) -} - -// ShortTag returns the short form of the YAML tag that indicates data type for -// the node. If the Tag field isn't explicitly defined, one will be computed -// based on the node properties. -func (n *Node) ShortTag() string { - if n.indicatedString() { - return strTag - } - if n.Tag == "" || n.Tag == "!" { - switch n.Kind { - case MappingNode: - return mapTag - case SequenceNode: - return seqTag - case AliasNode: - if n.Alias != nil { - return n.Alias.ShortTag() - } - case ScalarNode: - tag, _ := resolve("", n.Value) - return tag - case 0: - // Special case to make the zero value convenient. - if n.IsZero() { - return nullTag - } - } - return "" - } - return shortTag(n.Tag) -} - -func (n *Node) indicatedString() bool { - return n.Kind == ScalarNode && - (shortTag(n.Tag) == strTag || - (n.Tag == "" || n.Tag == "!") && n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0) -} - -// SetString is a convenience function that sets the node to a string value -// and defines its style in a pleasant way depending on its content. -func (n *Node) SetString(s string) { - n.Kind = ScalarNode - if utf8.ValidString(s) { - n.Value = s - n.Tag = strTag - } else { - n.Value = encodeBase64(s) - n.Tag = binaryTag - } - if strings.Contains(n.Value, "\n") { - n.Style = LiteralStyle - } -} - -// -------------------------------------------------------------------------- -// Maintain a mapping of keys to structure field indexes - -// The code in this section was copied from mgo/bson. - -// structInfo holds details for the serialization of fields of -// a given struct. -type structInfo struct { - FieldsMap map[string]fieldInfo - FieldsList []fieldInfo - - // InlineMap is the number of the field in the struct that - // contains an ,inline map, or -1 if there's none. - InlineMap int - - // InlineUnmarshalers holds indexes to inlined fields that - // contain unmarshaler values. - InlineUnmarshalers [][]int -} - -type fieldInfo struct { - Key string - Num int - OmitEmpty bool - Flow bool - // Id holds the unique field identifier, so we can cheaply - // check for field duplicates without maintaining an extra map. - Id int - - // Inline holds the field index if the field is part of an inlined struct. - Inline []int -} - -var structMap = make(map[reflect.Type]*structInfo) -var fieldMapMutex sync.RWMutex -var unmarshalerType reflect.Type - -func init() { - var v Unmarshaler - unmarshalerType = reflect.ValueOf(&v).Elem().Type() -} - -func getStructInfo(st reflect.Type) (*structInfo, error) { - fieldMapMutex.RLock() - sinfo, found := structMap[st] - fieldMapMutex.RUnlock() - if found { - return sinfo, nil - } - - n := st.NumField() - fieldsMap := make(map[string]fieldInfo) - fieldsList := make([]fieldInfo, 0, n) - inlineMap := -1 - inlineUnmarshalers := [][]int(nil) - for i := 0; i != n; i++ { - field := st.Field(i) - if field.PkgPath != "" && !field.Anonymous { - continue // Private field - } - - info := fieldInfo{Num: i} - - tag := field.Tag.Get("yaml") - if tag == "" && strings.Index(string(field.Tag), ":") < 0 { - tag = string(field.Tag) - } - if tag == "-" { - continue - } - - inline := false - fields := strings.Split(tag, ",") - if len(fields) > 1 { - for _, flag := range fields[1:] { - switch flag { - case "omitempty": - info.OmitEmpty = true - case "flow": - info.Flow = true - case "inline": - inline = true - default: - return nil, errors.New(fmt.Sprintf("unsupported flag %q in tag %q of type %s", flag, tag, st)) - } - } - tag = fields[0] - } - - if inline { - switch field.Type.Kind() { - case reflect.Map: - if inlineMap >= 0 { - return nil, errors.New("multiple ,inline maps in struct " + st.String()) - } - if field.Type.Key() != reflect.TypeOf("") { - return nil, errors.New("option ,inline needs a map with string keys in struct " + st.String()) - } - inlineMap = info.Num - case reflect.Struct, reflect.Ptr: - ftype := field.Type - for ftype.Kind() == reflect.Ptr { - ftype = ftype.Elem() - } - if ftype.Kind() != reflect.Struct { - return nil, errors.New("option ,inline may only be used on a struct or map field") - } - if reflect.PtrTo(ftype).Implements(unmarshalerType) { - inlineUnmarshalers = append(inlineUnmarshalers, []int{i}) - } else { - sinfo, err := getStructInfo(ftype) - if err != nil { - return nil, err - } - for _, index := range sinfo.InlineUnmarshalers { - inlineUnmarshalers = append(inlineUnmarshalers, append([]int{i}, index...)) - } - for _, finfo := range sinfo.FieldsList { - if _, found := fieldsMap[finfo.Key]; found { - msg := "duplicated key '" + finfo.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - if finfo.Inline == nil { - finfo.Inline = []int{i, finfo.Num} - } else { - finfo.Inline = append([]int{i}, finfo.Inline...) - } - finfo.Id = len(fieldsList) - fieldsMap[finfo.Key] = finfo - fieldsList = append(fieldsList, finfo) - } - } - default: - return nil, errors.New("option ,inline may only be used on a struct or map field") - } - continue - } - - if tag != "" { - info.Key = tag - } else { - info.Key = strings.ToLower(field.Name) - } - - if _, found = fieldsMap[info.Key]; found { - msg := "duplicated key '" + info.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - - info.Id = len(fieldsList) - fieldsList = append(fieldsList, info) - fieldsMap[info.Key] = info - } - - sinfo = &structInfo{ - FieldsMap: fieldsMap, - FieldsList: fieldsList, - InlineMap: inlineMap, - InlineUnmarshalers: inlineUnmarshalers, - } - - fieldMapMutex.Lock() - structMap[st] = sinfo - fieldMapMutex.Unlock() - return sinfo, nil -} - -// IsZeroer is used to check whether an object is zero to -// determine whether it should be omitted when marshaling -// with the omitempty flag. One notable implementation -// is time.Time. -type IsZeroer interface { - IsZero() bool -} - -func isZero(v reflect.Value) bool { - kind := v.Kind() - if z, ok := v.Interface().(IsZeroer); ok { - if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { - return true - } - return z.IsZero() - } - switch kind { - case reflect.String: - return len(v.String()) == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - case reflect.Slice: - return v.Len() == 0 - case reflect.Map: - return v.Len() == 0 - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Struct: - vt := v.Type() - for i := v.NumField() - 1; i >= 0; i-- { - if vt.Field(i).PkgPath != "" { - continue // Private field - } - if !isZero(v.Field(i)) { - return false - } - } - return true - } - return false -} diff --git a/api/vendor/gopkg.in/yaml.v3/yamlh.go b/api/vendor/gopkg.in/yaml.v3/yamlh.go deleted file mode 100644 index 7c6d00770619..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/yamlh.go +++ /dev/null @@ -1,807 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package yaml - -import ( - "fmt" - "io" -) - -// The version directive data. -type yaml_version_directive_t struct { - major int8 // The major version number. - minor int8 // The minor version number. -} - -// The tag directive data. -type yaml_tag_directive_t struct { - handle []byte // The tag handle. - prefix []byte // The tag prefix. -} - -type yaml_encoding_t int - -// The stream encoding. -const ( - // Let the parser choose the encoding. - yaml_ANY_ENCODING yaml_encoding_t = iota - - yaml_UTF8_ENCODING // The default UTF-8 encoding. - yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. - yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. -) - -type yaml_break_t int - -// Line break types. -const ( - // Let the parser choose the break type. - yaml_ANY_BREAK yaml_break_t = iota - - yaml_CR_BREAK // Use CR for line breaks (Mac style). - yaml_LN_BREAK // Use LN for line breaks (Unix style). - yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). -) - -type yaml_error_type_t int - -// Many bad things could happen with the parser and emitter. -const ( - // No error is produced. - yaml_NO_ERROR yaml_error_type_t = iota - - yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. - yaml_READER_ERROR // Cannot read or decode the input stream. - yaml_SCANNER_ERROR // Cannot scan the input stream. - yaml_PARSER_ERROR // Cannot parse the input stream. - yaml_COMPOSER_ERROR // Cannot compose a YAML document. - yaml_WRITER_ERROR // Cannot write to the output stream. - yaml_EMITTER_ERROR // Cannot emit a YAML stream. -) - -// The pointer position. -type yaml_mark_t struct { - index int // The position index. - line int // The position line. - column int // The position column. -} - -// Node Styles - -type yaml_style_t int8 - -type yaml_scalar_style_t yaml_style_t - -// Scalar styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = 0 - - yaml_PLAIN_SCALAR_STYLE yaml_scalar_style_t = 1 << iota // The plain scalar style. - yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. - yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. - yaml_LITERAL_SCALAR_STYLE // The literal scalar style. - yaml_FOLDED_SCALAR_STYLE // The folded scalar style. -) - -type yaml_sequence_style_t yaml_style_t - -// Sequence styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota - - yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. - yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. -) - -type yaml_mapping_style_t yaml_style_t - -// Mapping styles. -const ( - // Let the emitter choose the style. - yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota - - yaml_BLOCK_MAPPING_STYLE // The block mapping style. - yaml_FLOW_MAPPING_STYLE // The flow mapping style. -) - -// Tokens - -type yaml_token_type_t int - -// Token types. -const ( - // An empty token. - yaml_NO_TOKEN yaml_token_type_t = iota - - yaml_STREAM_START_TOKEN // A STREAM-START token. - yaml_STREAM_END_TOKEN // A STREAM-END token. - - yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. - yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. - yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. - yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. - - yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. - yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. - yaml_BLOCK_END_TOKEN // A BLOCK-END token. - - yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. - yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. - yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. - yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. - - yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. - yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. - yaml_KEY_TOKEN // A KEY token. - yaml_VALUE_TOKEN // A VALUE token. - - yaml_ALIAS_TOKEN // An ALIAS token. - yaml_ANCHOR_TOKEN // An ANCHOR token. - yaml_TAG_TOKEN // A TAG token. - yaml_SCALAR_TOKEN // A SCALAR token. -) - -func (tt yaml_token_type_t) String() string { - switch tt { - case yaml_NO_TOKEN: - return "yaml_NO_TOKEN" - case yaml_STREAM_START_TOKEN: - return "yaml_STREAM_START_TOKEN" - case yaml_STREAM_END_TOKEN: - return "yaml_STREAM_END_TOKEN" - case yaml_VERSION_DIRECTIVE_TOKEN: - return "yaml_VERSION_DIRECTIVE_TOKEN" - case yaml_TAG_DIRECTIVE_TOKEN: - return "yaml_TAG_DIRECTIVE_TOKEN" - case yaml_DOCUMENT_START_TOKEN: - return "yaml_DOCUMENT_START_TOKEN" - case yaml_DOCUMENT_END_TOKEN: - return "yaml_DOCUMENT_END_TOKEN" - case yaml_BLOCK_SEQUENCE_START_TOKEN: - return "yaml_BLOCK_SEQUENCE_START_TOKEN" - case yaml_BLOCK_MAPPING_START_TOKEN: - return "yaml_BLOCK_MAPPING_START_TOKEN" - case yaml_BLOCK_END_TOKEN: - return "yaml_BLOCK_END_TOKEN" - case yaml_FLOW_SEQUENCE_START_TOKEN: - return "yaml_FLOW_SEQUENCE_START_TOKEN" - case yaml_FLOW_SEQUENCE_END_TOKEN: - return "yaml_FLOW_SEQUENCE_END_TOKEN" - case yaml_FLOW_MAPPING_START_TOKEN: - return "yaml_FLOW_MAPPING_START_TOKEN" - case yaml_FLOW_MAPPING_END_TOKEN: - return "yaml_FLOW_MAPPING_END_TOKEN" - case yaml_BLOCK_ENTRY_TOKEN: - return "yaml_BLOCK_ENTRY_TOKEN" - case yaml_FLOW_ENTRY_TOKEN: - return "yaml_FLOW_ENTRY_TOKEN" - case yaml_KEY_TOKEN: - return "yaml_KEY_TOKEN" - case yaml_VALUE_TOKEN: - return "yaml_VALUE_TOKEN" - case yaml_ALIAS_TOKEN: - return "yaml_ALIAS_TOKEN" - case yaml_ANCHOR_TOKEN: - return "yaml_ANCHOR_TOKEN" - case yaml_TAG_TOKEN: - return "yaml_TAG_TOKEN" - case yaml_SCALAR_TOKEN: - return "yaml_SCALAR_TOKEN" - } - return "" -} - -// The token structure. -type yaml_token_t struct { - // The token type. - typ yaml_token_type_t - - // The start/end of the token. - start_mark, end_mark yaml_mark_t - - // The stream encoding (for yaml_STREAM_START_TOKEN). - encoding yaml_encoding_t - - // The alias/anchor/scalar value or tag/tag directive handle - // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). - value []byte - - // The tag suffix (for yaml_TAG_TOKEN). - suffix []byte - - // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). - prefix []byte - - // The scalar style (for yaml_SCALAR_TOKEN). - style yaml_scalar_style_t - - // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). - major, minor int8 -} - -// Events - -type yaml_event_type_t int8 - -// Event types. -const ( - // An empty event. - yaml_NO_EVENT yaml_event_type_t = iota - - yaml_STREAM_START_EVENT // A STREAM-START event. - yaml_STREAM_END_EVENT // A STREAM-END event. - yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. - yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. - yaml_ALIAS_EVENT // An ALIAS event. - yaml_SCALAR_EVENT // A SCALAR event. - yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. - yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. - yaml_MAPPING_START_EVENT // A MAPPING-START event. - yaml_MAPPING_END_EVENT // A MAPPING-END event. - yaml_TAIL_COMMENT_EVENT -) - -var eventStrings = []string{ - yaml_NO_EVENT: "none", - yaml_STREAM_START_EVENT: "stream start", - yaml_STREAM_END_EVENT: "stream end", - yaml_DOCUMENT_START_EVENT: "document start", - yaml_DOCUMENT_END_EVENT: "document end", - yaml_ALIAS_EVENT: "alias", - yaml_SCALAR_EVENT: "scalar", - yaml_SEQUENCE_START_EVENT: "sequence start", - yaml_SEQUENCE_END_EVENT: "sequence end", - yaml_MAPPING_START_EVENT: "mapping start", - yaml_MAPPING_END_EVENT: "mapping end", - yaml_TAIL_COMMENT_EVENT: "tail comment", -} - -func (e yaml_event_type_t) String() string { - if e < 0 || int(e) >= len(eventStrings) { - return fmt.Sprintf("unknown event %d", e) - } - return eventStrings[e] -} - -// The event structure. -type yaml_event_t struct { - - // The event type. - typ yaml_event_type_t - - // The start and end of the event. - start_mark, end_mark yaml_mark_t - - // The document encoding (for yaml_STREAM_START_EVENT). - encoding yaml_encoding_t - - // The version directive (for yaml_DOCUMENT_START_EVENT). - version_directive *yaml_version_directive_t - - // The list of tag directives (for yaml_DOCUMENT_START_EVENT). - tag_directives []yaml_tag_directive_t - - // The comments - head_comment []byte - line_comment []byte - foot_comment []byte - tail_comment []byte - - // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). - anchor []byte - - // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - tag []byte - - // The scalar value (for yaml_SCALAR_EVENT). - value []byte - - // Is the document start/end indicator implicit, or the tag optional? - // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). - implicit bool - - // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). - quoted_implicit bool - - // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - style yaml_style_t -} - -func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } -func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } -func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } - -// Nodes - -const ( - yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. - yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. - yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. - yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. - yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. - yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. - - yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. - yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. - - // Not in original libyaml. - yaml_BINARY_TAG = "tag:yaml.org,2002:binary" - yaml_MERGE_TAG = "tag:yaml.org,2002:merge" - - yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. - yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. - yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. -) - -type yaml_node_type_t int - -// Node types. -const ( - // An empty node. - yaml_NO_NODE yaml_node_type_t = iota - - yaml_SCALAR_NODE // A scalar node. - yaml_SEQUENCE_NODE // A sequence node. - yaml_MAPPING_NODE // A mapping node. -) - -// An element of a sequence node. -type yaml_node_item_t int - -// An element of a mapping node. -type yaml_node_pair_t struct { - key int // The key of the element. - value int // The value of the element. -} - -// The node structure. -type yaml_node_t struct { - typ yaml_node_type_t // The node type. - tag []byte // The node tag. - - // The node data. - - // The scalar parameters (for yaml_SCALAR_NODE). - scalar struct { - value []byte // The scalar value. - length int // The length of the scalar value. - style yaml_scalar_style_t // The scalar style. - } - - // The sequence parameters (for YAML_SEQUENCE_NODE). - sequence struct { - items_data []yaml_node_item_t // The stack of sequence items. - style yaml_sequence_style_t // The sequence style. - } - - // The mapping parameters (for yaml_MAPPING_NODE). - mapping struct { - pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). - pairs_start *yaml_node_pair_t // The beginning of the stack. - pairs_end *yaml_node_pair_t // The end of the stack. - pairs_top *yaml_node_pair_t // The top of the stack. - style yaml_mapping_style_t // The mapping style. - } - - start_mark yaml_mark_t // The beginning of the node. - end_mark yaml_mark_t // The end of the node. - -} - -// The document structure. -type yaml_document_t struct { - - // The document nodes. - nodes []yaml_node_t - - // The version directive. - version_directive *yaml_version_directive_t - - // The list of tag directives. - tag_directives_data []yaml_tag_directive_t - tag_directives_start int // The beginning of the tag directives list. - tag_directives_end int // The end of the tag directives list. - - start_implicit int // Is the document start indicator implicit? - end_implicit int // Is the document end indicator implicit? - - // The start/end of the document. - start_mark, end_mark yaml_mark_t -} - -// The prototype of a read handler. -// -// The read handler is called when the parser needs to read more bytes from the -// source. The handler should write not more than size bytes to the buffer. -// The number of written bytes should be set to the size_read variable. -// -// [in,out] data A pointer to an application data specified by -// yaml_parser_set_input(). -// [out] buffer The buffer to write the data from the source. -// [in] size The size of the buffer. -// [out] size_read The actual number of bytes read from the source. -// -// On success, the handler should return 1. If the handler failed, -// the returned value should be 0. On EOF, the handler should set the -// size_read to 0 and return 1. -type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) - -// This structure holds information about a potential simple key. -type yaml_simple_key_t struct { - possible bool // Is a simple key possible? - required bool // Is a simple key required? - token_number int // The number of the token. - mark yaml_mark_t // The position mark. -} - -// The states of the parser. -type yaml_parser_state_t int - -const ( - yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota - - yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. - yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. - yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. - yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. - yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. - yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. - yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. - yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. - yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. - yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. - yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. - yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. - yaml_PARSE_END_STATE // Expect nothing. -) - -func (ps yaml_parser_state_t) String() string { - switch ps { - case yaml_PARSE_STREAM_START_STATE: - return "yaml_PARSE_STREAM_START_STATE" - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_START_STATE: - return "yaml_PARSE_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return "yaml_PARSE_DOCUMENT_CONTENT_STATE" - case yaml_PARSE_DOCUMENT_END_STATE: - return "yaml_PARSE_DOCUMENT_END_STATE" - case yaml_PARSE_BLOCK_NODE_STATE: - return "yaml_PARSE_BLOCK_NODE_STATE" - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" - case yaml_PARSE_FLOW_NODE_STATE: - return "yaml_PARSE_FLOW_NODE_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" - case yaml_PARSE_END_STATE: - return "yaml_PARSE_END_STATE" - } - return "" -} - -// This structure holds aliases data. -type yaml_alias_data_t struct { - anchor []byte // The anchor. - index int // The node id. - mark yaml_mark_t // The anchor mark. -} - -// The parser structure. -// -// All members are internal. Manage the structure using the -// yaml_parser_ family of functions. -type yaml_parser_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - - problem string // Error description. - - // The byte about which the problem occurred. - problem_offset int - problem_value int - problem_mark yaml_mark_t - - // The error context. - context string - context_mark yaml_mark_t - - // Reader stuff - - read_handler yaml_read_handler_t // Read handler. - - input_reader io.Reader // File input data. - input []byte // String input data. - input_pos int - - eof bool // EOF flag - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - unread int // The number of unread characters in the buffer. - - newlines int // The number of line breaks since last non-break/non-blank character - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The input encoding. - - offset int // The offset of the current position (in bytes). - mark yaml_mark_t // The mark of the current position. - - // Comments - - head_comment []byte // The current head comments - line_comment []byte // The current line comments - foot_comment []byte // The current foot comments - tail_comment []byte // Foot comment that happens at the end of a block. - stem_comment []byte // Comment in item preceding a nested structure (list inside list item, etc) - - comments []yaml_comment_t // The folded comments for all parsed tokens - comments_head int - - // Scanner stuff - - stream_start_produced bool // Have we started to scan the input stream? - stream_end_produced bool // Have we reached the end of the input stream? - - flow_level int // The number of unclosed '[' and '{' indicators. - - tokens []yaml_token_t // The tokens queue. - tokens_head int // The head of the tokens queue. - tokens_parsed int // The number of tokens fetched from the queue. - token_available bool // Does the tokens queue contain a token ready for dequeueing. - - indent int // The current indentation level. - indents []int // The indentation levels stack. - - simple_key_allowed bool // May a simple key occur at the current position? - simple_keys []yaml_simple_key_t // The stack of simple keys. - simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number - - // Parser stuff - - state yaml_parser_state_t // The current parser state. - states []yaml_parser_state_t // The parser states stack. - marks []yaml_mark_t // The stack of marks. - tag_directives []yaml_tag_directive_t // The list of TAG directives. - - // Dumper stuff - - aliases []yaml_alias_data_t // The alias data. - - document *yaml_document_t // The currently parsed document. -} - -type yaml_comment_t struct { - - scan_mark yaml_mark_t // Position where scanning for comments started - token_mark yaml_mark_t // Position after which tokens will be associated with this comment - start_mark yaml_mark_t // Position of '#' comment mark - end_mark yaml_mark_t // Position where comment terminated - - head []byte - line []byte - foot []byte -} - -// Emitter Definitions - -// The prototype of a write handler. -// -// The write handler is called when the emitter needs to flush the accumulated -// characters to the output. The handler should write @a size bytes of the -// @a buffer to the output. -// -// @param[in,out] data A pointer to an application data specified by -// yaml_emitter_set_output(). -// @param[in] buffer The buffer with bytes to be written. -// @param[in] size The size of the buffer. -// -// @returns On success, the handler should return @c 1. If the handler failed, -// the returned value should be @c 0. -// -type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error - -type yaml_emitter_state_t int - -// The emitter states. -const ( - // Expect STREAM-START. - yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota - - yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. - yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out - yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. - yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out - yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. - yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. - yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. - yaml_EMIT_END_STATE // Expect nothing. -) - -// The emitter structure. -// -// All members are internal. Manage the structure using the @c yaml_emitter_ -// family of functions. -type yaml_emitter_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - problem string // Error description. - - // Writer stuff - - write_handler yaml_write_handler_t // Write handler. - - output_buffer *[]byte // String output data. - output_writer io.Writer // File output data. - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The stream encoding. - - // Emitter stuff - - canonical bool // If the output is in the canonical style? - best_indent int // The number of indentation spaces. - best_width int // The preferred width of the output lines. - unicode bool // Allow unescaped non-ASCII characters? - line_break yaml_break_t // The preferred line break. - - state yaml_emitter_state_t // The current emitter state. - states []yaml_emitter_state_t // The stack of states. - - events []yaml_event_t // The event queue. - events_head int // The head of the event queue. - - indents []int // The stack of indentation levels. - - tag_directives []yaml_tag_directive_t // The list of tag directives. - - indent int // The current indentation level. - - flow_level int // The current flow level. - - root_context bool // Is it the document root context? - sequence_context bool // Is it a sequence context? - mapping_context bool // Is it a mapping context? - simple_key_context bool // Is it a simple mapping key context? - - line int // The current line. - column int // The current column. - whitespace bool // If the last character was a whitespace? - indention bool // If the last character was an indentation character (' ', '-', '?', ':')? - open_ended bool // If an explicit document end is required? - - space_above bool // Is there's an empty line above? - foot_indent int // The indent used to write the foot comment above, or -1 if none. - - // Anchor analysis. - anchor_data struct { - anchor []byte // The anchor value. - alias bool // Is it an alias? - } - - // Tag analysis. - tag_data struct { - handle []byte // The tag handle. - suffix []byte // The tag suffix. - } - - // Scalar analysis. - scalar_data struct { - value []byte // The scalar value. - multiline bool // Does the scalar contain line breaks? - flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? - block_plain_allowed bool // Can the scalar be expressed in the block plain style? - single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? - block_allowed bool // Can the scalar be expressed in the literal or folded styles? - style yaml_scalar_style_t // The output style. - } - - // Comments - head_comment []byte - line_comment []byte - foot_comment []byte - tail_comment []byte - - key_line_comment []byte - - // Dumper stuff - - opened bool // If the stream was already opened? - closed bool // If the stream was already closed? - - // The information associated with the document nodes. - anchors *struct { - references int // The number of references. - anchor int // The anchor id. - serialized bool // If the node has been emitted? - } - - last_anchor_id int // The last assigned anchor id. - - document *yaml_document_t // The currently emitted document. -} diff --git a/api/vendor/gopkg.in/yaml.v3/yamlprivateh.go b/api/vendor/gopkg.in/yaml.v3/yamlprivateh.go deleted file mode 100644 index e88f9c54aecb..000000000000 --- a/api/vendor/gopkg.in/yaml.v3/yamlprivateh.go +++ /dev/null @@ -1,198 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package yaml - -const ( - // The size of the input raw buffer. - input_raw_buffer_size = 512 - - // The size of the input buffer. - // It should be possible to decode the whole raw buffer. - input_buffer_size = input_raw_buffer_size * 3 - - // The size of the output buffer. - output_buffer_size = 128 - - // The size of the output raw buffer. - // It should be possible to encode the whole output buffer. - output_raw_buffer_size = (output_buffer_size*2 + 2) - - // The size of other stacks and queues. - initial_stack_size = 16 - initial_queue_size = 16 - initial_string_size = 16 -) - -// Check if the character at the specified position is an alphabetical -// character, a digit, '_', or '-'. -func is_alpha(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' -} - -// Check if the character at the specified position is a digit. -func is_digit(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' -} - -// Get the value of a digit. -func as_digit(b []byte, i int) int { - return int(b[i]) - '0' -} - -// Check if the character at the specified position is a hex-digit. -func is_hex(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' -} - -// Get the value of a hex-digit. -func as_hex(b []byte, i int) int { - bi := b[i] - if bi >= 'A' && bi <= 'F' { - return int(bi) - 'A' + 10 - } - if bi >= 'a' && bi <= 'f' { - return int(bi) - 'a' + 10 - } - return int(bi) - '0' -} - -// Check if the character is ASCII. -func is_ascii(b []byte, i int) bool { - return b[i] <= 0x7F -} - -// Check if the character at the start of the buffer can be printed unescaped. -func is_printable(b []byte, i int) bool { - return ((b[i] == 0x0A) || // . == #x0A - (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E - (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF - (b[i] > 0xC2 && b[i] < 0xED) || - (b[i] == 0xED && b[i+1] < 0xA0) || - (b[i] == 0xEE) || - (b[i] == 0xEF && // #xE000 <= . <= #xFFFD - !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF - !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) -} - -// Check if the character at the specified position is NUL. -func is_z(b []byte, i int) bool { - return b[i] == 0x00 -} - -// Check if the beginning of the buffer is a BOM. -func is_bom(b []byte, i int) bool { - return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF -} - -// Check if the character at the specified position is space. -func is_space(b []byte, i int) bool { - return b[i] == ' ' -} - -// Check if the character at the specified position is tab. -func is_tab(b []byte, i int) bool { - return b[i] == '\t' -} - -// Check if the character at the specified position is blank (space or tab). -func is_blank(b []byte, i int) bool { - //return is_space(b, i) || is_tab(b, i) - return b[i] == ' ' || b[i] == '\t' -} - -// Check if the character at the specified position is a line break. -func is_break(b []byte, i int) bool { - return (b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) -} - -func is_crlf(b []byte, i int) bool { - return b[i] == '\r' && b[i+1] == '\n' -} - -// Check if the character is a line break or NUL. -func is_breakz(b []byte, i int) bool { - //return is_break(b, i) || is_z(b, i) - return ( - // is_break: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - // is_z: - b[i] == 0) -} - -// Check if the character is a line break, space, or NUL. -func is_spacez(b []byte, i int) bool { - //return is_space(b, i) || is_breakz(b, i) - return ( - // is_space: - b[i] == ' ' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Check if the character is a line break, space, tab, or NUL. -func is_blankz(b []byte, i int) bool { - //return is_blank(b, i) || is_breakz(b, i) - return ( - // is_blank: - b[i] == ' ' || b[i] == '\t' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Determine the width of the character. -func width(b byte) int { - // Don't replace these by a switch without first - // confirming that it is being inlined. - if b&0x80 == 0x00 { - return 1 - } - if b&0xE0 == 0xC0 { - return 2 - } - if b&0xF0 == 0xE0 { - return 3 - } - if b&0xF8 == 0xF0 { - return 4 - } - return 0 - -} diff --git a/api/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go b/api/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go index 775b3b0c3673..29cec61930c1 100644 --- a/api/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go +++ b/api/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go @@ -16,10 +16,6 @@ package spec import ( "encoding/json" - "net/http" - "os" - "path/filepath" - "github.com/go-openapi/jsonreference" "k8s.io/kube-openapi/pkg/internal" @@ -56,52 +52,6 @@ func (r *Ref) RemoteURI() string { return u.String() } -// IsValidURI returns true when the url the ref points to can be found -func (r *Ref) IsValidURI(basepaths ...string) bool { - if r.String() == "" { - return true - } - - v := r.RemoteURI() - if v == "" { - return true - } - - if r.HasFullURL { - rr, err := http.Get(v) - if err != nil { - return false - } - - return rr.StatusCode/100 == 2 - } - - if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) { - return false - } - - // check for local file - pth := v - if r.HasURLPathOnly { - base := "." - if len(basepaths) > 0 { - base = filepath.Dir(filepath.Join(basepaths...)) - } - p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth))) - if e != nil { - return false - } - pth = p - } - - fi, err := os.Stat(filepath.ToSlash(pth)) - if err != nil { - return false - } - - return !fi.IsDir() -} - // Inherits creates a new reference from a parent and a child // If the child cannot inherit from the parent, an error is returned func (r *Ref) Inherits(child Ref) (*Ref, error) { diff --git a/api/vendor/modules.txt b/api/vendor/modules.txt index 6cb6717fcddc..5c4a6f8f826b 100644 --- a/api/vendor/modules.txt +++ b/api/vendor/modules.txt @@ -33,7 +33,7 @@ github.com/cespare/xxhash/v2 # github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc ## explicit github.com/davecgh/go-spew/spew -# github.com/emicklei/go-restful/v3 v3.12.2 +# github.com/emicklei/go-restful/v3 v3.13.0 ## explicit; go 1.13 github.com/emicklei/go-restful/v3 github.com/emicklei/go-restful/v3/log @@ -53,16 +53,52 @@ github.com/fxamacker/cbor/v2 # github.com/go-logr/logr v1.4.3 ## explicit; go 1.18 github.com/go-logr/logr -# github.com/go-openapi/jsonpointer v0.21.1 -## explicit; go 1.20 +# github.com/go-openapi/jsonpointer v0.22.4 +## explicit; go 1.24.0 github.com/go-openapi/jsonpointer -# github.com/go-openapi/jsonreference v0.21.0 -## explicit; go 1.20 +# github.com/go-openapi/jsonreference v0.21.4 +## explicit; go 1.24.0 github.com/go-openapi/jsonreference github.com/go-openapi/jsonreference/internal -# github.com/go-openapi/swag v0.23.1 -## explicit; go 1.20 +# github.com/go-openapi/swag v0.25.4 +## explicit; go 1.24.0 github.com/go-openapi/swag +# github.com/go-openapi/swag/cmdutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/cmdutils +# github.com/go-openapi/swag/conv v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/conv +# github.com/go-openapi/swag/fileutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/fileutils +# github.com/go-openapi/swag/jsonname v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/jsonname +# github.com/go-openapi/swag/jsonutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/jsonutils +github.com/go-openapi/swag/jsonutils/adapters +github.com/go-openapi/swag/jsonutils/adapters/ifaces +github.com/go-openapi/swag/jsonutils/adapters/stdlib/json +# github.com/go-openapi/swag/loading v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/loading +# github.com/go-openapi/swag/mangling v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/mangling +# github.com/go-openapi/swag/netutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/netutils +# github.com/go-openapi/swag/stringutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/stringutils +# github.com/go-openapi/swag/typeutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/typeutils +# github.com/go-openapi/swag/yamlutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/yamlutils # github.com/gogo/protobuf v1.3.2 ## explicit; go 1.15 github.com/gogo/protobuf/proto @@ -70,7 +106,7 @@ github.com/gogo/protobuf/sortkeys # github.com/google/btree v1.1.3 ## explicit; go 1.18 github.com/google/btree -# github.com/google/gnostic-models v0.7.0 +# github.com/google/gnostic-models v0.7.1 ## explicit; go 1.22 github.com/google/gnostic-models/compiler github.com/google/gnostic-models/extensions @@ -90,17 +126,9 @@ github.com/google/uuid # github.com/inconshreveable/mousetrap v1.1.0 ## explicit; go 1.18 github.com/inconshreveable/mousetrap -# github.com/josharian/intern v1.0.0 -## explicit; go 1.5 -github.com/josharian/intern # github.com/json-iterator/go v1.1.12 ## explicit; go 1.12 github.com/json-iterator/go -# github.com/mailru/easyjson v0.9.0 -## explicit; go 1.20 -github.com/mailru/easyjson/buffer -github.com/mailru/easyjson/jlexer -github.com/mailru/easyjson/jwriter # github.com/mitchellh/hashstructure/v2 v2.0.2 ## explicit; go 1.14 github.com/mitchellh/hashstructure/v2 @@ -124,9 +152,6 @@ github.com/openshift/api/operator/v1 # github.com/patrickmn/go-cache v2.1.0+incompatible ## explicit github.com/patrickmn/go-cache -# github.com/pkg/errors v0.9.1 -## explicit -github.com/pkg/errors # github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 ## explicit github.com/pmezard/go-difflib/difflib @@ -146,8 +171,8 @@ github.com/prometheus/client_model/go ## explicit; go 1.24.0 github.com/prometheus/common/expfmt github.com/prometheus/common/model -# github.com/prometheus/procfs v0.16.1 -## explicit; go 1.23.0 +# github.com/prometheus/procfs v0.19.2 +## explicit; go 1.24.0 github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util @@ -258,15 +283,12 @@ google.golang.org/protobuf/runtime/protoimpl google.golang.org/protobuf/types/descriptorpb google.golang.org/protobuf/types/known/anypb google.golang.org/protobuf/types/known/timestamppb -# gopkg.in/evanphx/json-patch.v4 v4.12.0 +# gopkg.in/evanphx/json-patch.v4 v4.13.0 ## explicit gopkg.in/evanphx/json-patch.v4 # gopkg.in/inf.v0 v0.9.1 ## explicit gopkg.in/inf.v0 -# gopkg.in/yaml.v3 v3.0.1 -## explicit -gopkg.in/yaml.v3 # k8s.io/api v0.34.3 ## explicit; go 1.24.0 k8s.io/api/admission/v1 @@ -672,7 +694,7 @@ k8s.io/cloud-provider/api # k8s.io/component-base v0.34.3 ## explicit; go 1.24.0 k8s.io/component-base/cli/flag -# k8s.io/component-helpers v0.34.2 +# k8s.io/component-helpers v0.34.3 ## explicit; go 1.24.0 k8s.io/component-helpers/resource # k8s.io/csi-translation-lib v0.34.1 @@ -688,8 +710,8 @@ k8s.io/klog/v2/internal/dbg k8s.io/klog/v2/internal/serialize k8s.io/klog/v2/internal/severity k8s.io/klog/v2/internal/sloghandler -# k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b -## explicit; go 1.23 +# k8s.io/kube-openapi v0.0.0-20251125145642-4e65d59e963e +## explicit; go 1.23.0 k8s.io/kube-openapi/pkg/cached k8s.io/kube-openapi/pkg/common k8s.io/kube-openapi/pkg/handler3 @@ -774,7 +796,7 @@ sigs.k8s.io/karpenter/pkg/utils/volume ## explicit; go 1.18 sigs.k8s.io/randfill sigs.k8s.io/randfill/bytesource -# sigs.k8s.io/structured-merge-diff/v6 v6.3.0 +# sigs.k8s.io/structured-merge-diff/v6 v6.3.1 ## explicit; go 1.23 sigs.k8s.io/structured-merge-diff/v6/fieldpath sigs.k8s.io/structured-merge-diff/v6/merge diff --git a/api/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go b/api/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go index 5d3707a5b50c..c8138a6548a5 100644 --- a/api/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go +++ b/api/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go @@ -18,6 +18,7 @@ package schema import ( "sync" + "sync/atomic" ) // Schema is a list of named types. @@ -28,7 +29,7 @@ type Schema struct { Types []TypeDef `yaml:"types,omitempty"` once sync.Once - m map[string]TypeDef + m atomic.Pointer[map[string]TypeDef] lock sync.Mutex // Cached results of resolving type references to atoms. Only stores @@ -144,26 +145,28 @@ type Map struct { ElementRelationship ElementRelationship `yaml:"elementRelationship,omitempty"` once sync.Once - m map[string]StructField + m atomic.Pointer[map[string]StructField] } // FindField is a convenience function that returns the referenced StructField, // if it exists, or (nil, false) if it doesn't. func (m *Map) FindField(name string) (StructField, bool) { m.once.Do(func() { - m.m = make(map[string]StructField, len(m.Fields)) + mm := make(map[string]StructField, len(m.Fields)) for _, field := range m.Fields { - m.m[field.Name] = field + mm[field.Name] = field } + m.m.Store(&mm) }) - sf, ok := m.m[name] + sf, ok := (*m.m.Load())[name] return sf, ok } -// CopyInto this instance of Map into the other -// If other is nil this method does nothing. -// If other is already initialized, overwrites it with this instance -// Warning: Not thread safe +// CopyInto clones this instance of Map into dst +// +// If dst is nil this method does nothing. +// If dst is already initialized, overwrites it with this instance. +// Warning: Not thread safe. Only use dst after this function returns. func (m *Map) CopyInto(dst *Map) { if dst == nil { return @@ -175,12 +178,13 @@ func (m *Map) CopyInto(dst *Map) { dst.Unions = m.Unions dst.ElementRelationship = m.ElementRelationship - if m.m != nil { + mm := m.m.Load() + if mm != nil { // If cache is non-nil then the once token had been consumed. // Must reset token and use it again to ensure same semantics. dst.once = sync.Once{} dst.once.Do(func() { - dst.m = m.m + dst.m.Store(mm) }) } } @@ -274,12 +278,13 @@ type List struct { // if it exists, or (nil, false) if it doesn't. func (s *Schema) FindNamedType(name string) (TypeDef, bool) { s.once.Do(func() { - s.m = make(map[string]TypeDef, len(s.Types)) + sm := make(map[string]TypeDef, len(s.Types)) for _, t := range s.Types { - s.m[t.Name] = t + sm[t.Name] = t } + s.m.Store(&sm) }) - t, ok := s.m[name] + t, ok := (*s.m.Load())[name] return t, ok } @@ -352,10 +357,11 @@ func (s *Schema) Resolve(tr TypeRef) (Atom, bool) { return result, true } -// Clones this instance of Schema into the other -// If other is nil this method does nothing. -// If other is already initialized, overwrites it with this instance -// Warning: Not thread safe +// CopyInto clones this instance of Schema into dst +// +// If dst is nil this method does nothing. +// If dst is already initialized, overwrites it with this instance. +// Warning: Not thread safe. Only use dst after this function returns. func (s *Schema) CopyInto(dst *Schema) { if dst == nil { return @@ -364,12 +370,13 @@ func (s *Schema) CopyInto(dst *Schema) { // Schema type is considered immutable so sharing references dst.Types = s.Types - if s.m != nil { + sm := s.m.Load() + if sm != nil { // If cache is non-nil then the once token had been consumed. // Must reset token and use it again to ensure same semantics. dst.once = sync.Once{} dst.once.Do(func() { - dst.m = s.m + dst.m.Store(sm) }) } } diff --git a/api/vendor/sigs.k8s.io/structured-merge-diff/v6/typed/remove.go b/api/vendor/sigs.k8s.io/structured-merge-diff/v6/typed/remove.go index 86de5105d7c1..0db1734f941b 100644 --- a/api/vendor/sigs.k8s.io/structured-merge-diff/v6/typed/remove.go +++ b/api/vendor/sigs.k8s.io/structured-merge-diff/v6/typed/remove.go @@ -58,6 +58,10 @@ func (w *removingWalker) doList(t *schema.List) (errs ValidationErrors) { defer w.allocator.Free(l) // If list is null or empty just return if l == nil || l.Length() == 0 { + // For extraction, we just return the value as is (which is nil or empty). For extraction the difference matters. + if w.shouldExtract { + w.out = w.value.Unstructured() + } return nil } @@ -71,6 +75,7 @@ func (w *removingWalker) doList(t *schema.List) (errs ValidationErrors) { } var newItems []interface{} + hadMatches := false iter := l.RangeUsing(w.allocator) defer w.allocator.Free(iter) for iter.Next() { @@ -80,24 +85,40 @@ func (w *removingWalker) doList(t *schema.List) (errs ValidationErrors) { path, _ := fieldpath.MakePath(pe) // save items on the path when we shouldExtract // but ignore them when we are removing (i.e. !w.shouldExtract) - if w.toRemove.Has(path) { - if w.shouldExtract { - newItems = append(newItems, removeItemsWithSchema(item, w.toRemove, w.schema, t.ElementType, w.shouldExtract).Unstructured()) - } else { - continue + isExactPathMatch := w.toRemove.Has(path) + isPrefixMatch := !w.toRemove.WithPrefix(pe).Empty() + if w.shouldExtract { + if isPrefixMatch { + item = removeItemsWithSchema(item, w.toRemove.WithPrefix(pe), w.schema, t.ElementType, w.shouldExtract) + } + if isExactPathMatch || isPrefixMatch { + newItems = append(newItems, item.Unstructured()) } - } - if subset := w.toRemove.WithPrefix(pe); !subset.Empty() { - item = removeItemsWithSchema(item, subset, w.schema, t.ElementType, w.shouldExtract) } else { - // don't save items not on the path when we shouldExtract. - if w.shouldExtract { + if isExactPathMatch { continue } + if isPrefixMatch { + // Removing nested items within this list item and preserve if it becomes empty + hadMatches = true + wasMap := item.IsMap() + wasList := item.IsList() + item = removeItemsWithSchema(item, w.toRemove.WithPrefix(pe), w.schema, t.ElementType, w.shouldExtract) + // If item returned null but we're removing items within the structure(not the item itself), + // preserve the empty container structure + if item.IsNull() && !w.shouldExtract { + if wasMap { + item = value.NewValueInterface(map[string]interface{}{}) + } else if wasList { + item = value.NewValueInterface([]interface{}{}) + } + } + } + newItems = append(newItems, item.Unstructured()) } - newItems = append(newItems, item.Unstructured()) } - if len(newItems) > 0 { + // Preserve empty lists (non-nil) instead of converting to null when items were matched and removed + if len(newItems) > 0 || (hadMatches && !w.shouldExtract) { w.out = newItems } return nil @@ -113,6 +134,10 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors { } // If map is null or empty just return if m == nil || m.Empty() { + // For extraction, we just return the value as is (which is nil or empty). For extraction the difference matters. + if w.shouldExtract { + w.out = w.value.Unstructured() + } return nil } @@ -131,6 +156,7 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors { } newMap := map[string]interface{}{} + hadMatches := false m.Iterate(func(k string, val value.Value) bool { pe := fieldpath.PathElement{FieldName: &k} path, _ := fieldpath.MakePath(pe) @@ -148,7 +174,19 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors { return true } if subset := w.toRemove.WithPrefix(pe); !subset.Empty() { + hadMatches = true + wasMap := val.IsMap() + wasList := val.IsList() val = removeItemsWithSchema(val, subset, w.schema, fieldType, w.shouldExtract) + // If val returned null but we're removing items within the structure (not the field itself), + // preserve the empty container structure + if val.IsNull() && !w.shouldExtract { + if wasMap { + val = value.NewValueInterface(map[string]interface{}{}) + } else if wasList { + val = value.NewValueInterface([]interface{}{}) + } + } } else { // don't save values not on the path when we shouldExtract. if w.shouldExtract { @@ -158,7 +196,8 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors { newMap[k] = val.Unstructured() return true }) - if len(newMap) > 0 { + // Preserve empty maps (non-nil) instead of converting to null when items were matched and removed + if len(newMap) > 0 || (hadMatches && !w.shouldExtract) { w.out = newMap } return nil diff --git a/client/applyconfiguration/hypershift/v1beta1/hostedcontrolplaneinitializationstatus.go b/client/applyconfiguration/hypershift/v1beta1/hostedcontrolplaneinitializationstatus.go new file mode 100644 index 000000000000..3df3d3039414 --- /dev/null +++ b/client/applyconfiguration/hypershift/v1beta1/hostedcontrolplaneinitializationstatus.go @@ -0,0 +1,38 @@ +/* + + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// HostedControlPlaneInitializationStatusApplyConfiguration represents a declarative configuration of the HostedControlPlaneInitializationStatus type for use +// with apply. +type HostedControlPlaneInitializationStatusApplyConfiguration struct { + ControlPlaneInitialized *bool `json:"controlPlaneInitialized,omitempty"` +} + +// HostedControlPlaneInitializationStatusApplyConfiguration constructs a declarative configuration of the HostedControlPlaneInitializationStatus type for use with +// apply. +func HostedControlPlaneInitializationStatus() *HostedControlPlaneInitializationStatusApplyConfiguration { + return &HostedControlPlaneInitializationStatusApplyConfiguration{} +} + +// WithControlPlaneInitialized sets the ControlPlaneInitialized field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ControlPlaneInitialized field is set to the value of the last call. +func (b *HostedControlPlaneInitializationStatusApplyConfiguration) WithControlPlaneInitialized(value bool) *HostedControlPlaneInitializationStatusApplyConfiguration { + b.ControlPlaneInitialized = &value + return b +} diff --git a/client/applyconfiguration/hypershift/v1beta1/hostedcontrolplanestatus.go b/client/applyconfiguration/hypershift/v1beta1/hostedcontrolplanestatus.go index 3921f0dd7d99..fe6fadd5088c 100644 --- a/client/applyconfiguration/hypershift/v1beta1/hostedcontrolplanestatus.go +++ b/client/applyconfiguration/hypershift/v1beta1/hostedcontrolplanestatus.go @@ -26,24 +26,25 @@ import ( // HostedControlPlaneStatusApplyConfiguration represents a declarative configuration of the HostedControlPlaneStatus type for use // with apply. type HostedControlPlaneStatusApplyConfiguration struct { - Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` - Ready *bool `json:"ready,omitempty"` - Initialized *bool `json:"initialized,omitempty"` - ExternalManagedControlPlane *bool `json:"externalManagedControlPlane,omitempty"` - ControlPlaneEndpoint *APIEndpointApplyConfiguration `json:"controlPlaneEndpoint,omitempty"` - OAuthCallbackURLTemplate *string `json:"oauthCallbackURLTemplate,omitempty"` - ControlPlaneVersion *ControlPlaneVersionStatusApplyConfiguration `json:"controlPlaneVersion,omitempty"` - VersionStatus *ClusterVersionStatusApplyConfiguration `json:"versionStatus,omitempty"` - Version *string `json:"version,omitempty"` - ReleaseImage *string `json:"releaseImage,omitempty"` - LastReleaseImageTransitionTime *metav1.Time `json:"lastReleaseImageTransitionTime,omitempty"` - KubeConfig *KubeconfigSecretRefApplyConfiguration `json:"kubeConfig,omitempty"` - CustomKubeconfig *KubeconfigSecretRefApplyConfiguration `json:"customKubeconfig,omitempty"` - KubeadminPassword *corev1.LocalObjectReference `json:"kubeadminPassword,omitempty"` - Platform *PlatformStatusApplyConfiguration `json:"platform,omitempty"` - NodeCount *int `json:"nodeCount,omitempty"` - AutoNode *AutoNodeStatusApplyConfiguration `json:"autoNode,omitempty"` - Configuration *ConfigurationStatusApplyConfiguration `json:"configuration,omitempty"` + Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` + Ready *bool `json:"ready,omitempty"` + Initialized *bool `json:"initialized,omitempty"` + Initialization *HostedControlPlaneInitializationStatusApplyConfiguration `json:"initialization,omitempty"` + ExternalManagedControlPlane *bool `json:"externalManagedControlPlane,omitempty"` + ControlPlaneEndpoint *APIEndpointApplyConfiguration `json:"controlPlaneEndpoint,omitempty"` + OAuthCallbackURLTemplate *string `json:"oauthCallbackURLTemplate,omitempty"` + ControlPlaneVersion *ControlPlaneVersionStatusApplyConfiguration `json:"controlPlaneVersion,omitempty"` + VersionStatus *ClusterVersionStatusApplyConfiguration `json:"versionStatus,omitempty"` + Version *string `json:"version,omitempty"` + ReleaseImage *string `json:"releaseImage,omitempty"` + LastReleaseImageTransitionTime *metav1.Time `json:"lastReleaseImageTransitionTime,omitempty"` + KubeConfig *KubeconfigSecretRefApplyConfiguration `json:"kubeConfig,omitempty"` + CustomKubeconfig *KubeconfigSecretRefApplyConfiguration `json:"customKubeconfig,omitempty"` + KubeadminPassword *corev1.LocalObjectReference `json:"kubeadminPassword,omitempty"` + Platform *PlatformStatusApplyConfiguration `json:"platform,omitempty"` + NodeCount *int `json:"nodeCount,omitempty"` + AutoNode *AutoNodeStatusApplyConfiguration `json:"autoNode,omitempty"` + Configuration *ConfigurationStatusApplyConfiguration `json:"configuration,omitempty"` } // HostedControlPlaneStatusApplyConfiguration constructs a declarative configuration of the HostedControlPlaneStatus type for use with @@ -81,6 +82,14 @@ func (b *HostedControlPlaneStatusApplyConfiguration) WithInitialized(value bool) return b } +// WithInitialization sets the Initialization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Initialization field is set to the value of the last call. +func (b *HostedControlPlaneStatusApplyConfiguration) WithInitialization(value *HostedControlPlaneInitializationStatusApplyConfiguration) *HostedControlPlaneStatusApplyConfiguration { + b.Initialization = value + return b +} + // WithExternalManagedControlPlane sets the ExternalManagedControlPlane field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ExternalManagedControlPlane field is set to the value of the last call. diff --git a/client/applyconfiguration/utils.go b/client/applyconfiguration/utils.go index b89bca7ed49c..ff2b1a6ca9a2 100644 --- a/client/applyconfiguration/utils.go +++ b/client/applyconfiguration/utils.go @@ -239,6 +239,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &hypershiftv1beta1.HostedClusterStatusApplyConfiguration{} case v1beta1.SchemeGroupVersion.WithKind("HostedControlPlane"): return &hypershiftv1beta1.HostedControlPlaneApplyConfiguration{} + case v1beta1.SchemeGroupVersion.WithKind("HostedControlPlaneInitializationStatus"): + return &hypershiftv1beta1.HostedControlPlaneInitializationStatusApplyConfiguration{} case v1beta1.SchemeGroupVersion.WithKind("HostedControlPlaneSpec"): return &hypershiftv1beta1.HostedControlPlaneSpecApplyConfiguration{} case v1beta1.SchemeGroupVersion.WithKind("HostedControlPlaneStatus"): diff --git a/cmd/cluster/core/dump.go b/cmd/cluster/core/dump.go index ca9ccf35758a..74f287af6fdd 100644 --- a/cmd/cluster/core/dump.go +++ b/cmd/cluster/core/dump.go @@ -56,7 +56,7 @@ import ( capikubevirt "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" capiopenstackv1alpha1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1" capiopenstackv1beta1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" karpenterv1 "sigs.k8s.io/karpenter/pkg/apis/v1" secretsstorev1 "sigs.k8s.io/secrets-store-csi-driver/apis/v1" diff --git a/cmd/install/assets/assets.go b/cmd/install/assets/assets.go index 0e0e75446199..a4829de3d13b 100644 --- a/cmd/install/assets/assets.go +++ b/cmd/install/assets/assets.go @@ -31,6 +31,26 @@ var recordingRules embed.FS const capiLabel = "cluster.x-k8s.io/v1beta1" +// CAPICRDOverrides configures CAPI CRDs that have both v1beta1 and v1beta2 versions. +// These CRDs need conversion webhooks during the v1beta1 -> v1beta2 transition period +// to ensure v1beta1 clients (e.g. older CPO versions) can still operate correctly. +var CAPICRDOverrides = map[string]struct { + NeedsConversion bool +}{ + "clusterclasses.cluster.x-k8s.io": {NeedsConversion: true}, + "clusters.cluster.x-k8s.io": {NeedsConversion: true}, + "machinedeployments.cluster.x-k8s.io": {NeedsConversion: true}, + "machinedrainrules.cluster.x-k8s.io": {NeedsConversion: true}, + "machinehealthchecks.cluster.x-k8s.io": {NeedsConversion: true}, + "machinepools.cluster.x-k8s.io": {NeedsConversion: true}, + "machines.cluster.x-k8s.io": {NeedsConversion: true}, + "machinesets.cluster.x-k8s.io": {NeedsConversion: true}, + "ipaddressclaims.ipam.cluster.x-k8s.io": {NeedsConversion: true}, + "ipaddresses.ipam.cluster.x-k8s.io": {NeedsConversion: true}, + "clusterresourcesetbindings.addons.cluster.x-k8s.io": {NeedsConversion: true}, + "clusterresourcesets.addons.cluster.x-k8s.io": {NeedsConversion: true}, +} + // capiResources specifies which CRDs should get labeled with capiLabel // to satisfy CAPI contracts. There might be a way to achieve this during CRD // generation, but for now we're just post-processing at runtime here. diff --git a/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsclusters.yaml b/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsclusters.yaml index 0bced98c42e6..3a7b7ce160e9 100644 --- a/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsclusters.yaml +++ b/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsclusters.yaml @@ -2213,8 +2213,44 @@ spec: CapacityReservationPreference specifies the preference for use of Capacity Reservations by the instance. Valid values include: "Open": The instance may make use of open Capacity Reservations that match its AZ and InstanceType "None": The instance may not make use of any Capacity Reservations. This is to conserve open reservations for desired workloads - "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation + "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation. Note that this is incompatible with a MarketType of `Spot` type: string + cpuOptions: + description: |- + CPUOptions defines CPU-related settings for the instance, including the confidential computing policy. + When omitted, this means no opinion and the AWS platform is left to choose a reasonable default. + minProperties: 1 + properties: + confidentialCompute: + description: |- + ConfidentialCompute specifies whether confidential computing should be enabled for the instance, + and, if so, which confidential computing technology to use. + Valid values are: Disabled, AMDEncryptedVirtualizationNestedPaging + When set to Disabled, confidential computing will be disabled for the instance. + When set to AMDEncryptedVirtualizationNestedPaging, AMD SEV-SNP will be used as the confidential computing technology for the instance. + In this case, ensure the following conditions are met: + 1) The selected instance type supports AMD SEV-SNP. + 2) The selected AWS region supports AMD SEV-SNP. + 3) The selected AMI supports AMD SEV-SNP. + More details can be checked at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html + When omitted, this means no opinion and the AWS platform is left to choose a reasonable default, + which is subject to change without notice. The current default is Disabled. + enum: + - Disabled + - AMDEncryptedVirtualizationNestedPaging + type: string + type: object + dynamicHostAllocation: + description: |- + DynamicHostAllocation enables automatic allocation of dedicated hosts. + This field is mutually exclusive with HostID. + properties: + tags: + additionalProperties: + type: string + description: Tags to apply to the allocated dedicated host. + type: object + type: object ebsOptimized: description: Indicates whether the instance is optimized for Amazon EBS I/O. diff --git a/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachinepools.yaml b/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachinepools.yaml index 44c93ae3d6d2..d678a7844ad3 100644 --- a/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachinepools.yaml +++ b/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachinepools.yaml @@ -1001,9 +1001,10 @@ spec: type: array type: object version: - default: "2.3" - description: Version defines which version of Ignition will be - used to generate bootstrap data. + description: |- + Version defines which version of Ignition will be used to generate bootstrap data. + Defaults to `2.3` if storageType is set to `ClusterObjectStore`. + It will be ignored if storageType is set to `UnencryptedUserData`, as the userdata defines its own version. enum: - "2.3" - "3.0" diff --git a/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachines.yaml b/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachines.yaml index 8af9ddf66f52..0cb803f689dd 100644 --- a/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachines.yaml +++ b/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachines.yaml @@ -657,7 +657,7 @@ spec: CapacityReservationPreference specifies the preference for use of Capacity Reservations by the instance. Valid values include: "Open": The instance may make use of open Capacity Reservations that match its AZ and InstanceType "None": The instance may not make use of any Capacity Reservations. This is to conserve open reservations for desired workloads - "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation + "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation. Note that this is incompatible with a MarketType of `Spot` type: string cloudInit: description: |- @@ -692,6 +692,44 @@ spec: - ssm-parameter-store type: string type: object + cpuOptions: + description: |- + CPUOptions defines CPU-related settings for the instance, including the confidential computing policy. + When omitted, this means no opinion and the AWS platform is left to choose a reasonable default. + minProperties: 1 + properties: + confidentialCompute: + description: |- + ConfidentialCompute specifies whether confidential computing should be enabled for the instance, + and, if so, which confidential computing technology to use. + Valid values are: Disabled, AMDEncryptedVirtualizationNestedPaging + When set to Disabled, confidential computing will be disabled for the instance. + When set to AMDEncryptedVirtualizationNestedPaging, AMD SEV-SNP will be used as the confidential computing technology for the instance. + In this case, ensure the following conditions are met: + 1) The selected instance type supports AMD SEV-SNP. + 2) The selected AWS region supports AMD SEV-SNP. + 3) The selected AMI supports AMD SEV-SNP. + More details can be checked at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html + When omitted, this means no opinion and the AWS platform is left to choose a reasonable default, + which is subject to change without notice. The current default is Disabled. + enum: + - Disabled + - AMDEncryptedVirtualizationNestedPaging + type: string + type: object + dynamicHostAllocation: + description: |- + DynamicHostAllocation enables automatic allocation of a single dedicated host. + This field is mutually exclusive with HostID and always allocates exactly one host. + Cost effectiveness of allocating a single instance on a dedicated host may vary + depending on the instance type and the region. + properties: + tags: + additionalProperties: + type: string + description: Tags to apply to the allocated dedicated host. + type: object + type: object elasticIpPool: description: ElasticIPPool is the configuration to allocate Public IPv4 address (Elastic IP/EIP) from user-defined pool. @@ -722,18 +760,22 @@ spec: rule: self in ['none','amazon-pool'] type: object hostAffinity: + default: host description: |- HostAffinity specifies the dedicated host affinity setting for the instance. - When hostAffinity is set to host, an instance started onto a specific host always restarts on the same host if stopped. - When hostAffinity is set to default, and you stop and restart the instance, it can be restarted on any available host. + When HostAffinity is set to host, an instance started onto a specific host always restarts on the same host if stopped. + When HostAffinity is set to default, and you stop and restart the instance, it can be restarted on any available host. When HostAffinity is defined, HostID is required. enum: - default - host type: string hostID: - description: HostID specifies the Dedicated Host on which the instance - must be started. + description: |- + HostID specifies the Dedicated Host on which the instance must be started. + This field is mutually exclusive with DynamicHostAllocation. + maxLength: 19 + pattern: ^h-[0-9a-f]{17}$ type: string iamInstanceProfile: description: IAMInstanceProfile is a name of an IAM instance profile @@ -822,9 +864,10 @@ spec: type: array type: object version: - default: "2.3" - description: Version defines which version of Ignition will be - used to generate bootstrap data. + description: |- + Version defines which version of Ignition will be used to generate bootstrap data. + Defaults to `2.3` if storageType is set to `ClusterObjectStore`. + It will be ignored if storageType is set to `UnencryptedUserData`, as the userdata defines its own version. enum: - "2.3" - "3.0" @@ -1137,8 +1180,12 @@ spec: type: string type: object tenancy: - description: Tenancy indicates if instance should run on shared or - single-tenant hardware. + description: |- + Tenancy indicates if instance should run on shared or single-tenant hardware. + When Tenancy=host, AWS will attempt to find a suitable host from: + - Preexisting allocated hosts that have auto-placement enabled + - A specific host ID, if configured + - Allocating a new dedicated host if DynamicHostAllocation is configured enum: - default - dedicated @@ -1241,6 +1288,17 @@ spec: - type type: object type: array + dedicatedHost: + description: |- + DedicatedHost tracks the dynamically allocated dedicated host. + This field is populated when DynamicHostAllocation is used. + properties: + id: + description: |- + ID tracks the dynamically allocated dedicated host ID. + This field is populated when DynamicHostAllocation is used. + type: string + type: object failureMessage: description: |- FailureMessage will be set in the event that there is a terminal problem diff --git a/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachinetemplates.yaml b/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachinetemplates.yaml index 83af6cb6090f..9522677d0cad 100644 --- a/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachinetemplates.yaml +++ b/cmd/install/assets/cluster-api-provider-aws/infrastructure.cluster.x-k8s.io_awsmachinetemplates.yaml @@ -576,7 +576,7 @@ spec: CapacityReservationPreference specifies the preference for use of Capacity Reservations by the instance. Valid values include: "Open": The instance may make use of open Capacity Reservations that match its AZ and InstanceType "None": The instance may not make use of any Capacity Reservations. This is to conserve open reservations for desired workloads - "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation + "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation. Note that this is incompatible with a MarketType of `Spot` type: string cloudInit: description: |- @@ -611,6 +611,45 @@ spec: - ssm-parameter-store type: string type: object + cpuOptions: + description: |- + CPUOptions defines CPU-related settings for the instance, including the confidential computing policy. + When omitted, this means no opinion and the AWS platform is left to choose a reasonable default. + minProperties: 1 + properties: + confidentialCompute: + description: |- + ConfidentialCompute specifies whether confidential computing should be enabled for the instance, + and, if so, which confidential computing technology to use. + Valid values are: Disabled, AMDEncryptedVirtualizationNestedPaging + When set to Disabled, confidential computing will be disabled for the instance. + When set to AMDEncryptedVirtualizationNestedPaging, AMD SEV-SNP will be used as the confidential computing technology for the instance. + In this case, ensure the following conditions are met: + 1) The selected instance type supports AMD SEV-SNP. + 2) The selected AWS region supports AMD SEV-SNP. + 3) The selected AMI supports AMD SEV-SNP. + More details can be checked at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html + When omitted, this means no opinion and the AWS platform is left to choose a reasonable default, + which is subject to change without notice. The current default is Disabled. + enum: + - Disabled + - AMDEncryptedVirtualizationNestedPaging + type: string + type: object + dynamicHostAllocation: + description: |- + DynamicHostAllocation enables automatic allocation of a single dedicated host. + This field is mutually exclusive with HostID and always allocates exactly one host. + Cost effectiveness of allocating a single instance on a dedicated host may vary + depending on the instance type and the region. + properties: + tags: + additionalProperties: + type: string + description: Tags to apply to the allocated dedicated + host. + type: object + type: object elasticIpPool: description: ElasticIPPool is the configuration to allocate Public IPv4 address (Elastic IP/EIP) from user-defined pool. @@ -641,18 +680,22 @@ spec: rule: self in ['none','amazon-pool'] type: object hostAffinity: + default: host description: |- HostAffinity specifies the dedicated host affinity setting for the instance. - When hostAffinity is set to host, an instance started onto a specific host always restarts on the same host if stopped. - When hostAffinity is set to default, and you stop and restart the instance, it can be restarted on any available host. + When HostAffinity is set to host, an instance started onto a specific host always restarts on the same host if stopped. + When HostAffinity is set to default, and you stop and restart the instance, it can be restarted on any available host. When HostAffinity is defined, HostID is required. enum: - default - host type: string hostID: - description: HostID specifies the Dedicated Host on which - the instance must be started. + description: |- + HostID specifies the Dedicated Host on which the instance must be started. + This field is mutually exclusive with DynamicHostAllocation. + maxLength: 19 + pattern: ^h-[0-9a-f]{17}$ type: string iamInstanceProfile: description: IAMInstanceProfile is a name of an IAM instance @@ -741,9 +784,10 @@ spec: type: array type: object version: - default: "2.3" - description: Version defines which version of Ignition - will be used to generate bootstrap data. + description: |- + Version defines which version of Ignition will be used to generate bootstrap data. + Defaults to `2.3` if storageType is set to `ClusterObjectStore`. + It will be ignored if storageType is set to `UnencryptedUserData`, as the userdata defines its own version. enum: - "2.3" - "3.0" @@ -1063,8 +1107,12 @@ spec: type: string type: object tenancy: - description: Tenancy indicates if instance should run on shared - or single-tenant hardware. + description: |- + Tenancy indicates if instance should run on shared or single-tenant hardware. + When Tenancy=host, AWS will attempt to find a suitable host from: + - Preexisting allocated hosts that have auto-placement enabled + - A specific host ID, if configured + - Allocating a new dedicated host if DynamicHostAllocation is configured enum: - default - dedicated @@ -1108,7 +1156,84 @@ spec: This value is used for autoscaling from zero operations as defined in: https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20210310-opt-in-autoscaling-from-zero.md type: object + conditions: + description: Conditions defines current service state of the AWSMachineTemplate. + items: + description: Condition defines an observation of a Cluster API resource + operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + nodeInfo: + description: |- + NodeInfo contains information about the node's architecture and operating system. + This value is used for autoscaling from zero operations as defined in: + https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20210310-opt-in-autoscaling-from-zero.md + properties: + architecture: + description: |- + Architecture is the CPU architecture of the node. + Its underlying type is a string and its value can be any of amd64, arm64. + enum: + - amd64 + - arm64 + type: string + operatingSystem: + description: |- + OperatingSystem is the operating system of the node. + Its underlying type is a string and its value can be any of linux, windows. + enum: + - linux + - windows + type: string + type: object type: object type: object served: true storage: true + subresources: + status: {} diff --git a/cmd/install/assets/cluster-api-provider-azure/infrastructure.cluster.x-k8s.io_azureclusters.yaml b/cmd/install/assets/cluster-api-provider-azure/infrastructure.cluster.x-k8s.io_azureclusters.yaml index e3335e60dcda..819897033e45 100644 --- a/cmd/install/assets/cluster-api-provider-azure/infrastructure.cluster.x-k8s.io_azureclusters.yaml +++ b/cmd/install/assets/cluster-api-provider-azure/infrastructure.cluster.x-k8s.io_azureclusters.yaml @@ -215,6 +215,12 @@ spec: type: object name: type: string + zones: + description: Zones mentions the list of zones the + NAT gateway should be a part of. + items: + type: string + type: array required: - name type: object @@ -1003,6 +1009,12 @@ spec: type: object name: type: string + zones: + description: Zones mentions the list of zones the NAT + gateway should be a part of. + items: + type: string + type: array required: - name type: object diff --git a/cmd/install/assets/cluster-api-provider-azure/infrastructure.cluster.x-k8s.io_azuremachinetemplates.yaml b/cmd/install/assets/cluster-api-provider-azure/infrastructure.cluster.x-k8s.io_azuremachinetemplates.yaml index b2b53edca60a..e0104ae47dab 100644 --- a/cmd/install/assets/cluster-api-provider-azure/infrastructure.cluster.x-k8s.io_azuremachinetemplates.yaml +++ b/cmd/install/assets/cluster-api-provider-azure/infrastructure.cluster.x-k8s.io_azuremachinetemplates.yaml @@ -751,6 +751,48 @@ spec: required: - template type: object + status: + description: AzureMachineTemplateStatus defines the observed state of + AzureMachineTemplate. + properties: + capacity: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: |- + Capacity defines the resource capacity for this machine. + This value is used for autoscaling from zero operations as defined in: + https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20210310-opt-in-autoscaling-from-zero.md + type: object + nodeInfo: + description: |- + NodeInfo contains information about the node's architecture and operating system. + This value is used for autoscaling from zero operations as defined in: + https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20210310-opt-in-autoscaling-from-zero.md + properties: + architecture: + description: |- + Architecture is the CPU architecture of the node. + Its underlying type is a string and its value can be any of amd64, arm64. + enum: + - amd64 + - arm64 + type: string + operatingSystem: + description: |- + OperatingSystem is the operating system of the node. + Its underlying type is a string and its value can be any of linux, windows. + enum: + - linux + - windows + type: string + type: object + type: object type: object served: true storage: true + subresources: + status: {} diff --git a/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpclusters.yaml b/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpclusters.yaml index e3fd64fb83a8..cd5f2b9bdd95 100644 --- a/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpclusters.yaml +++ b/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpclusters.yaml @@ -86,6 +86,8 @@ spec: description: |- CredentialsRef is a reference to a Secret that contains the credentials to use for provisioning this cluster. If not supplied then the credentials of the controller will be used. + When creating a new GCP client, the controller will try to extract the type + of credential from the JSON data, and it will request a client for the specific credential type. properties: name: description: |- @@ -138,6 +140,12 @@ spec: - Regional - Global type: string + ipAddress: + description: |- + IPAddress is the static IP address to use for the Load Balancer. + If not set, a new static IP address will be allocated. + If set, it must be a valid free IP address from the LoadBalancer Subnet. + type: string name: description: |- Name is the name of the Load Balancer. If not set a default name @@ -173,6 +181,26 @@ spec: Defaults to true. type: boolean + firewall: + description: Firewall configuration. + properties: + defaultRulesManagement: + default: Managed + description: |- + DefaultRulesManagement determines the management policy for the default firewall rules + created by the controller. DefaultRulesManagement has no effect on user specified firewall + rules. DefaultRulesManagement has no effect when a HostProject is specified. + "Managed": The controller will create and manage firewall rules. + "Unmanaged": The controller will not create or modify any firewall rules. If + the RulesManagement is changed from Managed to Unmanaged after the firewall rules + have been created, then the firewall rules will not be deleted. + + Defaults to "Managed". + enum: + - Managed + - Unmanaged + type: string + type: object hostProject: description: HostProject is the name of the project hosting the shared VPC network resources. @@ -182,6 +210,17 @@ spec: (useful for changing apiserver port) format: int32 type: integer + minPortsPerVm: + default: 64 + description: |- + MinPortsPerVM: Minimum number of ports allocated to a VM from this NAT + config. If not set, a default number of ports is allocated to a VM. This is + rounded up to the nearest power of 2. For example, if the value of this + field is 50, at least 64 ports are allocated to a VM. + format: int64 + maximum: 65536 + minimum: 2 + type: integer mtu: default: 1460 description: |- diff --git a/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpclustertemplates.yaml b/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpclustertemplates.yaml index ba16634af556..65ecfd888711 100644 --- a/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpclustertemplates.yaml +++ b/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpclustertemplates.yaml @@ -103,6 +103,8 @@ spec: description: |- CredentialsRef is a reference to a Secret that contains the credentials to use for provisioning this cluster. If not supplied then the credentials of the controller will be used. + When creating a new GCP client, the controller will try to extract the type + of credential from the JSON data, and it will request a client for the specific credential type. properties: name: description: |- @@ -156,6 +158,12 @@ spec: - Regional - Global type: string + ipAddress: + description: |- + IPAddress is the static IP address to use for the Load Balancer. + If not set, a new static IP address will be allocated. + If set, it must be a valid free IP address from the LoadBalancer Subnet. + type: string name: description: |- Name is the name of the Load Balancer. If not set a default name @@ -192,6 +200,26 @@ spec: Defaults to true. type: boolean + firewall: + description: Firewall configuration. + properties: + defaultRulesManagement: + default: Managed + description: |- + DefaultRulesManagement determines the management policy for the default firewall rules + created by the controller. DefaultRulesManagement has no effect on user specified firewall + rules. DefaultRulesManagement has no effect when a HostProject is specified. + "Managed": The controller will create and manage firewall rules. + "Unmanaged": The controller will not create or modify any firewall rules. If + the RulesManagement is changed from Managed to Unmanaged after the firewall rules + have been created, then the firewall rules will not be deleted. + + Defaults to "Managed". + enum: + - Managed + - Unmanaged + type: string + type: object hostProject: description: HostProject is the name of the project hosting the shared VPC network resources. @@ -201,6 +229,17 @@ spec: backend (useful for changing apiserver port) format: int32 type: integer + minPortsPerVm: + default: 64 + description: |- + MinPortsPerVM: Minimum number of ports allocated to a VM from this NAT + config. If not set, a default number of ports is allocated to a VM. This is + rounded up to the nearest power of 2. For example, if the value of this + field is 50, at least 64 ports are allocated to a VM. + format: int64 + maximum: 65536 + minimum: 2 + type: integer mtu: default: 1460 description: |- diff --git a/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpmachines.yaml b/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpmachines.yaml index 55fb7d3093e4..4f9bbe029f4c 100644 --- a/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpmachines.yaml +++ b/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpmachines.yaml @@ -191,6 +191,32 @@ spec: items: type: string type: array + aliasIPRanges: + description: AliasIPRanges let you assign ranges of internal IP addresses + as aliases to a VM's network interfaces. + items: + description: AliasIPRange is an alias IP range attached to an instance's + network interface. + properties: + ipCidrRange: + description: |- + IPCidrRange is the IP alias ranges to allocate for this interface. This IP + CIDR range must belong to the specified subnetwork and cannot contain IP + addresses reserved by system or used by other network interfaces. This range + may be a single IP address (such as 10.2.3.4), a netmask (such as /24) or a + CIDR-formatted string (such as 10.1.2.0/24). + pattern: ^((([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/([0-9]|[12][0-9]|3[0-2])|(([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(/([0-9]|[12][0-9]|3[0-2])))$ + type: string + subnetworkRangeName: + description: |- + SubnetworkRangeName is the name of a subnetwork secondary IP range from which + to allocate an IP alias range. If not specified, the primary range of the + subnetwork is used. + type: string + required: + - ipCidrRange + type: object + type: array confidentialCompute: description: |- ConfidentialCompute Defines whether the instance should have confidential compute enabled or not, and the confidential computing technology of choice. @@ -208,6 +234,31 @@ spec: - AMDEncryptedVirtualizationNestedPaging - IntelTrustedDomainExtensions type: string + guestAccelerators: + description: |- + GuestAccelerators is a list of the type and count of accelerator cards + attached to the instance. + items: + description: |- + Accelerator is a specification of the type and number of accelerator + cards attached to the instance. + properties: + count: + description: |- + Count is the number of the guest accelerator cards exposed to this + instance. + format: int64 + type: integer + type: + description: |- + Type is the full or partial URL of the accelerator type resource to + attach to this instance. For example: + projects/my-project/zones/us-central1-c/acceleratorTypes/nvidia-tesla-p100 + If you are creating an instance template, specify only the accelerator name. + See GPUs on Compute Engine for a full list of accelerator types. + type: string + type: object + type: array image: description: |- Image is the full reference to a valid image to be used for this machine. diff --git a/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpmachinetemplates.yaml b/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpmachinetemplates.yaml index 2131a1870de4..c1d6f6c9db39 100644 --- a/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpmachinetemplates.yaml +++ b/cmd/install/assets/cluster-api-provider-gcp/infrastructure.cluster.x-k8s.io_gcpmachinetemplates.yaml @@ -206,6 +206,32 @@ spec: items: type: string type: array + aliasIPRanges: + description: AliasIPRanges let you assign ranges of internal + IP addresses as aliases to a VM's network interfaces. + items: + description: AliasIPRange is an alias IP range attached + to an instance's network interface. + properties: + ipCidrRange: + description: |- + IPCidrRange is the IP alias ranges to allocate for this interface. This IP + CIDR range must belong to the specified subnetwork and cannot contain IP + addresses reserved by system or used by other network interfaces. This range + may be a single IP address (such as 10.2.3.4), a netmask (such as /24) or a + CIDR-formatted string (such as 10.1.2.0/24). + pattern: ^((([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/([0-9]|[12][0-9]|3[0-2])|(([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(/([0-9]|[12][0-9]|3[0-2])))$ + type: string + subnetworkRangeName: + description: |- + SubnetworkRangeName is the name of a subnetwork secondary IP range from which + to allocate an IP alias range. If not specified, the primary range of the + subnetwork is used. + type: string + required: + - ipCidrRange + type: object + type: array confidentialCompute: description: |- ConfidentialCompute Defines whether the instance should have confidential compute enabled or not, and the confidential computing technology of choice. @@ -223,6 +249,31 @@ spec: - AMDEncryptedVirtualizationNestedPaging - IntelTrustedDomainExtensions type: string + guestAccelerators: + description: |- + GuestAccelerators is a list of the type and count of accelerator cards + attached to the instance. + items: + description: |- + Accelerator is a specification of the type and number of accelerator + cards attached to the instance. + properties: + count: + description: |- + Count is the number of the guest accelerator cards exposed to this + instance. + format: int64 + type: integer + type: + description: |- + Type is the full or partial URL of the accelerator type resource to + attach to this instance. For example: + projects/my-project/zones/us-central1-c/acceleratorTypes/nvidia-tesla-p100 + If you are creating an instance template, specify only the accelerator name. + See GPUs on Compute Engine for a full list of accelerator types. + type: string + type: object + type: array image: description: |- Image is the full reference to a valid image to be used for this machine. diff --git a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsclusters.yaml b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsclusters.yaml index daaa224b2bd8..3161cf00121a 100644 --- a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsclusters.yaml +++ b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsclusters.yaml @@ -301,6 +301,54 @@ spec: - tcp - udp type: string + selector: + description: |- + The selector is used to find IBMPowerVSMachines with matching labels. + If the label matches, the machine is then added to the load balancer listener configuration. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic required: - port type: object diff --git a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsclustertemplates.yaml b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsclustertemplates.yaml index 79e17cf6fe28..0a5b74c5c2e3 100644 --- a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsclustertemplates.yaml +++ b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsclustertemplates.yaml @@ -336,6 +336,55 @@ spec: - tcp - udp type: string + selector: + description: |- + The selector is used to find IBMPowerVSMachines with matching labels. + If the label matches, the machine is then added to the load balancer listener configuration. + properties: + matchExpressions: + description: matchExpressions is a list of + label selector requirements. The requirements + are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic required: - port type: object diff --git a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsimages.yaml b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsimages.yaml index 1e2841cd2ab7..330db5e5c7e6 100644 --- a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsimages.yaml +++ b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmpowervsimages.yaml @@ -79,6 +79,7 @@ spec: description: Type of storage, storage pool with the most available space will be selected. enum: + - tier0 - tier1 - tier3 type: string @@ -253,6 +254,7 @@ spec: description: Type of storage, storage pool with the most available space will be selected. enum: + - tier0 - tier1 - tier3 type: string @@ -330,6 +332,74 @@ spec: ready: description: Ready is true when the provider resource is ready. type: boolean + v1beta2: + description: v1beta2 groups all the fields that will be added or modified + in IBMPowerVSCluster's status with the V1Beta2 version. + properties: + conditions: + description: conditions represents the observations of a DevCluster's + current state. + items: + description: Condition contains details for one aspect of the + current state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, + Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object type: object type: object served: true diff --git a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcclusters.yaml b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcclusters.yaml index a76af55c2267..1c82d012d2e5 100644 --- a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcclusters.yaml +++ b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcclusters.yaml @@ -293,6 +293,54 @@ spec: - tcp - udp type: string + selector: + description: |- + The selector is used to find IBMPowerVSMachines with matching labels. + If the label matches, the machine is then added to the load balancer listener configuration. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic required: - port type: object @@ -566,6 +614,55 @@ spec: - tcp - udp type: string + selector: + description: |- + The selector is used to find IBMPowerVSMachines with matching labels. + If the label matches, the machine is then added to the load balancer listener configuration. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic required: - port type: object @@ -1401,6 +1498,74 @@ spec: zone: type: string type: object + v1beta2: + description: V1beta2 groups all the fields that will be added or modified + in IBMVPCCluster's status with the V1Beta2 version. + properties: + conditions: + description: Conditions represents the observations of a IBMVPCCluster's + current state. + items: + description: Condition contains details for one aspect of the + current state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, + Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object vpc: description: |- Important: Run "make" to regenerate code after modifying this file diff --git a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcclustertemplates.yaml b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcclustertemplates.yaml index 2d08691fe6f5..6b6af9c486ad 100644 --- a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcclustertemplates.yaml +++ b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcclustertemplates.yaml @@ -136,6 +136,55 @@ spec: - tcp - udp type: string + selector: + description: |- + The selector is used to find IBMPowerVSMachines with matching labels. + If the label matches, the machine is then added to the load balancer listener configuration. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are + ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that + the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic required: - port type: object @@ -417,6 +466,55 @@ spec: - tcp - udp type: string + selector: + description: |- + The selector is used to find IBMPowerVSMachines with matching labels. + If the label matches, the machine is then added to the load balancer listener configuration. + properties: + matchExpressions: + description: matchExpressions is a list + of label selector requirements. The + requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key + that the selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic required: - port type: object diff --git a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcmachines.yaml b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcmachines.yaml index 14375be72763..abf31355e7be 100644 --- a/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcmachines.yaml +++ b/cmd/install/assets/cluster-api-provider-ibmcloud/infrastructure.cluster.x-k8s.io_ibmvpcmachines.yaml @@ -626,6 +626,74 @@ spec: ready: description: Ready is true when the provider resource is ready. type: boolean + v1beta2: + description: V1beta2 groups all the fields that will be added or modified + in IBMVPCMachine's status with the V1Beta2 version. + properties: + conditions: + description: Conditions represents the observations of a IBMVPCMachine's + current state. + items: + description: Condition contains details for one aspect of the + current state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, + Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object type: object type: object served: true diff --git a/cmd/install/assets/cluster-api-provider-kubevirt/infrastructure.cluster.x-k8s.io_kubevirtclustertemplates.yaml b/cmd/install/assets/cluster-api-provider-kubevirt/infrastructure.cluster.x-k8s.io_kubevirtclustertemplates.yaml index c12c1e06533f..bfa8e55385c9 100644 --- a/cmd/install/assets/cluster-api-provider-kubevirt/infrastructure.cluster.x-k8s.io_kubevirtclustertemplates.yaml +++ b/cmd/install/assets/cluster-api-provider-kubevirt/infrastructure.cluster.x-k8s.io_kubevirtclustertemplates.yaml @@ -247,9 +247,9 @@ spec: required: - template type: object + x-kubernetes-validations: + - message: KubevirtClusterTemplate Spec is immutable + rule: self == oldSelf type: object - x-kubernetes-validations: - - message: KubevirtClusterTemplate is immutable - rule: self == oldSelf served: true storage: true diff --git a/cmd/install/assets/cluster-api-provider-openstack/infrastructure.cluster.x-k8s.io_openstackclusters.yaml b/cmd/install/assets/cluster-api-provider-openstack/infrastructure.cluster.x-k8s.io_openstackclusters.yaml index 98bdda44ea06..9e4d79613f28 100644 --- a/cmd/install/assets/cluster-api-provider-openstack/infrastructure.cluster.x-k8s.io_openstackclusters.yaml +++ b/cmd/install/assets/cluster-api-provider-openstack/infrastructure.cluster.x-k8s.io_openstackclusters.yaml @@ -124,6 +124,35 @@ spec: description: Flavor is the flavor name that will be used to create the APIServerLoadBalancer Spec. type: string + monitor: + description: Monitor contains configuration for the load balancer + health monitor. + properties: + delay: + description: Delay is the time in seconds between sending + probes to members. + minimum: 0 + type: integer + maxRetries: + description: MaxRetries is the number of successful checks + before changing the operating status of the member to ONLINE. + maximum: 10 + minimum: 0 + type: integer + maxRetriesDown: + description: MaxRetriesDown is the number of allowed check + failures before changing the operating status of the member + to ERROR. + maximum: 10 + minimum: 1 + type: integer + timeout: + description: Timeout is the maximum time in seconds for a + monitor to wait for a connection to be established before + it times out. + minimum: 0 + type: integer + type: object network: description: Network defines which network should the load balancer be allocated on. @@ -1540,11 +1569,17 @@ spec: allowed are "ingress" or "egress". For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. + enum: + - ingress + - egress type: string etherType: description: |- etherType must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. + enum: + - IPv4 + - IPv6 type: string name: description: |- @@ -1620,11 +1655,17 @@ spec: allowed are "ingress" or "egress". For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. + enum: + - ingress + - egress type: string etherType: description: |- etherType must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. + enum: + - IPv4 + - IPv6 type: string name: description: |- @@ -1695,11 +1736,17 @@ spec: allowed are "ingress" or "egress". For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. + enum: + - ingress + - egress type: string etherType: description: |- etherType must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. + enum: + - IPv4 + - IPv6 type: string name: description: |- diff --git a/cmd/install/assets/cluster-api-provider-openstack/infrastructure.cluster.x-k8s.io_openstackclustertemplates.yaml b/cmd/install/assets/cluster-api-provider-openstack/infrastructure.cluster.x-k8s.io_openstackclustertemplates.yaml index 2e417e81ea26..4f9970ebf988 100644 --- a/cmd/install/assets/cluster-api-provider-openstack/infrastructure.cluster.x-k8s.io_openstackclustertemplates.yaml +++ b/cmd/install/assets/cluster-api-provider-openstack/infrastructure.cluster.x-k8s.io_openstackclustertemplates.yaml @@ -108,6 +108,36 @@ spec: description: Flavor is the flavor name that will be used to create the APIServerLoadBalancer Spec. type: string + monitor: + description: Monitor contains configuration for the load + balancer health monitor. + properties: + delay: + description: Delay is the time in seconds between + sending probes to members. + minimum: 0 + type: integer + maxRetries: + description: MaxRetries is the number of successful + checks before changing the operating status of the + member to ONLINE. + maximum: 10 + minimum: 0 + type: integer + maxRetriesDown: + description: MaxRetriesDown is the number of allowed + check failures before changing the operating status + of the member to ERROR. + maximum: 10 + minimum: 1 + type: integer + timeout: + description: Timeout is the maximum time in seconds + for a monitor to wait for a connection to be established + before it times out. + minimum: 0 + type: integer + type: object network: description: Network defines which network should the load balancer be allocated on. @@ -1546,11 +1576,17 @@ spec: allowed are "ingress" or "egress". For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. + enum: + - ingress + - egress type: string etherType: description: |- etherType must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. + enum: + - IPv4 + - IPv6 type: string name: description: |- @@ -1627,11 +1663,17 @@ spec: allowed are "ingress" or "egress". For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. + enum: + - ingress + - egress type: string etherType: description: |- etherType must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. + enum: + - IPv4 + - IPv6 type: string name: description: |- @@ -1702,11 +1744,17 @@ spec: allowed are "ingress" or "egress". For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. + enum: + - ingress + - egress type: string etherType: description: |- etherType must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. + enum: + - IPv4 + - IPv6 type: string name: description: |- diff --git a/cmd/install/assets/cluster-api/addons.cluster.x-k8s.io_clusterresourcesetbindings.yaml b/cmd/install/assets/cluster-api/addons.cluster.x-k8s.io_clusterresourcesetbindings.yaml index 4378293d420d..079634214623 100644 --- a/cmd/install/assets/cluster-api/addons.cluster.x-k8s.io_clusterresourcesetbindings.yaml +++ b/cmd/install/assets/cluster-api/addons.cluster.x-k8s.io_clusterresourcesetbindings.yaml @@ -17,11 +17,15 @@ spec: scope: Namespaced versions: - additionalPrinterColumns: + - description: Cluster + jsonPath: .spec.clusterName + name: Cluster + type: string - description: Time duration since creation of ClusterResourceSetBinding jsonPath: .metadata.creationTimestamp name: Age type: date - name: v1beta1 + name: v1beta2 schema: openAPIV3Schema: description: ClusterResourceSetBinding lists all matching ClusterResourceSets @@ -103,21 +107,25 @@ spec: type: object maxItems: 100 type: array + x-kubernetes-list-type: atomic required: - clusterResourceSetName type: object maxItems: 100 type: array + x-kubernetes-list-type: atomic clusterName: - description: |- - clusterName is the name of the Cluster this binding applies to. - Note: this field mandatory in v1beta2. + description: clusterName is the name of the Cluster this binding applies + to. maxLength: 63 minLength: 1 type: string + required: + - clusterName type: object + required: + - spec type: object served: true storage: true - subresources: - status: {} + subresources: {} diff --git a/cmd/install/assets/cluster-api/addons.cluster.x-k8s.io_clusterresourcesets.yaml b/cmd/install/assets/cluster-api/addons.cluster.x-k8s.io_clusterresourcesets.yaml index 0766fa28b4f8..c8e8a8154b41 100644 --- a/cmd/install/assets/cluster-api/addons.cluster.x-k8s.io_clusterresourcesets.yaml +++ b/cmd/install/assets/cluster-api/addons.cluster.x-k8s.io_clusterresourcesets.yaml @@ -17,11 +17,20 @@ spec: scope: Namespaced versions: - additionalPrinterColumns: + - description: Resource applied + jsonPath: .status.conditions[?(@.type=="ResourcesApplied")].status + name: Applied + type: string + - description: Reconciliation paused + jsonPath: .status.conditions[?(@.type=="Paused")].status + name: Paused + priority: 10 + type: string - description: Time duration since creation of ClusterResourceSet jsonPath: .metadata.creationTimestamp name: Age type: date - name: v1beta1 + name: v1beta2 schema: openAPIV3Schema: description: |- @@ -122,7 +131,9 @@ spec: - name type: object maxItems: 100 + minItems: 1 type: array + x-kubernetes-list-type: atomic strategy: description: strategy is the strategy to be used during applying resources. Defaults to ApplyOnce. This field is immutable. @@ -132,137 +143,150 @@ spec: type: string required: - clusterSelector + - resources type: object status: description: status is the observed state of ClusterResourceSet. + minProperties: 1 properties: conditions: - description: conditions defines current state of the ClusterResourceSet. + description: |- + conditions represents the observations of a ClusterResourceSet's current state. + Known condition types are ResourcesApplied. items: - description: Condition defines an observation of a Cluster API resource - operational state. + description: Condition contains details for one aspect of the current + state of this API Resource. properties: lastTransitionTime: description: |- lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. format: date-time type: string message: description: |- message is a human readable message indicating details about the transition. - This field may be empty. - maxLength: 10240 - minLength: 1 + This may be an empty string. + maxLength: 32768 type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer reason: description: |- - reason is the reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may be empty. - maxLength: 256 + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 minLength: 1 - type: string - severity: - description: |- - severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - maxLength: 32 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ type: string status: description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown type: string type: - description: |- - type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - maxLength: 256 - minLength: 1 + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ type: string required: - lastTransitionTime + - message + - reason - status - type type: object + maxItems: 32 type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. + properties: + v1beta1: + description: v1beta1 groups all the status fields that are deprecated + and will be removed when support for v1beta1 will be dropped. + properties: + conditions: + description: |- + conditions defines current state of the ClusterResourceSet. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + type: object + type: object observedGeneration: description: observedGeneration reflects the generation of the most recently observed ClusterResourceSet. format: int64 + minimum: 1 type: integer - v1beta2: - description: v1beta2 groups all the fields that will be added or modified - in ClusterResourceSet's status with the V1Beta2 version. - properties: - conditions: - description: |- - conditions represents the observations of a ClusterResourceSet's current state. - Known condition types are ResourceSetApplied, Deleting. - items: - description: Condition contains details for one aspect of the - current state of this API Resource. - properties: - lastTransitionTime: - description: |- - lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - message is a human readable message indicating details about the transition. - This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: |- - observedGeneration represents the .metadata.generation that the condition was set based upon. - For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date - with respect to the current state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: |- - reason contains a programmatic identifier indicating the reason for the condition's last transition. - Producers of specific condition types may define expected values and meanings for this field, - and whether the values are considered a guaranteed API. - The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, - Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - maxItems: 32 - type: array - x-kubernetes-list-map-keys: - - type - x-kubernetes-list-type: map - type: object type: object + required: + - spec type: object served: true storage: true diff --git a/cmd/install/assets/cluster-api/cluster.x-k8s.io_clusterclasses.yaml b/cmd/install/assets/cluster-api/cluster.x-k8s.io_clusterclasses.yaml index e4ec44377390..e429ac6527ca 100644 --- a/cmd/install/assets/cluster-api/cluster.x-k8s.io_clusterclasses.yaml +++ b/cmd/install/assets/cluster-api/cluster.x-k8s.io_clusterclasses.yaml @@ -23,6 +23,7 @@ spec: jsonPath: .metadata.creationTimestamp name: Age type: date + deprecated: true name: v1beta1 schema: openAPIV3Schema: @@ -2415,6 +2416,2472 @@ spec: type: object type: object served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - description: Reconciliation paused + jsonPath: .status.conditions[?(@.type=="Paused")].status + name: Paused + priority: 10 + type: string + - description: Variables ready + jsonPath: .status.conditions[?(@.type=="VariablesReady")].status + name: Variables Ready + type: string + - description: Time duration since creation of ClusterClass + jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1beta2 + schema: + openAPIV3Schema: + description: |- + ClusterClass is a template which can be used to create managed topologies. + NOTE: This CRD can only be used if the ClusterTopology feature gate is enabled. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec is the desired state of ClusterClass. + properties: + availabilityGates: + description: |- + availabilityGates specifies additional conditions to include when evaluating Cluster Available condition. + + NOTE: If a Cluster is using this ClusterClass, and this Cluster defines a custom list of availabilityGates, + such list overrides availabilityGates defined in this field. + items: + description: ClusterAvailabilityGate contains the type of a Cluster + condition to be used as availability gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Cluster's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as availability gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this availabilityGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + controlPlane: + description: |- + controlPlane is a reference to a local struct that holds the details + for provisioning the Control Plane for the Cluster. + properties: + deletion: + description: deletion contains configuration options for Machine + deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + NOTE: This value can be overridden while defining a Cluster.Topology. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + NOTE: This value can be overridden while defining a Cluster.Topology. + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + NOTE: This value can be overridden while defining a Cluster.Topology. + format: int32 + minimum: 0 + type: integer + type: object + healthCheck: + description: |- + healthCheck defines a MachineHealthCheck for this ControlPlaneClass. + This field is supported if and only if the ControlPlane provider template + referenced above is Machine based and supports setting replicas. + minProperties: 1 + properties: + checks: + description: |- + checks are the checks that are used to evaluate if a Machine is healthy. + + Independent of this configuration the MachineHealthCheck controller will always + flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + Machines with deleted Nodes as unhealthy. + + Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + is defaulted to 10 minutes and evaluated accordingly. + minProperties: 1 + properties: + nodeStartupTimeoutSeconds: + description: |- + nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + to consider a Machine unhealthy if a corresponding Node isn't associated + through a `Spec.ProviderID` field. + + The duration set in this field is compared to the greatest of: + - Cluster's infrastructure ready condition timestamp (if and when available) + - Control Plane's initialized condition timestamp (if and when available) + - Machine's infrastructure ready condition timestamp (if and when available) + - Machine's metadata creation timestamp + + Defaults to 10 minutes. + If you wish to disable this feature, set the value explicitly to 0. + format: int32 + minimum: 0 + type: integer + unhealthyNodeConditions: + description: |- + unhealthyNodeConditions contains a list of conditions that determine + whether a node is considered unhealthy. The conditions are combined in a + logical OR, i.e. if any of the conditions is met, the node is unhealthy. + items: + description: |- + UnhealthyNodeCondition represents a Node condition type and value with a timeout + specified as a duration. When the named condition has been in the given + status for at least the timeout value, a node is considered unhealthy. + properties: + status: + description: status of the condition, one of True, + False, Unknown. + minLength: 1 + type: string + timeoutSeconds: + description: |- + timeoutSeconds is the duration that a node must be in a given status for, + after which the node is considered unhealthy. + For example, with a value of "1h", the node must match the status + for at least 1 hour before being considered unhealthy. + format: int32 + minimum: 0 + type: integer + type: + description: type of Node condition + minLength: 1 + type: string + required: + - status + - timeoutSeconds + - type + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + type: object + remediation: + description: |- + remediation configures if and how remediations are triggered if a Machine is unhealthy. + + If remediation or remediation.triggerIf is not set, + remediation will always be triggered for unhealthy Machines. + + If remediation or remediation.templateRef is not set, + the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + minProperties: 1 + properties: + templateRef: + description: |- + templateRef is a reference to a remediation template + provided by an infrastructure provider. + + This field is completely optional, when filled, the MachineHealthCheck controller + creates a new object from the template referenced and hands off remediation of the machine to + a controller that lives outside of Cluster API. + properties: + apiVersion: + description: |- + apiVersion of the remediation template. + apiVersion must be fully qualified domain name followed by / and a version. + NOTE: This field must be kept in sync with the APIVersion of the remediation template. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the remediation template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the remediation template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + triggerIf: + description: |- + triggerIf configures if remediations are triggered. + If this field is not set, remediations are always triggered. + minProperties: 1 + properties: + unhealthyInRange: + description: |- + unhealthyInRange specifies that remediations are only triggered if the number of + unhealthy Machines is in the configured range. + Takes precedence over unhealthyLessThanOrEqualTo. + Eg. "[3-5]" - This means that remediation will be allowed only when: + (a) there are at least 3 unhealthy Machines (and) + (b) there are at most 5 unhealthy Machines + maxLength: 32 + minLength: 1 + pattern: ^\[[0-9]+-[0-9]+\]$ + type: string + unhealthyLessThanOrEqualTo: + anyOf: + - type: integer + - type: string + description: |- + unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + unhealthy Machines is less than or equal to the configured value. + unhealthyInRange takes precedence if set. + x-kubernetes-int-or-string: true + type: object + type: object + type: object + machineInfrastructure: + description: |- + machineInfrastructure defines the metadata and infrastructure information + for control plane machines. + + This field is supported if and only if the control plane provider template + referenced above is Machine based and supports setting replicas. + properties: + templateRef: + description: templateRef is a required reference to the template + for a MachineInfrastructure of a ControlPlane. + properties: + apiVersion: + description: |- + apiVersion of the template. + apiVersion must be fully qualified domain name followed by / and a version. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + required: + - templateRef + type: object + metadata: + description: |- + metadata is the metadata applied to the ControlPlane and the Machines of the ControlPlane + if the ControlPlaneTemplate referenced is machine based. If not, it is applied only to the + ControlPlane. + At runtime this metadata is merged with the corresponding metadata from the topology. + + This field is supported if and only if the control plane provider template + referenced is Machine based. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + naming: + description: naming allows changing the naming pattern used when + creating the control plane provider object. + minProperties: 1 + properties: + template: + description: |- + template defines the template to use for generating the name of the ControlPlane object. + If not defined, it will fallback to `{{ .cluster.name }}-{{ .random }}`. + If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will + get concatenated with a random suffix of length 5. + The templating mechanism provides the following arguments: + * `.cluster.name`: The name of the cluster object. + * `.random`: A random alphanumeric string, without vowels, of length 5. + maxLength: 1024 + minLength: 1 + type: string + type: object + readinessGates: + description: |- + readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + + This field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready + computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine. + + NOTE: If a Cluster defines a custom list of readinessGates for the control plane, + such list overrides readinessGates defined in this field. + NOTE: Specific control plane provider implementations might automatically extend the list of readinessGates; + e.g. the kubeadm control provider adds ReadinessGates for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + items: + description: MachineReadinessGate contains the type of a Machine + condition to be used as a readiness gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Machine's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this readinessGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + templateRef: + description: templateRef contains the reference to a provider-specific + control plane template. + properties: + apiVersion: + description: |- + apiVersion of the template. + apiVersion must be fully qualified domain name followed by / and a version. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + required: + - templateRef + type: object + infrastructure: + description: |- + infrastructure is a reference to a local struct that holds the details + for provisioning the infrastructure cluster for the Cluster. + properties: + naming: + description: naming allows changing the naming pattern used when + creating the infrastructure cluster object. + minProperties: 1 + properties: + template: + description: |- + template defines the template to use for generating the name of the Infrastructure object. + If not defined, it will fallback to `{{ .cluster.name }}-{{ .random }}`. + If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will + get concatenated with a random suffix of length 5. + The templating mechanism provides the following arguments: + * `.cluster.name`: The name of the cluster object. + * `.random`: A random alphanumeric string, without vowels, of length 5. + maxLength: 1024 + minLength: 1 + type: string + type: object + templateRef: + description: templateRef contains the reference to a provider-specific + infrastructure cluster template. + properties: + apiVersion: + description: |- + apiVersion of the template. + apiVersion must be fully qualified domain name followed by / and a version. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + required: + - templateRef + type: object + patches: + description: |- + patches defines the patches which are applied to customize + referenced templates of a ClusterClass. + Note: Patches will be applied in the order of the array. + items: + description: ClusterClassPatch defines a patch which is applied + to customize the referenced templates. + properties: + definitions: + description: |- + definitions define inline patches. + Note: Patches will be applied in the order of the array. + Note: Exactly one of Definitions or External must be set. + items: + description: PatchDefinition defines a patch which is applied + to customize the referenced templates. + properties: + jsonPatches: + description: |- + jsonPatches defines the patches which should be applied on the templates + matching the selector. + Note: Patches will be applied in the order of the array. + items: + description: JSONPatch defines a JSON patch. + properties: + op: + description: |- + op defines the operation of the patch. + Note: Only `add`, `replace` and `remove` are supported. + enum: + - add + - replace + - remove + type: string + path: + description: |- + path defines the path of the patch. + Note: Only the spec of a template can be patched, thus the path has to start with /spec/. + Note: For now the only allowed array modifications are `append` and `prepend`, i.e.: + * for op: `add`: only index 0 (prepend) and - (append) are allowed + * for op: `replace` or `remove`: no indexes are allowed + maxLength: 512 + minLength: 1 + type: string + value: + description: |- + value defines the value of the patch. + Note: Either Value or ValueFrom is required for add and replace + operations. Only one of them is allowed to be set at the same time. + Note: We have to use apiextensionsv1.JSON instead of our JSON type, + because controller-tools has a hard-coded schema for apiextensionsv1.JSON + which cannot be produced by another type (unset type field). + Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111 + x-kubernetes-preserve-unknown-fields: true + valueFrom: + description: |- + valueFrom defines the value of the patch. + Note: Either Value or ValueFrom is required for add and replace + operations. Only one of them is allowed to be set at the same time. + properties: + template: + description: |- + template is the Go template to be used to calculate the value. + A template can reference variables defined in .spec.variables and builtin variables. + Note: The template must evaluate to a valid YAML or JSON value. + maxLength: 10240 + minLength: 1 + type: string + variable: + description: |- + variable is the variable to be used as value. + Variable can be one of the variables defined in .spec.variables or a builtin variable. + maxLength: 256 + minLength: 1 + type: string + type: object + required: + - op + - path + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + selector: + description: selector defines on which templates the patch + should be applied. + properties: + apiVersion: + description: |- + apiVersion filters templates by apiVersion. + apiVersion must be fully qualified domain name followed by / and a version. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind filters templates by kind. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + matchResources: + description: matchResources selects templates based + on where they are referenced. + minProperties: 1 + properties: + controlPlane: + description: |- + controlPlane selects templates referenced in .spec.ControlPlane. + Note: this will match the controlPlane and also the controlPlane + machineInfrastructure (depending on the kind and apiVersion). + type: boolean + infrastructureCluster: + description: infrastructureCluster selects templates + referenced in .spec.infrastructure. + type: boolean + machineDeploymentClass: + description: |- + machineDeploymentClass selects templates referenced in specific MachineDeploymentClasses in + .spec.workers.machineDeployments. + properties: + names: + description: names selects templates by class + names. + items: + maxLength: 256 + minLength: 1 + type: string + maxItems: 100 + type: array + x-kubernetes-list-type: atomic + type: object + machinePoolClass: + description: |- + machinePoolClass selects templates referenced in specific MachinePoolClasses in + .spec.workers.machinePools. + properties: + names: + description: names selects templates by class + names. + items: + maxLength: 256 + minLength: 1 + type: string + maxItems: 100 + type: array + x-kubernetes-list-type: atomic + type: object + type: object + required: + - apiVersion + - kind + - matchResources + type: object + required: + - jsonPatches + - selector + type: object + maxItems: 100 + type: array + x-kubernetes-list-type: atomic + description: + description: description is a human-readable description of + this patch. + maxLength: 1024 + minLength: 1 + type: string + enabledIf: + description: |- + enabledIf is a Go template to be used to calculate if a patch should be enabled. + It can reference variables defined in .spec.variables and builtin variables. + The patch will be enabled if the template evaluates to `true`, otherwise it will + be disabled. + If EnabledIf is not set, the patch will be enabled per default. + maxLength: 256 + minLength: 1 + type: string + external: + description: |- + external defines an external patch. + Note: Exactly one of Definitions or External must be set. + properties: + discoverVariablesExtension: + description: discoverVariablesExtension references an extension + which is called to discover variables. + maxLength: 512 + minLength: 1 + type: string + generatePatchesExtension: + description: generatePatchesExtension references an extension + which is called to generate patches. + maxLength: 512 + minLength: 1 + type: string + settings: + additionalProperties: + type: string + description: |- + settings defines key value pairs to be passed to the extensions. + Values defined here take precedence over the values defined in the + corresponding ExtensionConfig. + type: object + validateTopologyExtension: + description: validateTopologyExtension references an extension + which is called to validate the topology. + maxLength: 512 + minLength: 1 + type: string + type: object + name: + description: name of the patch. + maxLength: 256 + minLength: 1 + type: string + required: + - name + type: object + maxItems: 1000 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + variables: + description: |- + variables defines the variables which can be configured + in the Cluster topology and are then used in patches. + items: + description: |- + ClusterClassVariable defines a variable which can + be configured in the Cluster topology and used in patches. + properties: + deprecatedV1Beta1Metadata: + description: |- + deprecatedV1Beta1Metadata is the metadata of a variable. + It can be used to add additional data for higher level tools to + a ClusterClassVariable. + + Deprecated: This field is deprecated and will be removed when support for v1beta1 will be dropped. Please use XMetadata in JSONSchemaProps instead. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map that can be used to store and + retrieve arbitrary metadata. + They are not queryable. + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) variables. + type: object + type: object + name: + description: name of the variable. + maxLength: 256 + minLength: 1 + type: string + required: + description: |- + required specifies if the variable is required. + Note: this applies to the variable as a whole and thus the + top-level object defined in the schema. If nested fields are + required, this will be specified inside the schema. + type: boolean + schema: + description: schema defines the schema of the variable. + properties: + openAPIV3Schema: + description: |- + openAPIV3Schema defines the schema of a variable via OpenAPI v3 + schema. The schema is a subset of the schema used in + Kubernetes CRDs. + minProperties: 1 + properties: + additionalProperties: + description: |- + additionalProperties specifies the schema of values in a map (keys are always strings). + NOTE: Can only be set if type is object. + NOTE: AdditionalProperties is mutually exclusive with Properties. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + allOf: + description: |- + allOf specifies that the variable must validate against all of the subschemas in the array. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + anyOf: + description: |- + anyOf specifies that the variable must validate against one or more of the subschemas in the array. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + default: + description: |- + default is the default value of the variable. + NOTE: Can be set for all types. + x-kubernetes-preserve-unknown-fields: true + description: + description: description is a human-readable description + of this variable. + maxLength: 4096 + minLength: 1 + type: string + enum: + description: |- + enum is the list of valid values of the variable. + NOTE: Can be set for all types. + items: + x-kubernetes-preserve-unknown-fields: true + maxItems: 100 + type: array + x-kubernetes-list-type: atomic + example: + description: example is an example for this variable. + x-kubernetes-preserve-unknown-fields: true + exclusiveMaximum: + description: |- + exclusiveMaximum specifies if the Maximum is exclusive. + NOTE: Can only be set if type is integer or number. + type: boolean + exclusiveMinimum: + description: |- + exclusiveMinimum specifies if the Minimum is exclusive. + NOTE: Can only be set if type is integer or number. + type: boolean + format: + description: |- + format is an OpenAPI v3 format string. Unknown formats are ignored. + For a list of supported formats please see: (of the k8s.io/apiextensions-apiserver version we're currently using) + https://github.com/kubernetes/apiextensions-apiserver/blob/master/pkg/apiserver/validation/formats.go + NOTE: Can only be set if type is string. + maxLength: 32 + minLength: 1 + type: string + items: + description: |- + items specifies fields of an array. + NOTE: Can only be set if type is array. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + maxItems: + description: |- + maxItems is the max length of an array variable. + NOTE: Can only be set if type is array. + format: int64 + type: integer + maxLength: + description: |- + maxLength is the max length of a string variable. + NOTE: Can only be set if type is string. + format: int64 + type: integer + maxProperties: + description: |- + maxProperties is the maximum amount of entries in a map or properties in an object. + NOTE: Can only be set if type is object. + format: int64 + type: integer + maximum: + description: |- + maximum is the maximum of an integer or number variable. + If ExclusiveMaximum is false, the variable is valid if it is lower than, or equal to, the value of Maximum. + If ExclusiveMaximum is true, the variable is valid if it is strictly lower than the value of Maximum. + NOTE: Can only be set if type is integer or number. + format: int64 + type: integer + minItems: + description: |- + minItems is the min length of an array variable. + NOTE: Can only be set if type is array. + format: int64 + type: integer + minLength: + description: |- + minLength is the min length of a string variable. + NOTE: Can only be set if type is string. + format: int64 + type: integer + minProperties: + description: |- + minProperties is the minimum amount of entries in a map or properties in an object. + NOTE: Can only be set if type is object. + format: int64 + type: integer + minimum: + description: |- + minimum is the minimum of an integer or number variable. + If ExclusiveMinimum is false, the variable is valid if it is greater than, or equal to, the value of Minimum. + If ExclusiveMinimum is true, the variable is valid if it is strictly greater than the value of Minimum. + NOTE: Can only be set if type is integer or number. + format: int64 + type: integer + not: + description: |- + not specifies that the variable must not validate against the subschema. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + oneOf: + description: |- + oneOf specifies that the variable must validate against exactly one of the subschemas in the array. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + pattern: + description: |- + pattern is the regex which a string variable must match. + NOTE: Can only be set if type is string. + maxLength: 512 + minLength: 1 + type: string + properties: + description: |- + properties specifies fields of an object. + NOTE: Can only be set if type is object. + NOTE: Properties is mutually exclusive with AdditionalProperties. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + required: + description: |- + required specifies which fields of an object are required. + NOTE: Can only be set if type is object. + items: + maxLength: 256 + minLength: 1 + type: string + maxItems: 1000 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + type: + description: |- + type is the type of the variable. + Valid values are: object, array, string, integer, number or boolean. + enum: + - object + - array + - string + - integer + - number + - boolean + type: string + uniqueItems: + description: |- + uniqueItems specifies if items in an array must be unique. + NOTE: Can only be set if type is array. + type: boolean + x-kubernetes-int-or-string: + description: |- + x-kubernetes-int-or-string specifies that this value is + either an integer or a string. If this is true, an empty + type is allowed and type as child of anyOf is permitted + if following one of the following patterns: + + 1) anyOf: + - type: integer + - type: string + 2) allOf: + - anyOf: + - type: integer + - type: string + - ... zero or more + type: boolean + x-kubernetes-preserve-unknown-fields: + description: |- + x-kubernetes-preserve-unknown-fields allows setting fields in a variable object + which are not defined in the variable schema. This affects fields recursively, + except if nested properties or additionalProperties are specified in the schema. + type: boolean + x-kubernetes-validations: + description: x-kubernetes-validations describes a list + of validation rules written in the CEL expression + language. + items: + description: ValidationRule describes a validation + rule written in the CEL expression language. + properties: + fieldPath: + description: |- + fieldPath represents the field path returned when the validation fails. + It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. + e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo` + If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList` + It does not support list numeric index. + It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info. + Numeric index of array is not supported. + For field name which contains special characters, use `['specialName']` to refer the field name. + e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']` + maxLength: 512 + minLength: 1 + type: string + message: + description: |- + message represents the message displayed when validation fails. The message is required if the Rule contains + line breaks. The message must not contain line breaks. + If unset, the message is "failed rule: {Rule}". + e.g. "must be a URL with the host matching spec.host" + maxLength: 512 + minLength: 1 + type: string + messageExpression: + description: |- + messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. + Since messageExpression is used as a failure message, it must evaluate to a string. + If both message and messageExpression are present on a rule, then messageExpression will be used if validation + fails. If messageExpression results in a runtime error, the validation failure message is produced + as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string + that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset. + messageExpression has access to all the same variables as the rule; the only difference is the return type. + Example: + "x must be less than max ("+string(self.max)+")" + maxLength: 1024 + minLength: 1 + type: string + reason: + default: FieldValueInvalid + description: |- + reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule. + The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate". + If not set, default to use "FieldValueInvalid". + All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid. + enum: + - FieldValueInvalid + - FieldValueForbidden + - FieldValueRequired + - FieldValueDuplicate + type: string + rule: + description: "rule represents the expression which + will be evaluated by CEL.\nref: https://github.com/google/cel-spec\nThe + Rule is scoped to the location of the x-kubernetes-validations + extension in the schema.\nThe `self` variable + in the CEL expression is bound to the scoped + value.\nIf the Rule is scoped to an object with + properties, the accessible properties of the + object are field selectable\nvia `self.field` + and field presence can be checked via `has(self.field)`.\nIf + the Rule is scoped to an object with additionalProperties + (i.e. a map) the value of the map\nare accessible + via `self[mapKey]`, map containment can be checked + via `mapKey in self` and all entries of the + map\nare accessible via CEL macros and functions + such as `self.all(...)`.\nIf the Rule is scoped + to an array, the elements of the array are accessible + via `self[i]` and also by macros and\nfunctions.\nIf + the Rule is scoped to a scalar, `self` is bound + to the scalar value.\nExamples:\n- Rule scoped + to a map of objects: {\"rule\": \"self.components['Widget'].priority + < 10\"}\n- Rule scoped to a list of integers: + {\"rule\": \"self.values.all(value, value >= + 0 && value < 100)\"}\n- Rule scoped to a string + value: {\"rule\": \"self.startsWith('kube')\"}\n\nUnknown + data preserved in custom resources via x-kubernetes-preserve-unknown-fields + is not accessible in CEL\nexpressions. This + includes:\n- Unknown field values that are preserved + by object schemas with x-kubernetes-preserve-unknown-fields.\n- + Object properties where the property schema + is of an \"unknown type\". An \"unknown type\" + is recursively defined as:\n - A schema with + no type and x-kubernetes-preserve-unknown-fields + set to true\n - An array where the items schema + is of an \"unknown type\"\n - An object where + the additionalProperties schema is of an \"unknown + type\"\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` + are accessible.\nAccessible property names are + escaped according to the following rules when + accessed in the expression:\n- '__' escapes + to '__underscores__'\n- '.' escapes to '__dot__'\n- + '-' escapes to '__dash__'\n- '/' escapes to + '__slash__'\n- Property names that exactly match + a CEL RESERVED keyword escape to '__{keyword}__'. + The keywords are:\n\t \"true\", \"false\", + \"null\", \"in\", \"as\", \"break\", \"const\", + \"continue\", \"else\", \"for\", \"function\", + \"if\",\n\t \"import\", \"let\", \"loop\", + \"package\", \"namespace\", \"return\".\nExamples:\n + \ - Rule accessing a property named \"namespace\": + {\"rule\": \"self.__namespace__ > 0\"}\n - + Rule accessing a property named \"x-prop\": + {\"rule\": \"self.x__dash__prop > 0\"}\n - + Rule accessing a property named \"redact__d\": + {\"rule\": \"self.redact__underscores__d > 0\"}\n\nIf + `rule` makes use of the `oldSelf` variable it + is implicitly a\n`transition rule`.\n\nBy default, + the `oldSelf` variable is the same type as `self`.\n\nTransition + rules by default are applied only on UPDATE + requests and are\nskipped if an old value could + not be found." + maxLength: 4096 + minLength: 1 + type: string + required: + - rule + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - rule + x-kubernetes-list-type: map + x-metadata: + description: |- + x-metadata is the metadata of a variable or a nested field within a variable. + It can be used to add additional data for higher level tools. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map that can be used to store and + retrieve arbitrary metadata. + They are not queryable. + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) variables. + type: object + type: object + type: object + required: + - openAPIV3Schema + type: object + required: + - name + - required + - schema + type: object + maxItems: 1000 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + workers: + description: |- + workers describes the worker nodes for the cluster. + It is a collection of node types which can be used to create + the worker nodes of the cluster. + minProperties: 1 + properties: + machineDeployments: + description: |- + machineDeployments is a list of machine deployment classes that can be used to create + a set of worker nodes. + items: + description: |- + MachineDeploymentClass serves as a template to define a set of worker nodes of the cluster + provisioned using the `ClusterClass`. + properties: + bootstrap: + description: |- + bootstrap contains the bootstrap template reference to be used + for the creation of worker Machines. + properties: + templateRef: + description: templateRef is a required reference to + the BootstrapTemplate for a MachineDeployment. + properties: + apiVersion: + description: |- + apiVersion of the template. + apiVersion must be fully qualified domain name followed by / and a version. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + required: + - templateRef + type: object + class: + description: |- + class denotes a type of worker node present in the cluster, + this name MUST be unique within a ClusterClass and can be referenced + in the Cluster to create a managed MachineDeployment. + maxLength: 256 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options for + Machine deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + format: int32 + minimum: 0 + type: integer + order: + description: |- + order defines the order in which Machines are deleted when downscaling. + Defaults to "Random". Valid values are "Random, "Newest", "Oldest" + enum: + - Random + - Newest + - Oldest + type: string + type: object + failureDomain: + description: |- + failureDomain is the failure domain the machines will be created in. + Must match the name of a FailureDomain from the Cluster status. + NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + maxLength: 256 + minLength: 1 + type: string + healthCheck: + description: healthCheck defines a MachineHealthCheck for + this MachineDeploymentClass. + minProperties: 1 + properties: + checks: + description: |- + checks are the checks that are used to evaluate if a Machine is healthy. + + Independent of this configuration the MachineHealthCheck controller will always + flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + Machines with deleted Nodes as unhealthy. + + Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + is defaulted to 10 minutes and evaluated accordingly. + minProperties: 1 + properties: + nodeStartupTimeoutSeconds: + description: |- + nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + to consider a Machine unhealthy if a corresponding Node isn't associated + through a `Spec.ProviderID` field. + + The duration set in this field is compared to the greatest of: + - Cluster's infrastructure ready condition timestamp (if and when available) + - Control Plane's initialized condition timestamp (if and when available) + - Machine's infrastructure ready condition timestamp (if and when available) + - Machine's metadata creation timestamp + + Defaults to 10 minutes. + If you wish to disable this feature, set the value explicitly to 0. + format: int32 + minimum: 0 + type: integer + unhealthyNodeConditions: + description: |- + unhealthyNodeConditions contains a list of conditions that determine + whether a node is considered unhealthy. The conditions are combined in a + logical OR, i.e. if any of the conditions is met, the node is unhealthy. + items: + description: |- + UnhealthyNodeCondition represents a Node condition type and value with a timeout + specified as a duration. When the named condition has been in the given + status for at least the timeout value, a node is considered unhealthy. + properties: + status: + description: status of the condition, one + of True, False, Unknown. + minLength: 1 + type: string + timeoutSeconds: + description: |- + timeoutSeconds is the duration that a node must be in a given status for, + after which the node is considered unhealthy. + For example, with a value of "1h", the node must match the status + for at least 1 hour before being considered unhealthy. + format: int32 + minimum: 0 + type: integer + type: + description: type of Node condition + minLength: 1 + type: string + required: + - status + - timeoutSeconds + - type + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + type: object + remediation: + description: |- + remediation configures if and how remediations are triggered if a Machine is unhealthy. + + If remediation or remediation.triggerIf is not set, + remediation will always be triggered for unhealthy Machines. + + If remediation or remediation.templateRef is not set, + the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + minProperties: 1 + properties: + maxInFlight: + anyOf: + - type: integer + - type: string + description: |- + maxInFlight determines how many in flight remediations should happen at the same time. + + Remediation only happens on the MachineSet with the most current revision, while + older MachineSets (usually present during rollout operations) aren't allowed to remediate. + + Note: In general (independent of remediations), unhealthy machines are always + prioritized during scale down operations over healthy ones. + + MaxInFlight can be set to a fixed number or a percentage. + Example: when this is set to 20%, the MachineSet controller deletes at most 20% of + the desired replicas. + + If not set, remediation is limited to all machines (bounded by replicas) + under the active MachineSet's management. + x-kubernetes-int-or-string: true + templateRef: + description: |- + templateRef is a reference to a remediation template + provided by an infrastructure provider. + + This field is completely optional, when filled, the MachineHealthCheck controller + creates a new object from the template referenced and hands off remediation of the machine to + a controller that lives outside of Cluster API. + properties: + apiVersion: + description: |- + apiVersion of the remediation template. + apiVersion must be fully qualified domain name followed by / and a version. + NOTE: This field must be kept in sync with the APIVersion of the remediation template. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the remediation template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the remediation template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + triggerIf: + description: |- + triggerIf configures if remediations are triggered. + If this field is not set, remediations are always triggered. + minProperties: 1 + properties: + unhealthyInRange: + description: |- + unhealthyInRange specifies that remediations are only triggered if the number of + unhealthy Machines is in the configured range. + Takes precedence over unhealthyLessThanOrEqualTo. + Eg. "[3-5]" - This means that remediation will be allowed only when: + (a) there are at least 3 unhealthy Machines (and) + (b) there are at most 5 unhealthy Machines + maxLength: 32 + minLength: 1 + pattern: ^\[[0-9]+-[0-9]+\]$ + type: string + unhealthyLessThanOrEqualTo: + anyOf: + - type: integer + - type: string + description: |- + unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + unhealthy Machines is less than or equal to the configured value. + unhealthyInRange takes precedence if set. + x-kubernetes-int-or-string: true + type: object + type: object + type: object + infrastructure: + description: |- + infrastructure contains the infrastructure template reference to be used + for the creation of worker Machines. + properties: + templateRef: + description: templateRef is a required reference to + the InfrastructureTemplate for a MachineDeployment. + properties: + apiVersion: + description: |- + apiVersion of the template. + apiVersion must be fully qualified domain name followed by / and a version. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + required: + - templateRef + type: object + metadata: + description: |- + metadata is the metadata applied to the MachineDeployment and the machines of the MachineDeployment. + At runtime this metadata is merged with the corresponding metadata from the topology. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + minReadySeconds: + description: |- + minReadySeconds is the minimum number of seconds for which a newly created machine should + be ready. + Defaults to 0 (machine will be considered available as soon as it + is ready) + NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + format: int32 + minimum: 0 + type: integer + naming: + description: naming allows changing the naming pattern used + when creating the MachineDeployment. + minProperties: 1 + properties: + template: + description: |- + template defines the template to use for generating the name of the MachineDeployment object. + If not defined, it will fallback to `{{ .cluster.name }}-{{ .machineDeployment.topologyName }}-{{ .random }}`. + If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will + get concatenated with a random suffix of length 5. + The templating mechanism provides the following arguments: + * `.cluster.name`: The name of the cluster object. + * `.random`: A random alphanumeric string, without vowels, of length 5. + * `.machineDeployment.topologyName`: The name of the MachineDeployment topology (Cluster.spec.topology.workers.machineDeployments[].name). + maxLength: 1024 + minLength: 1 + type: string + type: object + readinessGates: + description: |- + readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + + This field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready + computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine. + + NOTE: If a Cluster defines a custom list of readinessGates for a MachineDeployment using this MachineDeploymentClass, + such list overrides readinessGates defined in this field. + items: + description: MachineReadinessGate contains the type of + a Machine condition to be used as a readiness gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Machine's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this readinessGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + rollout: + description: |- + rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. + It allows you to define the strategy used during rolling replacements. + minProperties: 1 + properties: + strategy: + description: strategy specifies how to roll out control + plane Machines. + minProperties: 1 + properties: + rollingUpdate: + description: |- + rollingUpdate is the rolling update config params. Present only if + type = RollingUpdate. + minProperties: 1 + properties: + maxSurge: + anyOf: + - type: integer + - type: string + description: |- + maxSurge is the maximum number of machines that can be scheduled above the + desired number of machines. + Value can be an absolute number (ex: 5) or a percentage of + desired machines (ex: 10%). + This can not be 0 if MaxUnavailable is 0. + Absolute number is calculated from percentage by rounding up. + Defaults to 1. + Example: when this is set to 30%, the new MachineSet can be scaled + up immediately when the rolling update starts, such that the total + number of old and new machines do not exceed 130% of desired + machines. Once old machines have been killed, new MachineSet can + be scaled up further, ensuring that total number of machines running + at any time during the update is at most 130% of desired machines. + x-kubernetes-int-or-string: true + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of machines that can be unavailable during the update. + Value can be an absolute number (ex: 5) or a percentage of desired + machines (ex: 10%). + Absolute number is calculated from percentage by rounding down. + This can not be 0 if MaxSurge is 0. + Defaults to 0. + Example: when this is set to 30%, the old MachineSet can be scaled + down to 70% of desired machines immediately when the rolling update + starts. Once new machines are ready, old MachineSet can be scaled + down further, followed by scaling up the new MachineSet, ensuring + that the total number of machines available at all times + during the update is at least 70% of desired machines. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type of rollout. Allowed values are RollingUpdate and OnDelete. + Default is RollingUpdate. + enum: + - RollingUpdate + - OnDelete + type: string + required: + - type + type: object + type: object + required: + - bootstrap + - class + - infrastructure + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - class + x-kubernetes-list-type: map + machinePools: + description: |- + machinePools is a list of machine pool classes that can be used to create + a set of worker nodes. + items: + description: |- + MachinePoolClass serves as a template to define a pool of worker nodes of the cluster + provisioned using `ClusterClass`. + properties: + bootstrap: + description: |- + bootstrap contains the bootstrap template reference to be used + for the creation of the Machines in the MachinePool. + properties: + templateRef: + description: templateRef is a required reference to + the BootstrapTemplate for a MachinePool. + properties: + apiVersion: + description: |- + apiVersion of the template. + apiVersion must be fully qualified domain name followed by / and a version. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + required: + - templateRef + type: object + class: + description: |- + class denotes a type of machine pool present in the cluster, + this name MUST be unique within a ClusterClass and can be referenced + in the Cluster to create a managed MachinePool. + maxLength: 256 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options for + Machine deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine Pool is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + format: int32 + minimum: 0 + type: integer + type: object + failureDomains: + description: |- + failureDomains is the list of failure domains the MachinePool should be attached to. + Must match a key in the FailureDomains map stored on the cluster object. + NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + items: + maxLength: 256 + minLength: 1 + type: string + maxItems: 100 + type: array + x-kubernetes-list-type: atomic + infrastructure: + description: |- + infrastructure contains the infrastructure template reference to be used + for the creation of the MachinePool. + properties: + templateRef: + description: templateRef is a required reference to + the InfrastructureTemplate for a MachinePool. + properties: + apiVersion: + description: |- + apiVersion of the template. + apiVersion must be fully qualified domain name followed by / and a version. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + required: + - templateRef + type: object + metadata: + description: |- + metadata is the metadata applied to the MachinePool. + At runtime this metadata is merged with the corresponding metadata from the topology. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + minReadySeconds: + description: |- + minReadySeconds is the minimum number of seconds for which a newly created machine pool should + be ready. + Defaults to 0 (machine will be considered available as soon as it + is ready) + NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + format: int32 + minimum: 0 + type: integer + naming: + description: naming allows changing the naming pattern used + when creating the MachinePool. + minProperties: 1 + properties: + template: + description: |- + template defines the template to use for generating the name of the MachinePool object. + If not defined, it will fallback to `{{ .cluster.name }}-{{ .machinePool.topologyName }}-{{ .random }}`. + If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will + get concatenated with a random suffix of length 5. + The templating mechanism provides the following arguments: + * `.cluster.name`: The name of the cluster object. + * `.random`: A random alphanumeric string, without vowels, of length 5. + * `.machinePool.topologyName`: The name of the MachinePool topology (Cluster.spec.topology.workers.machinePools[].name). + maxLength: 1024 + minLength: 1 + type: string + type: object + required: + - bootstrap + - class + - infrastructure + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - class + x-kubernetes-list-type: map + type: object + required: + - controlPlane + - infrastructure + type: object + status: + description: status is the observed state of ClusterClass. + minProperties: 1 + properties: + conditions: + description: |- + conditions represents the observations of a ClusterClass's current state. + Known condition types are VariablesReady, RefVersionsUpToDate, Paused. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. + properties: + v1beta1: + description: v1beta1 groups all the status fields that are deprecated + and will be removed when support for v1beta1 will be dropped. + properties: + conditions: + description: |- + conditions defines current observed state of the ClusterClass. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + type: object + type: object + observedGeneration: + description: observedGeneration is the latest generation observed + by the controller. + format: int64 + minimum: 1 + type: integer + variables: + description: variables is a list of ClusterClassStatusVariable that + are defined for the ClusterClass. + items: + description: ClusterClassStatusVariable defines a variable which + appears in the status of a ClusterClass. + properties: + definitions: + description: definitions is a list of definitions for a variable. + items: + description: ClusterClassStatusVariableDefinition defines + a variable which appears in the status of a ClusterClass. + properties: + deprecatedV1Beta1Metadata: + description: |- + deprecatedV1Beta1Metadata is the metadata of a variable. + It can be used to add additional data for higher level tools to + a ClusterClassVariable. + + Deprecated: This field is deprecated and will be removed when support for v1beta1 will be dropped. Please use XMetadata in JSONSchemaProps instead. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map that can be used to store and + retrieve arbitrary metadata. + They are not queryable. + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) variables. + type: object + type: object + from: + description: |- + from specifies the origin of the variable definition. + This will be `inline` for variables defined in the ClusterClass or the name of a patch defined in the ClusterClass + for variables discovered from a DiscoverVariables runtime extensions. + maxLength: 256 + minLength: 1 + type: string + required: + description: |- + required specifies if the variable is required. + Note: this applies to the variable as a whole and thus the + top-level object defined in the schema. If nested fields are + required, this will be specified inside the schema. + type: boolean + schema: + description: schema defines the schema of the variable. + properties: + openAPIV3Schema: + description: |- + openAPIV3Schema defines the schema of a variable via OpenAPI v3 + schema. The schema is a subset of the schema used in + Kubernetes CRDs. + minProperties: 1 + properties: + additionalProperties: + description: |- + additionalProperties specifies the schema of values in a map (keys are always strings). + NOTE: Can only be set if type is object. + NOTE: AdditionalProperties is mutually exclusive with Properties. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + allOf: + description: |- + allOf specifies that the variable must validate against all of the subschemas in the array. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + anyOf: + description: |- + anyOf specifies that the variable must validate against one or more of the subschemas in the array. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + default: + description: |- + default is the default value of the variable. + NOTE: Can be set for all types. + x-kubernetes-preserve-unknown-fields: true + description: + description: description is a human-readable description + of this variable. + maxLength: 4096 + minLength: 1 + type: string + enum: + description: |- + enum is the list of valid values of the variable. + NOTE: Can be set for all types. + items: + x-kubernetes-preserve-unknown-fields: true + maxItems: 100 + type: array + x-kubernetes-list-type: atomic + example: + description: example is an example for this variable. + x-kubernetes-preserve-unknown-fields: true + exclusiveMaximum: + description: |- + exclusiveMaximum specifies if the Maximum is exclusive. + NOTE: Can only be set if type is integer or number. + type: boolean + exclusiveMinimum: + description: |- + exclusiveMinimum specifies if the Minimum is exclusive. + NOTE: Can only be set if type is integer or number. + type: boolean + format: + description: |- + format is an OpenAPI v3 format string. Unknown formats are ignored. + For a list of supported formats please see: (of the k8s.io/apiextensions-apiserver version we're currently using) + https://github.com/kubernetes/apiextensions-apiserver/blob/master/pkg/apiserver/validation/formats.go + NOTE: Can only be set if type is string. + maxLength: 32 + minLength: 1 + type: string + items: + description: |- + items specifies fields of an array. + NOTE: Can only be set if type is array. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + maxItems: + description: |- + maxItems is the max length of an array variable. + NOTE: Can only be set if type is array. + format: int64 + type: integer + maxLength: + description: |- + maxLength is the max length of a string variable. + NOTE: Can only be set if type is string. + format: int64 + type: integer + maxProperties: + description: |- + maxProperties is the maximum amount of entries in a map or properties in an object. + NOTE: Can only be set if type is object. + format: int64 + type: integer + maximum: + description: |- + maximum is the maximum of an integer or number variable. + If ExclusiveMaximum is false, the variable is valid if it is lower than, or equal to, the value of Maximum. + If ExclusiveMaximum is true, the variable is valid if it is strictly lower than the value of Maximum. + NOTE: Can only be set if type is integer or number. + format: int64 + type: integer + minItems: + description: |- + minItems is the min length of an array variable. + NOTE: Can only be set if type is array. + format: int64 + type: integer + minLength: + description: |- + minLength is the min length of a string variable. + NOTE: Can only be set if type is string. + format: int64 + type: integer + minProperties: + description: |- + minProperties is the minimum amount of entries in a map or properties in an object. + NOTE: Can only be set if type is object. + format: int64 + type: integer + minimum: + description: |- + minimum is the minimum of an integer or number variable. + If ExclusiveMinimum is false, the variable is valid if it is greater than, or equal to, the value of Minimum. + If ExclusiveMinimum is true, the variable is valid if it is strictly greater than the value of Minimum. + NOTE: Can only be set if type is integer or number. + format: int64 + type: integer + not: + description: |- + not specifies that the variable must not validate against the subschema. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + oneOf: + description: |- + oneOf specifies that the variable must validate against exactly one of the subschemas in the array. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + pattern: + description: |- + pattern is the regex which a string variable must match. + NOTE: Can only be set if type is string. + maxLength: 512 + minLength: 1 + type: string + properties: + description: |- + properties specifies fields of an object. + NOTE: Can only be set if type is object. + NOTE: Properties is mutually exclusive with AdditionalProperties. + NOTE: This field uses PreserveUnknownFields and Schemaless, + because recursive validation is not possible. + x-kubernetes-preserve-unknown-fields: true + required: + description: |- + required specifies which fields of an object are required. + NOTE: Can only be set if type is object. + items: + maxLength: 256 + minLength: 1 + type: string + maxItems: 1000 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + type: + description: |- + type is the type of the variable. + Valid values are: object, array, string, integer, number or boolean. + enum: + - object + - array + - string + - integer + - number + - boolean + type: string + uniqueItems: + description: |- + uniqueItems specifies if items in an array must be unique. + NOTE: Can only be set if type is array. + type: boolean + x-kubernetes-int-or-string: + description: |- + x-kubernetes-int-or-string specifies that this value is + either an integer or a string. If this is true, an empty + type is allowed and type as child of anyOf is permitted + if following one of the following patterns: + + 1) anyOf: + - type: integer + - type: string + 2) allOf: + - anyOf: + - type: integer + - type: string + - ... zero or more + type: boolean + x-kubernetes-preserve-unknown-fields: + description: |- + x-kubernetes-preserve-unknown-fields allows setting fields in a variable object + which are not defined in the variable schema. This affects fields recursively, + except if nested properties or additionalProperties are specified in the schema. + type: boolean + x-kubernetes-validations: + description: x-kubernetes-validations describes + a list of validation rules written in the CEL + expression language. + items: + description: ValidationRule describes a validation + rule written in the CEL expression language. + properties: + fieldPath: + description: |- + fieldPath represents the field path returned when the validation fails. + It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. + e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo` + If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList` + It does not support list numeric index. + It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info. + Numeric index of array is not supported. + For field name which contains special characters, use `['specialName']` to refer the field name. + e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']` + maxLength: 512 + minLength: 1 + type: string + message: + description: |- + message represents the message displayed when validation fails. The message is required if the Rule contains + line breaks. The message must not contain line breaks. + If unset, the message is "failed rule: {Rule}". + e.g. "must be a URL with the host matching spec.host" + maxLength: 512 + minLength: 1 + type: string + messageExpression: + description: |- + messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. + Since messageExpression is used as a failure message, it must evaluate to a string. + If both message and messageExpression are present on a rule, then messageExpression will be used if validation + fails. If messageExpression results in a runtime error, the validation failure message is produced + as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string + that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset. + messageExpression has access to all the same variables as the rule; the only difference is the return type. + Example: + "x must be less than max ("+string(self.max)+")" + maxLength: 1024 + minLength: 1 + type: string + reason: + default: FieldValueInvalid + description: |- + reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule. + The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate". + If not set, default to use "FieldValueInvalid". + All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid. + enum: + - FieldValueInvalid + - FieldValueForbidden + - FieldValueRequired + - FieldValueDuplicate + type: string + rule: + description: "rule represents the expression + which will be evaluated by CEL.\nref: + https://github.com/google/cel-spec\nThe + Rule is scoped to the location of the + x-kubernetes-validations extension in + the schema.\nThe `self` variable in the + CEL expression is bound to the scoped + value.\nIf the Rule is scoped to an object + with properties, the accessible properties + of the object are field selectable\nvia + `self.field` and field presence can be + checked via `has(self.field)`.\nIf the + Rule is scoped to an object with additionalProperties + (i.e. a map) the value of the map\nare + accessible via `self[mapKey]`, map containment + can be checked via `mapKey in self` and + all entries of the map\nare accessible + via CEL macros and functions such as `self.all(...)`.\nIf + the Rule is scoped to an array, the elements + of the array are accessible via `self[i]` + and also by macros and\nfunctions.\nIf + the Rule is scoped to a scalar, `self` + is bound to the scalar value.\nExamples:\n- + Rule scoped to a map of objects: {\"rule\": + \"self.components['Widget'].priority < + 10\"}\n- Rule scoped to a list of integers: + {\"rule\": \"self.values.all(value, value + >= 0 && value < 100)\"}\n- Rule scoped + to a string value: {\"rule\": \"self.startsWith('kube')\"}\n\nUnknown + data preserved in custom resources via + x-kubernetes-preserve-unknown-fields is + not accessible in CEL\nexpressions. This + includes:\n- Unknown field values that + are preserved by object schemas with x-kubernetes-preserve-unknown-fields.\n- + Object properties where the property schema + is of an \"unknown type\". An \"unknown + type\" is recursively defined as:\n - + A schema with no type and x-kubernetes-preserve-unknown-fields + set to true\n - An array where the items + schema is of an \"unknown type\"\n - + An object where the additionalProperties + schema is of an \"unknown type\"\n\nOnly + property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` + are accessible.\nAccessible property names + are escaped according to the following + rules when accessed in the expression:\n- + '__' escapes to '__underscores__'\n- '.' + escapes to '__dot__'\n- '-' escapes to + '__dash__'\n- '/' escapes to '__slash__'\n- + Property names that exactly match a CEL + RESERVED keyword escape to '__{keyword}__'. + The keywords are:\n\t \"true\", \"false\", + \"null\", \"in\", \"as\", \"break\", \"const\", + \"continue\", \"else\", \"for\", \"function\", + \"if\",\n\t \"import\", \"let\", \"loop\", + \"package\", \"namespace\", \"return\".\nExamples:\n + \ - Rule accessing a property named \"namespace\": + {\"rule\": \"self.__namespace__ > 0\"}\n + \ - Rule accessing a property named \"x-prop\": + {\"rule\": \"self.x__dash__prop > 0\"}\n + \ - Rule accessing a property named \"redact__d\": + {\"rule\": \"self.redact__underscores__d + > 0\"}\n\nIf `rule` makes use of the `oldSelf` + variable it is implicitly a\n`transition + rule`.\n\nBy default, the `oldSelf` variable + is the same type as `self`.\n\nTransition + rules by default are applied only on UPDATE + requests and are\nskipped if an old value + could not be found." + maxLength: 4096 + minLength: 1 + type: string + required: + - rule + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - rule + x-kubernetes-list-type: map + x-metadata: + description: |- + x-metadata is the metadata of a variable or a nested field within a variable. + It can be used to add additional data for higher level tools. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map that can be used to store and + retrieve arbitrary metadata. + They are not queryable. + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) variables. + type: object + type: object + type: object + required: + - openAPIV3Schema + type: object + required: + - from + - required + - schema + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + definitionsConflict: + description: definitionsConflict specifies whether or not there + are conflicting definitions for a single variable name. + type: boolean + name: + description: name is the name of the variable. + maxLength: 256 + minLength: 1 + type: string + required: + - definitions + - name + type: object + maxItems: 1000 + type: array + x-kubernetes-list-type: atomic + type: object + required: + - spec + type: object + served: true storage: true subresources: status: {} diff --git a/cmd/install/assets/cluster-api/cluster.x-k8s.io_clusters.yaml b/cmd/install/assets/cluster-api/cluster.x-k8s.io_clusters.yaml index aa16351b2790..f66415318475 100644 --- a/cmd/install/assets/cluster-api/cluster.x-k8s.io_clusters.yaml +++ b/cmd/install/assets/cluster-api/cluster.x-k8s.io_clusters.yaml @@ -36,6 +36,7 @@ spec: jsonPath: .spec.topology.version name: Version type: string + deprecated: true name: v1beta1 schema: openAPIV3Schema: @@ -1273,7 +1274,7 @@ spec: failureMessage indicates that there is a fatal problem reconciling the state, and will be set to a descriptive error message. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. maxLength: 10240 minLength: 1 type: string @@ -1283,7 +1284,7 @@ spec: state, and will be set to a token value suitable for programmatic interpretation. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. type: string infrastructureReady: description: infrastructureReady is the state of the infrastructure @@ -1446,6 +1447,1623 @@ spec: type: object type: object served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - description: ClusterClass of this Cluster, empty if the Cluster is not using + a ClusterClass + jsonPath: .spec.topology.classRef.name + name: ClusterClass + type: string + - description: Cluster pass all availability checks + jsonPath: .status.conditions[?(@.type=="Available")].status + name: Available + type: string + - description: The desired number of control plane machines + jsonPath: .status.controlPlane.desiredReplicas + name: CP Desired + type: integer + - description: The number of control plane machines + jsonPath: .status.controlPlane.replicas + name: CP Current + priority: 10 + type: integer + - description: The number of control plane machines with Ready condition true + jsonPath: .status.controlPlane.readyReplicas + name: CP Ready + priority: 10 + type: integer + - description: The number of control plane machines with Available condition true + jsonPath: .status.controlPlane.availableReplicas + name: CP Available + type: integer + - description: The number of control plane machines with UpToDate condition true + jsonPath: .status.controlPlane.upToDateReplicas + name: CP Up-to-date + type: integer + - description: The desired number of worker machines + jsonPath: .status.workers.desiredReplicas + name: W Desired + type: integer + - description: The number of worker machines + jsonPath: .status.workers.replicas + name: W Current + priority: 10 + type: integer + - description: The number of worker machines with Ready condition true + jsonPath: .status.workers.readyReplicas + name: W Ready + priority: 10 + type: integer + - description: The number of worker machines with Available condition true + jsonPath: .status.workers.availableReplicas + name: W Available + type: integer + - description: The number of worker machines with UpToDate condition true + jsonPath: .status.workers.upToDateReplicas + name: W Up-to-date + type: integer + - description: Reconciliation paused + jsonPath: .status.conditions[?(@.type=="Paused")].status + name: Paused + priority: 10 + type: string + - description: Cluster status such as Pending/Provisioning/Provisioned/Deleting/Failed + jsonPath: .status.phase + name: Phase + type: string + - description: Time duration since creation of Cluster + jsonPath: .metadata.creationTimestamp + name: Age + type: date + - description: Kubernetes version associated with this Cluster + jsonPath: .spec.topology.version + name: Version + type: string + name: v1beta2 + schema: + openAPIV3Schema: + description: Cluster is the Schema for the clusters API. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec is the desired state of Cluster. + minProperties: 1 + properties: + availabilityGates: + description: |- + availabilityGates specifies additional conditions to include when evaluating Cluster Available condition. + + If this field is not defined and the Cluster implements a managed topology, availabilityGates + from the corresponding ClusterClass will be used, if any. + items: + description: ClusterAvailabilityGate contains the type of a Cluster + condition to be used as availability gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Cluster's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as availability gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this availabilityGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + clusterNetwork: + description: clusterNetwork represents the cluster network configuration. + minProperties: 1 + properties: + apiServerPort: + description: |- + apiServerPort specifies the port the API Server should bind to. + Defaults to 6443. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + pods: + description: pods is the network ranges from which Pod networks + are allocated. + properties: + cidrBlocks: + description: cidrBlocks is a list of CIDR blocks. + items: + maxLength: 43 + minLength: 1 + type: string + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + required: + - cidrBlocks + type: object + serviceDomain: + description: serviceDomain is the domain name for services. + maxLength: 253 + minLength: 1 + type: string + services: + description: services is the network ranges from which service + VIPs are allocated. + properties: + cidrBlocks: + description: cidrBlocks is a list of CIDR blocks. + items: + maxLength: 43 + minLength: 1 + type: string + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + required: + - cidrBlocks + type: object + type: object + controlPlaneEndpoint: + description: controlPlaneEndpoint represents the endpoint used to + communicate with the control plane. + minProperties: 1 + properties: + host: + description: host is the hostname on which the API server is serving. + maxLength: 512 + minLength: 1 + type: string + port: + description: port is the port on which the API server is serving. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + type: object + controlPlaneRef: + description: |- + controlPlaneRef is an optional reference to a provider-specific resource that holds + the details for provisioning the Control Plane for a Cluster. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + infrastructureRef: + description: |- + infrastructureRef is a reference to a provider-specific resource that holds the details + for provisioning infrastructure for a cluster in said provider. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + paused: + description: paused can be used to prevent controllers from processing + the Cluster and all its associated objects. + type: boolean + topology: + description: |- + topology encapsulates the topology for the cluster. + NOTE: It is required to enable the ClusterTopology + feature gate flag to activate managed topologies support; + this feature is highly experimental, and parts of it might still be not implemented. + properties: + classRef: + description: classRef is the ref to the ClusterClass that should + be used for the topology. + properties: + name: + description: |- + name is the name of the ClusterClass that should be used for the topology. + name must be a valid ClusterClass name and because of that be at most 253 characters in length + and it must consist only of lower case alphanumeric characters, hyphens (-) and periods (.), and must start + and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + namespace: + description: |- + namespace is the namespace of the ClusterClass that should be used for the topology. + If namespace is empty or not set, it is defaulted to the namespace of the Cluster object. + namespace must be a valid namespace name and because of that be at most 63 characters in length + and it must consist only of lower case alphanumeric characters or hyphens (-), and must start + and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ + type: string + required: + - name + type: object + controlPlane: + description: controlPlane describes the cluster control plane. + minProperties: 1 + properties: + deletion: + description: deletion contains configuration options for Machine + deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + format: int32 + minimum: 0 + type: integer + type: object + healthCheck: + description: |- + healthCheck allows to enable, disable and override control plane health check + configuration from the ClusterClass for this control plane. + minProperties: 1 + properties: + checks: + description: |- + checks are the checks that are used to evaluate if a Machine is healthy. + + If one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, + and as a consequence the checks and remediation fields from Cluster will be used instead of the + corresponding fields in ClusterClass. + + Independent of this configuration the MachineHealthCheck controller will always + flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + Machines with deleted Nodes as unhealthy. + + Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + is defaulted to 10 minutes and evaluated accordingly. + minProperties: 1 + properties: + nodeStartupTimeoutSeconds: + description: |- + nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + to consider a Machine unhealthy if a corresponding Node isn't associated + through a `Spec.ProviderID` field. + + The duration set in this field is compared to the greatest of: + - Cluster's infrastructure ready condition timestamp (if and when available) + - Control Plane's initialized condition timestamp (if and when available) + - Machine's infrastructure ready condition timestamp (if and when available) + - Machine's metadata creation timestamp + + Defaults to 10 minutes. + If you wish to disable this feature, set the value explicitly to 0. + format: int32 + minimum: 0 + type: integer + unhealthyNodeConditions: + description: |- + unhealthyNodeConditions contains a list of conditions that determine + whether a node is considered unhealthy. The conditions are combined in a + logical OR, i.e. if any of the conditions is met, the node is unhealthy. + items: + description: |- + UnhealthyNodeCondition represents a Node condition type and value with a timeout + specified as a duration. When the named condition has been in the given + status for at least the timeout value, a node is considered unhealthy. + properties: + status: + description: status of the condition, one of + True, False, Unknown. + minLength: 1 + type: string + timeoutSeconds: + description: |- + timeoutSeconds is the duration that a node must be in a given status for, + after which the node is considered unhealthy. + For example, with a value of "1h", the node must match the status + for at least 1 hour before being considered unhealthy. + format: int32 + minimum: 0 + type: integer + type: + description: type of Node condition + minLength: 1 + type: string + required: + - status + - timeoutSeconds + - type + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + type: object + enabled: + description: |- + enabled controls if a MachineHealthCheck should be created for the target machines. + + If false: No MachineHealthCheck will be created. + + If not set(default): A MachineHealthCheck will be created if it is defined here or + in the associated ClusterClass. If no MachineHealthCheck is defined then none will be created. + + If true: A MachineHealthCheck is guaranteed to be created. Cluster validation will + block if `enable` is true and no MachineHealthCheck definition is available. + type: boolean + remediation: + description: |- + remediation configures if and how remediations are triggered if a Machine is unhealthy. + + If one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, + and as a consequence the checks and remediation fields from cluster will be used instead of the + corresponding fields in ClusterClass. + + If an health check override is defined and remediation or remediation.triggerIf is not set, + remediation will always be triggered for unhealthy Machines. + + If an health check override is defined and remediation or remediation.templateRef is not set, + the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + minProperties: 1 + properties: + templateRef: + description: |- + templateRef is a reference to a remediation template + provided by an infrastructure provider. + + This field is completely optional, when filled, the MachineHealthCheck controller + creates a new object from the template referenced and hands off remediation of the machine to + a controller that lives outside of Cluster API. + properties: + apiVersion: + description: |- + apiVersion of the remediation template. + apiVersion must be fully qualified domain name followed by / and a version. + NOTE: This field must be kept in sync with the APIVersion of the remediation template. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the remediation template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the remediation template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + triggerIf: + description: |- + triggerIf configures if remediations are triggered. + If this field is not set, remediations are always triggered. + minProperties: 1 + properties: + unhealthyInRange: + description: |- + unhealthyInRange specifies that remediations are only triggered if the number of + unhealthy Machines is in the configured range. + Takes precedence over unhealthyLessThanOrEqualTo. + Eg. "[3-5]" - This means that remediation will be allowed only when: + (a) there are at least 3 unhealthy Machines (and) + (b) there are at most 5 unhealthy Machines + maxLength: 32 + minLength: 1 + pattern: ^\[[0-9]+-[0-9]+\]$ + type: string + unhealthyLessThanOrEqualTo: + anyOf: + - type: integer + - type: string + description: |- + unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + unhealthy Machines is less than or equal to the configured value. + unhealthyInRange takes precedence if set. + x-kubernetes-int-or-string: true + type: object + type: object + type: object + metadata: + description: |- + metadata is the metadata applied to the ControlPlane and the Machines of the ControlPlane + if the ControlPlaneTemplate referenced by the ClusterClass is machine based. If not, it + is applied only to the ControlPlane. + At runtime this metadata is merged with the corresponding metadata from the ClusterClass. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + readinessGates: + description: |- + readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + + This field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready + computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine. + + If this field is not defined, readinessGates from the corresponding ControlPlaneClass will be used, if any. + + NOTE: Specific control plane provider implementations might automatically extend the list of readinessGates; + e.g. the kubeadm control provider adds ReadinessGates for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + items: + description: MachineReadinessGate contains the type of a + Machine condition to be used as a readiness gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Machine's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this readinessGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + replicas: + description: |- + replicas is the number of control plane nodes. + If the value is not set, the ControlPlane object is created without the number of Replicas + and it's assumed that the control plane controller does not implement support for this field. + When specified against a control plane provider that lacks support for this field, this value will be ignored. + format: int32 + type: integer + variables: + description: variables can be used to customize the ControlPlane + through patches. + minProperties: 1 + properties: + overrides: + description: overrides can be used to override Cluster + level variables. + items: + description: |- + ClusterVariable can be used to customize the Cluster through patches. Each ClusterVariable is associated with a + Variable definition in the ClusterClass `status` variables. + properties: + name: + description: name of the variable. + maxLength: 256 + minLength: 1 + type: string + value: + description: |- + value of the variable. + Note: the value will be validated against the schema of the corresponding ClusterClassVariable + from the ClusterClass. + Note: We have to use apiextensionsv1.JSON instead of a custom JSON type, because controller-tools has a + hard-coded schema for apiextensionsv1.JSON which cannot be produced by another type via controller-tools, + i.e. it is not possible to have no type field. + Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111 + x-kubernetes-preserve-unknown-fields: true + required: + - name + - value + type: object + maxItems: 1000 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + type: object + variables: + description: |- + variables can be used to customize the Cluster through + patches. They must comply to the corresponding + VariableClasses defined in the ClusterClass. + items: + description: |- + ClusterVariable can be used to customize the Cluster through patches. Each ClusterVariable is associated with a + Variable definition in the ClusterClass `status` variables. + properties: + name: + description: name of the variable. + maxLength: 256 + minLength: 1 + type: string + value: + description: |- + value of the variable. + Note: the value will be validated against the schema of the corresponding ClusterClassVariable + from the ClusterClass. + Note: We have to use apiextensionsv1.JSON instead of a custom JSON type, because controller-tools has a + hard-coded schema for apiextensionsv1.JSON which cannot be produced by another type via controller-tools, + i.e. it is not possible to have no type field. + Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111 + x-kubernetes-preserve-unknown-fields: true + required: + - name + - value + type: object + maxItems: 1000 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + version: + description: version is the Kubernetes version of the cluster. + maxLength: 256 + minLength: 1 + type: string + workers: + description: |- + workers encapsulates the different constructs that form the worker nodes + for the cluster. + minProperties: 1 + properties: + machineDeployments: + description: machineDeployments is a list of machine deployments + in the cluster. + items: + description: |- + MachineDeploymentTopology specifies the different parameters for a set of worker nodes in the topology. + This set of nodes is managed by a MachineDeployment object whose lifecycle is managed by the Cluster controller. + properties: + class: + description: |- + class is the name of the MachineDeploymentClass used to create the set of worker nodes. + This should match one of the deployment classes defined in the ClusterClass object + mentioned in the `Cluster.Spec.Class` field. + maxLength: 256 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options + for Machine deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + format: int32 + minimum: 0 + type: integer + order: + description: |- + order defines the order in which Machines are deleted when downscaling. + Defaults to "Random". Valid values are "Random, "Newest", "Oldest" + enum: + - Random + - Newest + - Oldest + type: string + type: object + failureDomain: + description: |- + failureDomain is the failure domain the machines will be created in. + Must match a key in the FailureDomains map stored on the cluster object. + maxLength: 256 + minLength: 1 + type: string + healthCheck: + description: |- + healthCheck allows to enable, disable and override MachineDeployment health check + configuration from the ClusterClass for this MachineDeployment. + minProperties: 1 + properties: + checks: + description: |- + checks are the checks that are used to evaluate if a Machine is healthy. + + If one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, + and as a consequence the checks and remediation fields from Cluster will be used instead of the + corresponding fields in ClusterClass. + + Independent of this configuration the MachineHealthCheck controller will always + flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + Machines with deleted Nodes as unhealthy. + + Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + is defaulted to 10 minutes and evaluated accordingly. + minProperties: 1 + properties: + nodeStartupTimeoutSeconds: + description: |- + nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + to consider a Machine unhealthy if a corresponding Node isn't associated + through a `Spec.ProviderID` field. + + The duration set in this field is compared to the greatest of: + - Cluster's infrastructure ready condition timestamp (if and when available) + - Control Plane's initialized condition timestamp (if and when available) + - Machine's infrastructure ready condition timestamp (if and when available) + - Machine's metadata creation timestamp + + Defaults to 10 minutes. + If you wish to disable this feature, set the value explicitly to 0. + format: int32 + minimum: 0 + type: integer + unhealthyNodeConditions: + description: |- + unhealthyNodeConditions contains a list of conditions that determine + whether a node is considered unhealthy. The conditions are combined in a + logical OR, i.e. if any of the conditions is met, the node is unhealthy. + items: + description: |- + UnhealthyNodeCondition represents a Node condition type and value with a timeout + specified as a duration. When the named condition has been in the given + status for at least the timeout value, a node is considered unhealthy. + properties: + status: + description: status of the condition, + one of True, False, Unknown. + minLength: 1 + type: string + timeoutSeconds: + description: |- + timeoutSeconds is the duration that a node must be in a given status for, + after which the node is considered unhealthy. + For example, with a value of "1h", the node must match the status + for at least 1 hour before being considered unhealthy. + format: int32 + minimum: 0 + type: integer + type: + description: type of Node condition + minLength: 1 + type: string + required: + - status + - timeoutSeconds + - type + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + type: object + enabled: + description: |- + enabled controls if a MachineHealthCheck should be created for the target machines. + + If false: No MachineHealthCheck will be created. + + If not set(default): A MachineHealthCheck will be created if it is defined here or + in the associated ClusterClass. If no MachineHealthCheck is defined then none will be created. + + If true: A MachineHealthCheck is guaranteed to be created. Cluster validation will + block if `enable` is true and no MachineHealthCheck definition is available. + type: boolean + remediation: + description: |- + remediation configures if and how remediations are triggered if a Machine is unhealthy. + + If one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, + and as a consequence the checks and remediation fields from cluster will be used instead of the + corresponding fields in ClusterClass. + + If an health check override is defined and remediation or remediation.triggerIf is not set, + remediation will always be triggered for unhealthy Machines. + + If an health check override is defined and remediation or remediation.templateRef is not set, + the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + minProperties: 1 + properties: + maxInFlight: + anyOf: + - type: integer + - type: string + description: |- + maxInFlight determines how many in flight remediations should happen at the same time. + + Remediation only happens on the MachineSet with the most current revision, while + older MachineSets (usually present during rollout operations) aren't allowed to remediate. + + Note: In general (independent of remediations), unhealthy machines are always + prioritized during scale down operations over healthy ones. + + MaxInFlight can be set to a fixed number or a percentage. + Example: when this is set to 20%, the MachineSet controller deletes at most 20% of + the desired replicas. + + If not set, remediation is limited to all machines (bounded by replicas) + under the active MachineSet's management. + x-kubernetes-int-or-string: true + templateRef: + description: |- + templateRef is a reference to a remediation template + provided by an infrastructure provider. + + This field is completely optional, when filled, the MachineHealthCheck controller + creates a new object from the template referenced and hands off remediation of the machine to + a controller that lives outside of Cluster API. + properties: + apiVersion: + description: |- + apiVersion of the remediation template. + apiVersion must be fully qualified domain name followed by / and a version. + NOTE: This field must be kept in sync with the APIVersion of the remediation template. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the remediation template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the remediation template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + triggerIf: + description: |- + triggerIf configures if remediations are triggered. + If this field is not set, remediations are always triggered. + minProperties: 1 + properties: + unhealthyInRange: + description: |- + unhealthyInRange specifies that remediations are only triggered if the number of + unhealthy Machines is in the configured range. + Takes precedence over unhealthyLessThanOrEqualTo. + Eg. "[3-5]" - This means that remediation will be allowed only when: + (a) there are at least 3 unhealthy Machines (and) + (b) there are at most 5 unhealthy Machines + maxLength: 32 + minLength: 1 + pattern: ^\[[0-9]+-[0-9]+\]$ + type: string + unhealthyLessThanOrEqualTo: + anyOf: + - type: integer + - type: string + description: |- + unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + unhealthy Machines is less than or equal to the configured value. + unhealthyInRange takes precedence if set. + x-kubernetes-int-or-string: true + type: object + type: object + type: object + metadata: + description: |- + metadata is the metadata applied to the MachineDeployment and the machines of the MachineDeployment. + At runtime this metadata is merged with the corresponding metadata from the ClusterClass. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + minReadySeconds: + description: |- + minReadySeconds is the minimum number of seconds for which a newly created machine should + be ready. + Defaults to 0 (machine will be considered available as soon as it + is ready) + format: int32 + minimum: 0 + type: integer + name: + description: |- + name is the unique identifier for this MachineDeploymentTopology. + The value is used with other unique identifiers to create a MachineDeployment's Name + (e.g. cluster's name, etc). In case the name is greater than the allowed maximum length, + the values are hashed together. + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + readinessGates: + description: |- + readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + + This field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready + computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine. + + If this field is not defined, readinessGates from the corresponding MachineDeploymentClass will be used, if any. + items: + description: MachineReadinessGate contains the type + of a Machine condition to be used as a readiness + gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Machine's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this readinessGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + replicas: + description: |- + replicas is the number of worker nodes belonging to this set. + If the value is nil, the MachineDeployment is created without the number of Replicas (defaulting to 1) + and it's assumed that an external entity (like cluster autoscaler) is responsible for the management + of this value. + format: int32 + type: integer + rollout: + description: |- + rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. + It allows you to define the strategy used during rolling replacements. + minProperties: 1 + properties: + strategy: + description: strategy specifies how to roll out + control plane Machines. + minProperties: 1 + properties: + rollingUpdate: + description: |- + rollingUpdate is the rolling update config params. Present only if + type = RollingUpdate. + minProperties: 1 + properties: + maxSurge: + anyOf: + - type: integer + - type: string + description: |- + maxSurge is the maximum number of machines that can be scheduled above the + desired number of machines. + Value can be an absolute number (ex: 5) or a percentage of + desired machines (ex: 10%). + This can not be 0 if MaxUnavailable is 0. + Absolute number is calculated from percentage by rounding up. + Defaults to 1. + Example: when this is set to 30%, the new MachineSet can be scaled + up immediately when the rolling update starts, such that the total + number of old and new machines do not exceed 130% of desired + machines. Once old machines have been killed, new MachineSet can + be scaled up further, ensuring that total number of machines running + at any time during the update is at most 130% of desired machines. + x-kubernetes-int-or-string: true + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of machines that can be unavailable during the update. + Value can be an absolute number (ex: 5) or a percentage of desired + machines (ex: 10%). + Absolute number is calculated from percentage by rounding down. + This can not be 0 if MaxSurge is 0. + Defaults to 0. + Example: when this is set to 30%, the old MachineSet can be scaled + down to 70% of desired machines immediately when the rolling update + starts. Once new machines are ready, old MachineSet can be scaled + down further, followed by scaling up the new MachineSet, ensuring + that the total number of machines available at all times + during the update is at least 70% of desired machines. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type of rollout. Allowed values are RollingUpdate and OnDelete. + Default is RollingUpdate. + enum: + - RollingUpdate + - OnDelete + type: string + required: + - type + type: object + type: object + variables: + description: variables can be used to customize the + MachineDeployment through patches. + minProperties: 1 + properties: + overrides: + description: overrides can be used to override Cluster + level variables. + items: + description: |- + ClusterVariable can be used to customize the Cluster through patches. Each ClusterVariable is associated with a + Variable definition in the ClusterClass `status` variables. + properties: + name: + description: name of the variable. + maxLength: 256 + minLength: 1 + type: string + value: + description: |- + value of the variable. + Note: the value will be validated against the schema of the corresponding ClusterClassVariable + from the ClusterClass. + Note: We have to use apiextensionsv1.JSON instead of a custom JSON type, because controller-tools has a + hard-coded schema for apiextensionsv1.JSON which cannot be produced by another type via controller-tools, + i.e. it is not possible to have no type field. + Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111 + x-kubernetes-preserve-unknown-fields: true + required: + - name + - value + type: object + maxItems: 1000 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + required: + - class + - name + type: object + maxItems: 2000 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + machinePools: + description: machinePools is a list of machine pools in the + cluster. + items: + description: |- + MachinePoolTopology specifies the different parameters for a pool of worker nodes in the topology. + This pool of nodes is managed by a MachinePool object whose lifecycle is managed by the Cluster controller. + properties: + class: + description: |- + class is the name of the MachinePoolClass used to create the pool of worker nodes. + This should match one of the deployment classes defined in the ClusterClass object + mentioned in the `Cluster.Spec.Class` field. + maxLength: 256 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options + for Machine deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the MachinePool + hosts after the MachinePool is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + format: int32 + minimum: 0 + type: integer + type: object + failureDomains: + description: |- + failureDomains is the list of failure domains the machine pool will be created in. + Must match a key in the FailureDomains map stored on the cluster object. + items: + maxLength: 256 + minLength: 1 + type: string + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + metadata: + description: |- + metadata is the metadata applied to the MachinePool. + At runtime this metadata is merged with the corresponding metadata from the ClusterClass. + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + minReadySeconds: + description: |- + minReadySeconds is the minimum number of seconds for which a newly created machine pool should + be ready. + Defaults to 0 (machine will be considered available as soon as it + is ready) + format: int32 + minimum: 0 + type: integer + name: + description: |- + name is the unique identifier for this MachinePoolTopology. + The value is used with other unique identifiers to create a MachinePool's Name + (e.g. cluster's name, etc). In case the name is greater than the allowed maximum length, + the values are hashed together. + maxLength: 63 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + replicas: + description: |- + replicas is the number of nodes belonging to this pool. + If the value is nil, the MachinePool is created without the number of Replicas (defaulting to 1) + and it's assumed that an external entity (like cluster autoscaler) is responsible for the management + of this value. + format: int32 + type: integer + variables: + description: variables can be used to customize the + MachinePool through patches. + minProperties: 1 + properties: + overrides: + description: overrides can be used to override Cluster + level variables. + items: + description: |- + ClusterVariable can be used to customize the Cluster through patches. Each ClusterVariable is associated with a + Variable definition in the ClusterClass `status` variables. + properties: + name: + description: name of the variable. + maxLength: 256 + minLength: 1 + type: string + value: + description: |- + value of the variable. + Note: the value will be validated against the schema of the corresponding ClusterClassVariable + from the ClusterClass. + Note: We have to use apiextensionsv1.JSON instead of a custom JSON type, because controller-tools has a + hard-coded schema for apiextensionsv1.JSON which cannot be produced by another type via controller-tools, + i.e. it is not possible to have no type field. + Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111 + x-kubernetes-preserve-unknown-fields: true + required: + - name + - value + type: object + maxItems: 1000 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + required: + - class + - name + type: object + maxItems: 2000 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + type: object + required: + - classRef + - version + type: object + type: object + status: + description: status is the observed state of Cluster. + minProperties: 1 + properties: + conditions: + description: |- + conditions represents the observations of a Cluster's current state. + Known condition types are Available, InfrastructureReady, ControlPlaneInitialized, ControlPlaneAvailable, WorkersAvailable, MachinesReady + MachinesUpToDate, RemoteConnectionProbe, ScalingUp, ScalingDown, Remediating, Deleting, Paused. + Additionally, a TopologyReconciled condition will be added in case the Cluster is referencing a ClusterClass / defining a managed Topology. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + controlPlane: + description: controlPlane groups all the observations about Cluster's + ControlPlane current state. + properties: + availableReplicas: + description: availableReplicas is the total number of available + control plane machines in this cluster. A machine is considered + available when Machine's Available condition is true. + format: int32 + type: integer + desiredReplicas: + description: desiredReplicas is the total number of desired control + plane machines in this cluster. + format: int32 + type: integer + readyReplicas: + description: readyReplicas is the total number of ready control + plane machines in this cluster. A machine is considered ready + when Machine's Ready condition is true. + format: int32 + type: integer + replicas: + description: |- + replicas is the total number of control plane machines in this cluster. + NOTE: replicas also includes machines still being provisioned or being deleted. + format: int32 + type: integer + upToDateReplicas: + description: upToDateReplicas is the number of up-to-date control + plane machines in this cluster. A machine is considered up-to-date + when Machine's UpToDate condition is true. + format: int32 + type: integer + type: object + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. + properties: + v1beta1: + description: v1beta1 groups all the status fields that are deprecated + and will be removed when support for v1beta1 will be dropped. + properties: + conditions: + description: |- + conditions defines current service state of the cluster. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + failureMessage: + description: |- + failureMessage indicates that there is a fatal problem reconciling the + state, and will be set to a descriptive error message. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + maxLength: 10240 + minLength: 1 + type: string + failureReason: + description: |- + failureReason indicates that there is a fatal problem reconciling the + state, and will be set to a token value suitable for + programmatic interpretation. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + type: string + type: object + type: object + failureDomains: + description: failureDomains is a slice of failure domain objects synced + from the infrastructure provider. + items: + description: |- + FailureDomain is the Schema for Cluster API failure domains. + It allows controllers to understand how many failure domains a cluster can optionally span across. + properties: + attributes: + additionalProperties: + type: string + description: attributes is a free form map of attributes an + infrastructure provider might use or require. + type: object + controlPlane: + description: controlPlane determines if this failure domain + is suitable for use by control plane machines. + type: boolean + name: + description: name is the name of the failure domain. + maxLength: 256 + minLength: 1 + type: string + required: + - name + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + initialization: + description: |- + initialization provides observations of the Cluster initialization process. + NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Cluster provisioning. + minProperties: 1 + properties: + controlPlaneInitialized: + description: |- + controlPlaneInitialized denotes when the control plane is functional enough to accept requests. + This information is usually used as a signal for starting all the provisioning operations that depends on + a functional API server, but do not require a full HA control plane to exists, like e.g. join worker Machines, + install core addons like CNI, CPI, CSI etc. + NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + The value of this field is never updated after initialization is completed. + type: boolean + infrastructureProvisioned: + description: |- + infrastructureProvisioned is true when the infrastructure provider reports that Cluster's infrastructure is fully provisioned. + NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + The value of this field is never updated after provisioning is completed. + type: boolean + type: object + observedGeneration: + description: observedGeneration is the latest generation observed + by the controller. + format: int64 + minimum: 1 + type: integer + phase: + description: phase represents the current phase of cluster actuation. + enum: + - Pending + - Provisioning + - Provisioned + - Deleting + - Failed + - Unknown + type: string + workers: + description: workers groups all the observations about Cluster's Workers + current state. + properties: + availableReplicas: + description: availableReplicas is the total number of available + worker machines in this cluster. A machine is considered available + when Machine's Available condition is true. + format: int32 + type: integer + desiredReplicas: + description: desiredReplicas is the total number of desired worker + machines in this cluster. + format: int32 + type: integer + readyReplicas: + description: readyReplicas is the total number of ready worker + machines in this cluster. A machine is considered ready when + Machine's Ready condition is true. + format: int32 + type: integer + replicas: + description: |- + replicas is the total number of worker machines in this cluster. + NOTE: replicas also includes machines still being provisioned or being deleted. + format: int32 + type: integer + upToDateReplicas: + description: upToDateReplicas is the number of up-to-date worker + machines in this cluster. A machine is considered up-to-date + when Machine's UpToDate condition is true. + format: int32 + type: integer + type: object + type: object + required: + - spec + type: object + served: true storage: true subresources: status: {} diff --git a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinedeployments.yaml b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinedeployments.yaml index 1901804867a4..e6d429803b25 100644 --- a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinedeployments.yaml +++ b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinedeployments.yaml @@ -57,6 +57,7 @@ spec: jsonPath: .spec.template.spec.version name: Version type: string + deprecated: true name: v1beta1 schema: openAPIV3Schema: @@ -668,7 +669,7 @@ spec: be machines that are running but not yet available or machines that still have not been created. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. format: int32 type: integer updatedReplicas: @@ -767,6 +768,781 @@ spec: type: object type: object served: true + storage: false + subresources: + scale: + labelSelectorPath: .status.selector + specReplicasPath: .spec.replicas + statusReplicasPath: .status.replicas + status: {} + - additionalPrinterColumns: + - description: Cluster + jsonPath: .spec.clusterName + name: Cluster + type: string + - description: Cluster pass all availability checks + jsonPath: .status.conditions[?(@.type=="Available")].status + name: Available + type: string + - description: The desired number of machines + jsonPath: .spec.replicas + name: Desired + type: integer + - description: The number of machines + jsonPath: .status.replicas + name: Current + type: integer + - description: The number of machines with Ready condition true + jsonPath: .status.readyReplicas + name: Ready + type: integer + - description: The number of machines with Available condition true + jsonPath: .status.availableReplicas + name: Available + type: integer + - description: The number of machines with UpToDate condition true + jsonPath: .status.upToDateReplicas + name: Up-to-date + type: integer + - description: Reconciliation paused + jsonPath: .status.conditions[?(@.type=="Paused")].status + name: Paused + priority: 10 + type: string + - description: MachineDeployment status such as ScalingUp/ScalingDown/Running/Failed/Unknown + jsonPath: .status.phase + name: Phase + type: string + - description: Time duration since creation of MachineDeployment + jsonPath: .metadata.creationTimestamp + name: Age + type: date + - description: Kubernetes version associated with this MachineDeployment + jsonPath: .spec.template.spec.version + name: Version + type: string + name: v1beta2 + schema: + openAPIV3Schema: + description: MachineDeployment is the Schema for the machinedeployments API. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec is the desired state of MachineDeployment. + properties: + clusterName: + description: clusterName is the name of the Cluster this object belongs + to. + maxLength: 63 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options for MachineDeployment + deletion. + minProperties: 1 + properties: + order: + description: |- + order defines the order in which Machines are deleted when downscaling. + Defaults to "Random". Valid values are "Random, "Newest", "Oldest" + enum: + - Random + - Newest + - Oldest + type: string + type: object + machineNaming: + description: |- + machineNaming allows changing the naming pattern used when creating Machines. + Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines. + minProperties: 1 + properties: + template: + description: |- + template defines the template to use for generating the names of the + Machine objects. + If not defined, it will fallback to `{{ .machineSet.name }}-{{ .random }}`. + If the generated name string exceeds 63 characters, it will be trimmed to + 58 characters and will + get concatenated with a random suffix of length 5. + Length of the template string must not exceed 256 characters. + The template allows the following variables `.cluster.name`, + `.machineSet.name` and `.random`. + The variable `.cluster.name` retrieves the name of the cluster object + that owns the Machines being created. + The variable `.machineSet.name` retrieves the name of the MachineSet + object that owns the Machines being created. + The variable `.random` is substituted with random alphanumeric string, + without vowels, of length 5. This variable is required part of the + template. If not provided, validation will fail. + maxLength: 256 + minLength: 1 + type: string + type: object + paused: + description: paused indicates that the deployment is paused. + type: boolean + remediation: + description: remediation controls how unhealthy Machines are remediated. + minProperties: 1 + properties: + maxInFlight: + anyOf: + - type: integer + - type: string + description: |- + maxInFlight determines how many in flight remediations should happen at the same time. + + Remediation only happens on the MachineSet with the most current revision, while + older MachineSets (usually present during rollout operations) aren't allowed to remediate. + + Note: In general (independent of remediations), unhealthy machines are always + prioritized during scale down operations over healthy ones. + + MaxInFlight can be set to a fixed number or a percentage. + Example: when this is set to 20%, the MachineSet controller deletes at most 20% of + the desired replicas. + + If not set, remediation is limited to all machines (bounded by replicas) + under the active MachineSet's management. + x-kubernetes-int-or-string: true + type: object + replicas: + description: |- + replicas is the number of desired machines. + This is a pointer to distinguish between explicit zero and not specified. + + Defaults to: + * if the Kubernetes autoscaler min size and max size annotations are set: + - if it's a new MachineDeployment, use min size + - if the replicas field of the old MachineDeployment is < min size, use min size + - if the replicas field of the old MachineDeployment is > max size, use max size + - if the replicas field of the old MachineDeployment is in the (min size, max size) range, keep the value from the oldMD + * otherwise use 1 + Note: Defaulting will be run whenever the replicas field is not set: + * A new MachineDeployment is created with replicas not set. + * On an existing MachineDeployment the replicas field was first set and is now unset. + Those cases are especially relevant for the following Kubernetes autoscaler use cases: + * A new MachineDeployment is created and replicas should be managed by the autoscaler + * An existing MachineDeployment which initially wasn't controlled by the autoscaler + should be later controlled by the autoscaler + format: int32 + type: integer + rollout: + description: |- + rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. + It allows you to require that all Machines are replaced after a certain time, + and allows you to define the strategy used during rolling replacements. + minProperties: 1 + properties: + after: + description: |- + after is a field to indicate a rollout should be performed + after the specified time even if no changes have been made to the + MachineDeployment. + Example: In the YAML the time can be specified in the RFC3339 format. + To specify the rolloutAfter target as March 9, 2023, at 9 am UTC + use "2023-03-09T09:00:00Z". + format: date-time + type: string + strategy: + description: strategy specifies how to roll out control plane + Machines. + minProperties: 1 + properties: + rollingUpdate: + description: |- + rollingUpdate is the rolling update config params. Present only if + type = RollingUpdate. + minProperties: 1 + properties: + maxSurge: + anyOf: + - type: integer + - type: string + description: |- + maxSurge is the maximum number of machines that can be scheduled above the + desired number of machines. + Value can be an absolute number (ex: 5) or a percentage of + desired machines (ex: 10%). + This can not be 0 if MaxUnavailable is 0. + Absolute number is calculated from percentage by rounding up. + Defaults to 1. + Example: when this is set to 30%, the new MachineSet can be scaled + up immediately when the rolling update starts, such that the total + number of old and new machines do not exceed 130% of desired + machines. Once old machines have been killed, new MachineSet can + be scaled up further, ensuring that total number of machines running + at any time during the update is at most 130% of desired machines. + x-kubernetes-int-or-string: true + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of machines that can be unavailable during the update. + Value can be an absolute number (ex: 5) or a percentage of desired + machines (ex: 10%). + Absolute number is calculated from percentage by rounding down. + This can not be 0 if MaxSurge is 0. + Defaults to 0. + Example: when this is set to 30%, the old MachineSet can be scaled + down to 70% of desired machines immediately when the rolling update + starts. Once new machines are ready, old MachineSet can be scaled + down further, followed by scaling up the new MachineSet, ensuring + that the total number of machines available at all times + during the update is at least 70% of desired machines. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type of rollout. Allowed values are RollingUpdate and OnDelete. + Default is RollingUpdate. + enum: + - RollingUpdate + - OnDelete + type: string + required: + - type + type: object + type: object + selector: + description: |- + selector is the label selector for machines. Existing MachineSets whose machines are + selected by this will be the ones affected by this deployment. + It must match the machine template's labels. + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. + The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector applies + to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + template: + description: template describes the machines that will be created. + properties: + metadata: + description: |- + metadata is the standard object's metadata. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + spec: + description: |- + spec is the specification of the desired behavior of the machine. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + properties: + bootstrap: + description: |- + bootstrap is a reference to a local struct which encapsulates + fields to configure the Machine’s bootstrapping mechanism. + properties: + configRef: + description: |- + configRef is a reference to a bootstrap provider-specific resource + that holds configuration details. The reference is optional to + allow users/operators to specify Bootstrap.DataSecretName without + the need of a controller. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + dataSecretName: + description: |- + dataSecretName is the name of the secret that stores the bootstrap data script. + If nil, the Machine should remain in the Pending state. + maxLength: 253 + minLength: 0 + type: string + type: object + clusterName: + description: clusterName is the name of the Cluster this object + belongs to. + maxLength: 63 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options for Machine + deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + format: int32 + minimum: 0 + type: integer + type: object + failureDomain: + description: |- + failureDomain is the failure domain the machine will be created in. + Must match the name of a FailureDomain from the Cluster status. + maxLength: 256 + minLength: 1 + type: string + infrastructureRef: + description: |- + infrastructureRef is a required reference to a custom resource + offered by an infrastructure provider. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + minReadySeconds: + description: |- + minReadySeconds is the minimum number of seconds for which a Machine should be ready before considering it available. + Defaults to 0 (Machine will be considered available as soon as the Machine is ready) + format: int32 + minimum: 0 + type: integer + providerID: + description: |- + providerID is the identification ID of the machine provided by the provider. + This field must match the provider ID as seen on the node object corresponding to this machine. + This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler + with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out + machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a + generic out-of-tree provider for autoscaler, this field is required by autoscaler to be + able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver + and then a comparison is done to find out unregistered machines and are marked for delete. + This field will be set by the actuators and consumed by higher level entities like autoscaler that will + be interfacing with cluster-api as generic provider. + maxLength: 512 + minLength: 1 + type: string + readinessGates: + description: |- + readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + + This field can be used e.g. by Cluster API control plane providers to extend the semantic of the + Ready condition for the Machine they control, like the kubeadm control provider adding ReadinessGates + for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + + Another example are external controllers, e.g. responsible to install special software/hardware on the Machines; + they can include the status of those components with a new condition and add this condition to ReadinessGates. + + NOTE: In case readinessGates conditions start with the APIServer, ControllerManager, Scheduler prefix, and all those + readiness gates condition are reporting the same message, when computing the Machine's Ready condition those + readinessGates will be replaced by a single entry reporting "Control plane components: " + message. + This helps to improve readability of conditions bubbling up to the Machine's owner resource / to the Cluster). + items: + description: MachineReadinessGate contains the type of a + Machine condition to be used as a readiness gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Machine's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this readinessGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + version: + description: |- + version defines the desired Kubernetes version. + This field is meant to be optionally used by bootstrap providers. + maxLength: 256 + minLength: 1 + type: string + required: + - bootstrap + - clusterName + - infrastructureRef + type: object + required: + - spec + type: object + required: + - clusterName + - selector + - template + type: object + status: + description: status is the observed state of MachineDeployment. + minProperties: 1 + properties: + availableReplicas: + description: availableReplicas is the number of available replicas + for this MachineDeployment. A machine is considered available when + Machine's Available condition is true. + format: int32 + type: integer + conditions: + description: |- + conditions represents the observations of a MachineDeployment's current state. + Known condition types are Available, MachinesReady, MachinesUpToDate, ScalingUp, ScalingDown, Remediating, Deleting, Paused. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. + properties: + v1beta1: + description: v1beta1 groups all the status fields that are deprecated + and will be removed when support for v1beta1 will be dropped. + properties: + availableReplicas: + description: |- + availableReplicas is the total number of available machines (ready for at least minReadySeconds) + targeted by this deployment. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + conditions: + description: |- + conditions defines current service state of the MachineDeployment. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + readyReplicas: + description: |- + readyReplicas is the total number of ready machines targeted by this deployment. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + unavailableReplicas: + description: |- + unavailableReplicas is the total number of unavailable machines targeted by this deployment. + This is the total number of machines that are still required for + the deployment to have 100% available capacity. They may either + be machines that are running but not yet available or machines + that still have not been created. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + updatedReplicas: + description: |- + updatedReplicas is the total number of non-terminated machines targeted by this deployment + that have the desired template spec. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + type: object + type: object + observedGeneration: + description: observedGeneration is the generation observed by the + deployment controller. + format: int64 + minimum: 1 + type: integer + phase: + description: phase represents the current phase of a MachineDeployment + (ScalingUp, ScalingDown, Running, Failed, or Unknown). + enum: + - ScalingUp + - ScalingDown + - Running + - Failed + - Unknown + type: string + readyReplicas: + description: readyReplicas is the number of ready replicas for this + MachineDeployment. A machine is considered ready when Machine's + Ready condition is true. + format: int32 + type: integer + replicas: + description: |- + replicas is the total number of non-terminated machines targeted by this deployment + (their labels match the selector). + format: int32 + type: integer + selector: + description: |- + selector is the same as the label selector but in the string format to avoid introspection + by clients. The string will be in the same format as the query-param syntax. + More info about label selectors: http://kubernetes.io/docs/user-guide/labels#label-selectors + maxLength: 4096 + minLength: 1 + type: string + upToDateReplicas: + description: upToDateReplicas is the number of up-to-date replicas + targeted by this deployment. A machine is considered up-to-date + when Machine's UpToDate condition is true. + format: int32 + type: integer + type: object + required: + - spec + type: object + served: true storage: true subresources: scale: diff --git a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinedrainrules.yaml b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinedrainrules.yaml index 6b941073dc53..daa50c1b09b8 100644 --- a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinedrainrules.yaml +++ b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinedrainrules.yaml @@ -29,6 +29,7 @@ spec: jsonPath: .metadata.creationTimestamp name: Age type: date + deprecated: true name: v1beta1 schema: openAPIV3Schema: @@ -392,5 +393,383 @@ spec: - spec type: object served: true + storage: false + subresources: {} + - additionalPrinterColumns: + - description: Drain behavior + jsonPath: .spec.drain.behavior + name: Behavior + type: string + - description: Drain order + jsonPath: .spec.drain.order + name: Order + type: string + - description: Time duration since creation of the MachineDrainRule + jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1beta2 + schema: + openAPIV3Schema: + description: MachineDrainRule is the Schema for the MachineDrainRule API. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec defines the spec of a MachineDrainRule. + properties: + drain: + description: drain configures if and how Pods are drained. + properties: + behavior: + description: |- + behavior defines the drain behavior. + Can be either "Drain", "Skip", or "WaitCompleted". + "Drain" means that the Pods to which this MachineDrainRule applies will be drained. + If behavior is set to "Drain" the order in which Pods are drained can be configured + with the order field. When draining Pods of a Node the Pods will be grouped by order + and one group after another will be drained (by increasing order). Cluster API will + wait until all Pods of a group are terminated / removed from the Node before starting + with the next group. + "Skip" means that the Pods to which this MachineDrainRule applies will be skipped during drain. + "WaitCompleted" means that the pods to which this MachineDrainRule applies will never be evicted + and we wait for them to be completed, it is enforced that pods marked with this behavior always have Order=0. + enum: + - Drain + - Skip + - WaitCompleted + type: string + order: + description: |- + order defines the order in which Pods are drained. + Pods with higher order are drained after Pods with lower order. + order can only be set if behavior is set to "Drain". + If order is not set, 0 will be used. + Valid values for order are from -2147483648 to 2147483647 (inclusive). + format: int32 + type: integer + required: + - behavior + type: object + machines: + description: |- + machines defines to which Machines this MachineDrainRule should be applied. + + If machines is not set, the MachineDrainRule applies to all Machines in the Namespace. + If machines contains multiple selectors, the results are ORed. + Within a single Machine selector the results of selector and clusterSelector are ANDed. + Machines will be selected from all Clusters in the Namespace unless otherwise + restricted with the clusterSelector. + + Example: Selects control plane Machines in all Clusters or + Machines with label "os" == "linux" in Clusters with label + "stage" == "production". + + - selector: + matchExpressions: + - key: cluster.x-k8s.io/control-plane + operator: Exists + - selector: + matchLabels: + os: linux + clusterSelector: + matchExpressions: + - key: stage + operator: In + values: + - production + items: + description: MachineDrainRuleMachineSelector defines to which Machines + this MachineDrainRule should be applied. + minProperties: 1 + properties: + clusterSelector: + description: |- + clusterSelector is a label selector which selects Machines by the labels of + their Clusters. + This field follows standard label selector semantics; if not present or + empty, it selects Machines of all Clusters. + + If selector is also set, then the selector as a whole selects + Machines matching selector belonging to Clusters selected by clusterSelector. + If selector is not set, it selects all Machines belonging to Clusters + selected by clusterSelector. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + selector: + description: |- + selector is a label selector which selects Machines by their labels. + This field follows standard label selector semantics; if not present or + empty, it selects all Machines. + + If clusterSelector is also set, then the selector as a whole selects + Machines matching selector belonging to Clusters selected by clusterSelector. + If clusterSelector is not set, it selects all Machines matching selector in + all Clusters. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + x-kubernetes-validations: + - message: entries in machines must be unique + rule: self.all(x, self.exists_one(y, x == y)) + pods: + description: |- + pods defines to which Pods this MachineDrainRule should be applied. + + If pods is not set, the MachineDrainRule applies to all Pods in all Namespaces. + If pods contains multiple selectors, the results are ORed. + Within a single Pod selector the results of selector and namespaceSelector are ANDed. + Pods will be selected from all Namespaces unless otherwise + restricted with the namespaceSelector. + + Example: Selects Pods with label "app" == "logging" in all Namespaces or + Pods with label "app" == "prometheus" in the "monitoring" + Namespace. + + - selector: + matchExpressions: + - key: app + operator: In + values: + - logging + - selector: + matchLabels: + app: prometheus + namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: monitoring + items: + description: MachineDrainRulePodSelector defines to which Pods this + MachineDrainRule should be applied. + minProperties: 1 + properties: + namespaceSelector: + description: |- + namespaceSelector is a label selector which selects Pods by the labels of + their Namespaces. + This field follows standard label selector semantics; if not present or + empty, it selects Pods of all Namespaces. + + If selector is also set, then the selector as a whole selects + Pods matching selector in Namespaces selected by namespaceSelector. + If selector is not set, it selects all Pods in Namespaces selected by + namespaceSelector. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + selector: + description: |- + selector is a label selector which selects Pods by their labels. + This field follows standard label selector semantics; if not present or + empty, it selects all Pods. + + If namespaceSelector is also set, then the selector as a whole selects + Pods matching selector in Namespaces selected by namespaceSelector. + If namespaceSelector is not set, it selects all Pods matching selector in + all Namespaces. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + x-kubernetes-validations: + - message: entries in pods must be unique + rule: self.all(x, self.exists_one(y, x == y)) + required: + - drain + type: object + required: + - metadata + - spec + type: object + served: true storage: true subresources: {} diff --git a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinehealthchecks.yaml b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinehealthchecks.yaml index 11b4ecc90c07..fa644b4f4368 100644 --- a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinehealthchecks.yaml +++ b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinehealthchecks.yaml @@ -40,6 +40,7 @@ spec: jsonPath: .metadata.creationTimestamp name: Age type: date + deprecated: true name: v1beta1 schema: openAPIV3Schema: @@ -406,6 +407,436 @@ spec: type: object type: object served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - description: Cluster + jsonPath: .spec.clusterName + name: Cluster + type: string + - description: Number of machines currently monitored + jsonPath: .status.expectedMachines + name: Replicas + type: integer + - description: Current observed healthy machines + jsonPath: .status.currentHealthy + name: Healthy + type: integer + - description: Reconciliation paused + jsonPath: .status.conditions[?(@.type=="Paused")].status + name: Paused + priority: 10 + type: string + - description: Time duration since creation of MachineHealthCheck + jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1beta2 + schema: + openAPIV3Schema: + description: MachineHealthCheck is the Schema for the machinehealthchecks + API. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec is the specification of machine health check policy + properties: + checks: + description: |- + checks are the checks that are used to evaluate if a Machine is healthy. + + Independent of this configuration the MachineHealthCheck controller will always + flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + Machines with deleted Nodes as unhealthy. + + Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + is defaulted to 10 minutes and evaluated accordingly. + minProperties: 1 + properties: + nodeStartupTimeoutSeconds: + description: |- + nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + to consider a Machine unhealthy if a corresponding Node isn't associated + through a `Spec.ProviderID` field. + + The duration set in this field is compared to the greatest of: + - Cluster's infrastructure ready condition timestamp (if and when available) + - Control Plane's initialized condition timestamp (if and when available) + - Machine's infrastructure ready condition timestamp (if and when available) + - Machine's metadata creation timestamp + + Defaults to 10 minutes. + If you wish to disable this feature, set the value explicitly to 0. + format: int32 + minimum: 0 + type: integer + unhealthyNodeConditions: + description: |- + unhealthyNodeConditions contains a list of conditions that determine + whether a node is considered unhealthy. The conditions are combined in a + logical OR, i.e. if any of the conditions is met, the node is unhealthy. + items: + description: |- + UnhealthyNodeCondition represents a Node condition type and value with a timeout + specified as a duration. When the named condition has been in the given + status for at least the timeout value, a node is considered unhealthy. + properties: + status: + description: status of the condition, one of True, False, + Unknown. + minLength: 1 + type: string + timeoutSeconds: + description: |- + timeoutSeconds is the duration that a node must be in a given status for, + after which the node is considered unhealthy. + For example, with a value of "1h", the node must match the status + for at least 1 hour before being considered unhealthy. + format: int32 + minimum: 0 + type: integer + type: + description: type of Node condition + minLength: 1 + type: string + required: + - status + - timeoutSeconds + - type + type: object + maxItems: 100 + minItems: 1 + type: array + x-kubernetes-list-type: atomic + type: object + clusterName: + description: clusterName is the name of the Cluster this object belongs + to. + maxLength: 63 + minLength: 1 + type: string + remediation: + description: |- + remediation configures if and how remediations are triggered if a Machine is unhealthy. + + If remediation or remediation.triggerIf is not set, + remediation will always be triggered for unhealthy Machines. + + If remediation or remediation.templateRef is not set, + the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + minProperties: 1 + properties: + templateRef: + description: |- + templateRef is a reference to a remediation template + provided by an infrastructure provider. + + This field is completely optional, when filled, the MachineHealthCheck controller + creates a new object from the template referenced and hands off remediation of the machine to + a controller that lives outside of Cluster API. + properties: + apiVersion: + description: |- + apiVersion of the remediation template. + apiVersion must be fully qualified domain name followed by / and a version. + NOTE: This field must be kept in sync with the APIVersion of the remediation template. + maxLength: 317 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$ + type: string + kind: + description: |- + kind of the remediation template. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the remediation template. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiVersion + - kind + - name + type: object + triggerIf: + description: |- + triggerIf configures if remediations are triggered. + If this field is not set, remediations are always triggered. + minProperties: 1 + properties: + unhealthyInRange: + description: |- + unhealthyInRange specifies that remediations are only triggered if the number of + unhealthy Machines is in the configured range. + Takes precedence over unhealthyLessThanOrEqualTo. + Eg. "[3-5]" - This means that remediation will be allowed only when: + (a) there are at least 3 unhealthy Machines (and) + (b) there are at most 5 unhealthy Machines + maxLength: 32 + minLength: 1 + pattern: ^\[[0-9]+-[0-9]+\]$ + type: string + unhealthyLessThanOrEqualTo: + anyOf: + - type: integer + - type: string + description: |- + unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + unhealthy Machines is less than or equal to the configured value. + unhealthyInRange takes precedence if set. + x-kubernetes-int-or-string: true + type: object + type: object + selector: + description: selector is a label selector to match machines whose + health will be exercised + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. + The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector applies + to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + required: + - clusterName + - selector + type: object + status: + description: status is the most recently observed status of MachineHealthCheck + resource + minProperties: 1 + properties: + conditions: + description: |- + conditions represents the observations of a MachineHealthCheck's current state. + Known condition types are RemediationAllowed, Paused. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + currentHealthy: + description: currentHealthy is the total number of healthy machines + counted by this machine health check + format: int32 + minimum: 0 + type: integer + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. + properties: + v1beta1: + description: v1beta1 groups all the status fields that are deprecated + and will be removed when support for v1beta1 will be dropped. + properties: + conditions: + description: |- + conditions defines current service state of the MachineHealthCheck. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + type: object + type: object + expectedMachines: + description: expectedMachines is the total number of machines counted + by this machine health check + format: int32 + minimum: 0 + type: integer + observedGeneration: + description: observedGeneration is the latest generation observed + by the controller. + format: int64 + minimum: 1 + type: integer + remediationsAllowed: + description: |- + remediationsAllowed is the number of further remediations allowed by this machine health check before + maxUnhealthy short circuiting will be applied + format: int32 + minimum: 0 + type: integer + targets: + description: targets shows the current list of machines the machine + health check is watching + items: + maxLength: 253 + minLength: 1 + type: string + maxItems: 10000 + type: array + x-kubernetes-list-type: atomic + type: object + required: + - spec + type: object + served: true storage: true subresources: status: {} diff --git a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinepools.yaml b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinepools.yaml index b12c7241622a..698af44792d1 100644 --- a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinepools.yaml +++ b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinepools.yaml @@ -45,6 +45,7 @@ spec: jsonPath: .spec.template.spec.version name: Version type: string + deprecated: true name: v1beta1 schema: openAPIV3Schema: @@ -424,7 +425,7 @@ spec: failureMessage indicates that there is a problem reconciling the state, and will be set to a descriptive error message. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. maxLength: 10240 minLength: 1 type: string @@ -433,7 +434,7 @@ spec: failureReason indicates that there is a problem reconciling the state, and will be set to a token value suitable for programmatic interpretation. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. type: string infrastructureReady: description: infrastructureReady is the state of the infrastructure @@ -525,7 +526,7 @@ spec: be machine instances that are running but not yet available or machine instances that still have not been created. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. format: int32 type: integer v1beta2: @@ -619,6 +620,657 @@ spec: type: object type: object served: true + storage: false + subresources: + scale: + specReplicasPath: .spec.replicas + statusReplicasPath: .status.replicas + status: {} + - additionalPrinterColumns: + - description: Cluster + jsonPath: .spec.clusterName + name: Cluster + type: string + - description: The desired number of machines + jsonPath: .spec.replicas + name: Desired + type: integer + - description: The number of machines + jsonPath: .status.replicas + name: Current + type: integer + - description: The number of machines with Ready condition true + jsonPath: .status.readyReplicas + name: Ready + type: integer + - description: The number of machines with Available condition true + jsonPath: .status.availableReplicas + name: Available + type: integer + - description: The number of machines with UpToDate condition true + jsonPath: .status.upToDateReplicas + name: Up-to-date + type: integer + - description: Reconciliation paused + jsonPath: .status.conditions[?(@.type=="Paused")].status + name: Paused + priority: 10 + type: string + - description: MachinePool status such as Terminating/Pending/Provisioning/Running/Failed + etc + jsonPath: .status.phase + name: Phase + type: string + - description: Time duration since creation of MachinePool + jsonPath: .metadata.creationTimestamp + name: Age + type: date + - description: Kubernetes version associated with this MachinePool + jsonPath: .spec.template.spec.version + name: Version + type: string + name: v1beta2 + schema: + openAPIV3Schema: + description: |- + MachinePool is the Schema for the machinepools API. + NOTE: This CRD can only be used if the MachinePool feature gate is enabled. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec is the desired state of MachinePool. + properties: + clusterName: + description: clusterName is the name of the Cluster this object belongs + to. + maxLength: 63 + minLength: 1 + type: string + failureDomains: + description: failureDomains is the list of failure domains this MachinePool + should be attached to. + items: + maxLength: 256 + minLength: 1 + type: string + maxItems: 100 + type: array + x-kubernetes-list-type: atomic + providerIDList: + description: |- + providerIDList are the identification IDs of machine instances provided by the provider. + This field must match the provider IDs as seen on the node objects corresponding to a machine pool's machine instances. + items: + maxLength: 512 + minLength: 1 + type: string + maxItems: 10000 + type: array + x-kubernetes-list-type: atomic + replicas: + description: |- + replicas is the number of desired machines. Defaults to 1. + This is a pointer to distinguish between explicit zero and not specified. + format: int32 + type: integer + template: + description: template describes the machines that will be created. + properties: + metadata: + description: |- + metadata is the standard object's metadata. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + spec: + description: |- + spec is the specification of the desired behavior of the machine. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + properties: + bootstrap: + description: |- + bootstrap is a reference to a local struct which encapsulates + fields to configure the Machine’s bootstrapping mechanism. + properties: + configRef: + description: |- + configRef is a reference to a bootstrap provider-specific resource + that holds configuration details. The reference is optional to + allow users/operators to specify Bootstrap.DataSecretName without + the need of a controller. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + dataSecretName: + description: |- + dataSecretName is the name of the secret that stores the bootstrap data script. + If nil, the Machine should remain in the Pending state. + maxLength: 253 + minLength: 0 + type: string + type: object + clusterName: + description: clusterName is the name of the Cluster this object + belongs to. + maxLength: 63 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options for Machine + deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + format: int32 + minimum: 0 + type: integer + type: object + failureDomain: + description: |- + failureDomain is the failure domain the machine will be created in. + Must match the name of a FailureDomain from the Cluster status. + maxLength: 256 + minLength: 1 + type: string + infrastructureRef: + description: |- + infrastructureRef is a required reference to a custom resource + offered by an infrastructure provider. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + minReadySeconds: + description: |- + minReadySeconds is the minimum number of seconds for which a Machine should be ready before considering it available. + Defaults to 0 (Machine will be considered available as soon as the Machine is ready) + format: int32 + minimum: 0 + type: integer + providerID: + description: |- + providerID is the identification ID of the machine provided by the provider. + This field must match the provider ID as seen on the node object corresponding to this machine. + This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler + with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out + machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a + generic out-of-tree provider for autoscaler, this field is required by autoscaler to be + able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver + and then a comparison is done to find out unregistered machines and are marked for delete. + This field will be set by the actuators and consumed by higher level entities like autoscaler that will + be interfacing with cluster-api as generic provider. + maxLength: 512 + minLength: 1 + type: string + readinessGates: + description: |- + readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + + This field can be used e.g. by Cluster API control plane providers to extend the semantic of the + Ready condition for the Machine they control, like the kubeadm control provider adding ReadinessGates + for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + + Another example are external controllers, e.g. responsible to install special software/hardware on the Machines; + they can include the status of those components with a new condition and add this condition to ReadinessGates. + + NOTE: In case readinessGates conditions start with the APIServer, ControllerManager, Scheduler prefix, and all those + readiness gates condition are reporting the same message, when computing the Machine's Ready condition those + readinessGates will be replaced by a single entry reporting "Control plane components: " + message. + This helps to improve readability of conditions bubbling up to the Machine's owner resource / to the Cluster). + items: + description: MachineReadinessGate contains the type of a + Machine condition to be used as a readiness gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Machine's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this readinessGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + version: + description: |- + version defines the desired Kubernetes version. + This field is meant to be optionally used by bootstrap providers. + maxLength: 256 + minLength: 1 + type: string + required: + - bootstrap + - clusterName + - infrastructureRef + type: object + required: + - spec + type: object + required: + - clusterName + - template + type: object + status: + description: status is the observed state of MachinePool. + minProperties: 1 + properties: + availableReplicas: + description: availableReplicas is the number of available replicas + for this MachinePool. A machine is considered available when Machine's + Available condition is true. + format: int32 + type: integer + conditions: + description: |- + conditions represents the observations of a MachinePool's current state. + Known condition types are Available, BootstrapConfigReady, InfrastructureReady, MachinesReady, MachinesUpToDate, + ScalingUp, ScalingDown, Remediating, Deleting, Paused. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. + properties: + v1beta1: + description: v1beta1 groups all the status fields that are deprecated + and will be removed when support for v1beta1 will be dropped. + properties: + availableReplicas: + description: |- + availableReplicas is the number of available replicas (ready for at least minReadySeconds) for this MachinePool. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + conditions: + description: |- + conditions define the current service state of the MachinePool. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + failureMessage: + description: |- + failureMessage indicates that there is a problem reconciling the state, + and will be set to a descriptive error message. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + maxLength: 10240 + minLength: 1 + type: string + failureReason: + description: |- + failureReason indicates that there is a problem reconciling the state, and + will be set to a token value suitable for programmatic interpretation. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + type: string + readyReplicas: + description: |- + readyReplicas is the number of ready replicas for this MachinePool. A machine is considered ready when the node has been created and is "Ready". + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + unavailableReplicas: + description: |- + unavailableReplicas is the total number of unavailable machine instances targeted by this machine pool. + This is the total number of machine instances that are still required for + the machine pool to have 100% available capacity. They may either + be machine instances that are running but not yet available or machine instances + that still have not been created. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + type: object + type: object + initialization: + description: |- + initialization provides observations of the MachinePool initialization process. + NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial MachinePool provisioning. + minProperties: 1 + properties: + bootstrapDataSecretCreated: + description: |- + bootstrapDataSecretCreated is true when the bootstrap provider reports that the MachinePool's boostrap secret is created. + NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + The value of this field is never updated after provisioning is completed. + type: boolean + infrastructureProvisioned: + description: |- + infrastructureProvisioned is true when the infrastructure provider reports that MachinePool's infrastructure is fully provisioned. + NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + The value of this field is never updated after provisioning is completed. + type: boolean + type: object + nodeRefs: + description: nodeRefs will point to the corresponding Nodes if it + they exist. + items: + description: ObjectReference contains enough information to let + you inspect or modify the referred object. + properties: + apiVersion: + description: API version of the referent. + type: string + fieldPath: + description: |- + If referring to a piece of an object instead of an entire object, this string + should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. + For example, if the object reference is to a container within a pod, this would take on a value like: + "spec.containers{name}" (where "name" refers to the name of the container that triggered + the event) or if no container name is specified "spec.containers[2]" (container with + index 2 in this pod). This syntax is chosen only to have some well-defined way of + referencing a part of an object. + type: string + kind: + description: |- + Kind of the referent. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + name: + description: |- + Name of the referent. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + namespace: + description: |- + Namespace of the referent. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/ + type: string + resourceVersion: + description: |- + Specific resourceVersion to which this reference is made, if any. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency + type: string + uid: + description: |- + UID of the referent. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids + type: string + type: object + x-kubernetes-map-type: atomic + maxItems: 10000 + type: array + x-kubernetes-list-type: atomic + observedGeneration: + description: observedGeneration is the latest generation observed + by the controller. + format: int64 + minimum: 1 + type: integer + phase: + description: phase represents the current phase of cluster actuation. + enum: + - Pending + - Provisioning + - Provisioned + - Running + - ScalingUp + - ScalingDown + - Scaling + - Deleting + - Failed + - Unknown + type: string + readyReplicas: + description: readyReplicas is the number of ready replicas for this + MachinePool. A machine is considered ready when Machine's Ready + condition is true. + format: int32 + type: integer + replicas: + description: replicas is the most recently observed number of replicas. + format: int32 + type: integer + upToDateReplicas: + description: upToDateReplicas is the number of up-to-date replicas + targeted by this MachinePool. A machine is considered up-to-date + when Machine's UpToDate condition is true. + format: int32 + type: integer + type: object + required: + - spec + type: object + served: true storage: true subresources: scale: diff --git a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machines.yaml b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machines.yaml index 93c2dad97a2e..226e4c40393b 100644 --- a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machines.yaml +++ b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machines.yaml @@ -43,6 +43,7 @@ spec: jsonPath: .spec.version name: Version type: string + deprecated: true name: v1beta1 schema: openAPIV3Schema: @@ -411,7 +412,7 @@ spec: can be added as events to the Machine object and/or logged in the controller's output. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. maxLength: 10240 minLength: 1 type: string @@ -434,7 +435,7 @@ spec: can be added as events to the Machine object and/or logged in the controller's output. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. type: string infrastructureReady: description: infrastructureReady is the state of the infrastructure @@ -645,6 +646,669 @@ spec: type: object type: object served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - description: Cluster + jsonPath: .spec.clusterName + name: Cluster + type: string + - description: Node name associated with this machine + jsonPath: .status.nodeRef.name + name: Node Name + type: string + - description: Provider ID + jsonPath: .spec.providerID + name: Provider ID + priority: 10 + type: string + - description: Machine pass all readiness checks + jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - description: Machine is Ready for at least MinReadySeconds + jsonPath: .status.conditions[?(@.type=="Available")].status + name: Available + type: string + - description: ' Machine spec matches the spec of the Machine''s owner resource, + e.g. MachineDeployment' + jsonPath: .status.conditions[?(@.type=="UpToDate")].status + name: Up-to-date + type: string + - description: Internal IP of the machine + jsonPath: .status.addresses[?(@.type=="InternalIP")].address + name: Internal-IP + priority: 10 + type: string + - description: External IP of the machine + jsonPath: .status.addresses[?(@.type=="ExternalIP")].address + name: External-IP + priority: 10 + type: string + - description: OS Image reported by the node + jsonPath: .status.nodeInfo.osImage + name: OS-Image + priority: 10 + type: string + - description: Reconciliation paused + jsonPath: .status.conditions[?(@.type=="Paused")].status + name: Paused + priority: 10 + type: string + - description: Machine status such as Terminating/Pending/Running/Failed etc + jsonPath: .status.phase + name: Phase + type: string + - description: Time duration since creation of Machine + jsonPath: .metadata.creationTimestamp + name: Age + type: date + - description: Kubernetes version associated with this Machine + jsonPath: .spec.version + name: Version + type: string + name: v1beta2 + schema: + openAPIV3Schema: + description: Machine is the Schema for the machines API. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec is the desired state of Machine. + properties: + bootstrap: + description: |- + bootstrap is a reference to a local struct which encapsulates + fields to configure the Machine’s bootstrapping mechanism. + properties: + configRef: + description: |- + configRef is a reference to a bootstrap provider-specific resource + that holds configuration details. The reference is optional to + allow users/operators to specify Bootstrap.DataSecretName without + the need of a controller. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + dataSecretName: + description: |- + dataSecretName is the name of the secret that stores the bootstrap data script. + If nil, the Machine should remain in the Pending state. + maxLength: 253 + minLength: 0 + type: string + type: object + clusterName: + description: clusterName is the name of the Cluster this object belongs + to. + maxLength: 63 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options for Machine deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + format: int32 + minimum: 0 + type: integer + type: object + failureDomain: + description: |- + failureDomain is the failure domain the machine will be created in. + Must match the name of a FailureDomain from the Cluster status. + maxLength: 256 + minLength: 1 + type: string + infrastructureRef: + description: |- + infrastructureRef is a required reference to a custom resource + offered by an infrastructure provider. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + minReadySeconds: + description: |- + minReadySeconds is the minimum number of seconds for which a Machine should be ready before considering it available. + Defaults to 0 (Machine will be considered available as soon as the Machine is ready) + format: int32 + minimum: 0 + type: integer + providerID: + description: |- + providerID is the identification ID of the machine provided by the provider. + This field must match the provider ID as seen on the node object corresponding to this machine. + This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler + with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out + machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a + generic out-of-tree provider for autoscaler, this field is required by autoscaler to be + able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver + and then a comparison is done to find out unregistered machines and are marked for delete. + This field will be set by the actuators and consumed by higher level entities like autoscaler that will + be interfacing with cluster-api as generic provider. + maxLength: 512 + minLength: 1 + type: string + readinessGates: + description: |- + readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + + This field can be used e.g. by Cluster API control plane providers to extend the semantic of the + Ready condition for the Machine they control, like the kubeadm control provider adding ReadinessGates + for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + + Another example are external controllers, e.g. responsible to install special software/hardware on the Machines; + they can include the status of those components with a new condition and add this condition to ReadinessGates. + + NOTE: In case readinessGates conditions start with the APIServer, ControllerManager, Scheduler prefix, and all those + readiness gates condition are reporting the same message, when computing the Machine's Ready condition those + readinessGates will be replaced by a single entry reporting "Control plane components: " + message. + This helps to improve readability of conditions bubbling up to the Machine's owner resource / to the Cluster). + items: + description: MachineReadinessGate contains the type of a Machine + condition to be used as a readiness gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Machine's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this readinessGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + version: + description: |- + version defines the desired Kubernetes version. + This field is meant to be optionally used by bootstrap providers. + maxLength: 256 + minLength: 1 + type: string + required: + - bootstrap + - clusterName + - infrastructureRef + type: object + status: + description: status is the observed state of Machine. + minProperties: 1 + properties: + addresses: + description: |- + addresses is a list of addresses assigned to the machine. + This field is copied from the infrastructure provider reference. + items: + description: MachineAddress contains information for the node's + address. + properties: + address: + description: address is the machine address. + maxLength: 256 + minLength: 1 + type: string + type: + description: type is the machine address type, one of Hostname, + ExternalIP, InternalIP, ExternalDNS or InternalDNS. + enum: + - Hostname + - ExternalIP + - InternalIP + - ExternalDNS + - InternalDNS + type: string + required: + - address + - type + type: object + maxItems: 128 + type: array + x-kubernetes-list-type: atomic + certificatesExpiryDate: + description: |- + certificatesExpiryDate is the expiry date of the machine certificates. + This value is only set for control plane machines. + format: date-time + type: string + conditions: + description: |- + conditions represents the observations of a Machine's current state. + Known condition types are Available, Ready, UpToDate, BootstrapConfigReady, InfrastructureReady, NodeReady, + NodeHealthy, Deleting, Paused. + If a MachineHealthCheck is targeting this machine, also HealthCheckSucceeded, OwnerRemediated conditions are added. + Additionally control plane Machines controlled by KubeadmControlPlane will have following additional conditions: + APIServerPodHealthy, ControllerManagerPodHealthy, SchedulerPodHealthy, EtcdPodHealthy, EtcdMemberHealthy. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + deletion: + description: |- + deletion contains information relating to removal of the Machine. + Only present when the Machine has a deletionTimestamp and drain or wait for volume detach started. + properties: + nodeDrainStartTime: + description: |- + nodeDrainStartTime is the time when the drain of the node started and is used to determine + if the nodeDrainTimeoutSeconds is exceeded. + Only present when the Machine has a deletionTimestamp and draining the node had been started. + format: date-time + type: string + waitForNodeVolumeDetachStartTime: + description: |- + waitForNodeVolumeDetachStartTime is the time when waiting for volume detachment started + and is used to determine if the nodeVolumeDetachTimeoutSeconds is exceeded. + Detaching volumes from nodes is usually done by CSI implementations and the current state + is observed from the node's `.Status.VolumesAttached` field. + Only present when the Machine has a deletionTimestamp and waiting for volume detachments had been started. + format: date-time + type: string + type: object + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. + properties: + v1beta1: + description: |- + v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + properties: + conditions: + description: |- + conditions defines current service state of the Machine. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + failureMessage: + description: |- + failureMessage will be set in the event that there is a terminal problem + reconciling the Machine and will contain a more verbose string suitable + for logging and human consumption. + + This field should not be set for transitive errors that a controller + faces that are expected to be fixed automatically over + time (like service outages), but instead indicate that something is + fundamentally wrong with the Machine's spec or the configuration of + the controller, and that manual intervention is required. Examples + of terminal errors would be invalid combinations of settings in the + spec, values that are unsupported by the controller, or the + responsible controller itself being critically misconfigured. + + Any transient errors that occur during the reconciliation of Machines + can be added as events to the Machine object and/or logged in the + controller's output. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + maxLength: 10240 + minLength: 1 + type: string + failureReason: + description: |- + failureReason will be set in the event that there is a terminal problem + reconciling the Machine and will contain a succinct value suitable + for machine interpretation. + + This field should not be set for transitive errors that a controller + faces that are expected to be fixed automatically over + time (like service outages), but instead indicate that something is + fundamentally wrong with the Machine's spec or the configuration of + the controller, and that manual intervention is required. Examples + of terminal errors would be invalid combinations of settings in the + spec, values that are unsupported by the controller, or the + responsible controller itself being critically misconfigured. + + Any transient errors that occur during the reconciliation of Machines + can be added as events to the Machine object and/or logged in the + controller's output. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + type: string + type: object + type: object + initialization: + description: |- + initialization provides observations of the Machine initialization process. + NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Machine provisioning. + minProperties: 1 + properties: + bootstrapDataSecretCreated: + description: |- + bootstrapDataSecretCreated is true when the bootstrap provider reports that the Machine's boostrap secret is created. + NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + The value of this field is never updated after provisioning is completed. + type: boolean + infrastructureProvisioned: + description: |- + infrastructureProvisioned is true when the infrastructure provider reports that Machine's infrastructure is fully provisioned. + NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + The value of this field is never updated after provisioning is completed. + type: boolean + type: object + lastUpdated: + description: lastUpdated identifies when the phase of the Machine + last transitioned. + format: date-time + type: string + nodeInfo: + description: |- + nodeInfo is a set of ids/uuids to uniquely identify the node. + More info: https://kubernetes.io/docs/concepts/nodes/node/#info + properties: + architecture: + description: The Architecture reported by the node + type: string + bootID: + description: Boot ID reported by the node. + type: string + containerRuntimeVersion: + description: ContainerRuntime Version reported by the node through + runtime remote API (e.g. containerd://1.4.2). + type: string + kernelVersion: + description: Kernel Version reported by the node from 'uname -r' + (e.g. 3.16.0-0.bpo.4-amd64). + type: string + kubeProxyVersion: + description: 'Deprecated: KubeProxy Version reported by the node.' + type: string + kubeletVersion: + description: Kubelet Version reported by the node. + type: string + machineID: + description: |- + MachineID reported by the node. For unique machine identification + in the cluster this field is preferred. Learn more from man(5) + machine-id: http://man7.org/linux/man-pages/man5/machine-id.5.html + type: string + operatingSystem: + description: The Operating System reported by the node + type: string + osImage: + description: OS Image reported by the node from /etc/os-release + (e.g. Debian GNU/Linux 7 (wheezy)). + type: string + swap: + description: Swap Info reported by the node. + properties: + capacity: + description: Total amount of swap memory in bytes. + format: int64 + type: integer + type: object + systemUUID: + description: |- + SystemUUID reported by the node. For unique machine identification + MachineID is preferred. This field is specific to Red Hat hosts + https://access.redhat.com/documentation/en-us/red_hat_subscription_management/1/html/rhsm/uuid + type: string + required: + - architecture + - bootID + - containerRuntimeVersion + - kernelVersion + - kubeProxyVersion + - kubeletVersion + - machineID + - operatingSystem + - osImage + - systemUUID + type: object + nodeRef: + description: nodeRef will point to the corresponding Node if it exists. + properties: + name: + description: |- + name of the node. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - name + type: object + observedGeneration: + description: observedGeneration is the latest generation observed + by the controller. + format: int64 + minimum: 1 + type: integer + phase: + description: phase represents the current phase of machine actuation. + enum: + - Pending + - Provisioning + - Provisioned + - Running + - Deleting + - Deleted + - Failed + - Unknown + type: string + type: object + required: + - spec + type: object + served: true storage: true subresources: status: {} diff --git a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinesets.yaml b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinesets.yaml index 391cb23ea497..e0e0462abb4a 100644 --- a/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinesets.yaml +++ b/cmd/install/assets/cluster-api/cluster.x-k8s.io_machinesets.yaml @@ -48,6 +48,7 @@ spec: jsonPath: .spec.template.spec.version name: Version type: string + deprecated: true name: v1beta1 schema: openAPIV3Schema: @@ -508,7 +509,7 @@ spec: reconciling the Machine and will contain a more verbose string suitable for logging and human consumption. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. maxLength: 10240 minLength: 1 type: string @@ -537,13 +538,13 @@ spec: can be added as events to the MachineSet object and/or logged in the controller's output. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. type: string fullyLabeledReplicas: description: |- fullyLabeledReplicas is the number of replicas that have labels matching the labels of the machine template of the MachineSet. - Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. format: int32 type: integer observedGeneration: @@ -659,6 +660,683 @@ spec: type: object type: object served: true + storage: false + subresources: + scale: + labelSelectorPath: .status.selector + specReplicasPath: .spec.replicas + statusReplicasPath: .status.replicas + status: {} + - additionalPrinterColumns: + - description: Cluster + jsonPath: .spec.clusterName + name: Cluster + type: string + - description: The desired number of machines + jsonPath: .spec.replicas + name: Desired + type: integer + - description: The number of machines + jsonPath: .status.replicas + name: Current + type: integer + - description: The number of machines with Ready condition true + jsonPath: .status.readyReplicas + name: Ready + type: integer + - description: The number of machines with Available condition true + jsonPath: .status.availableReplicas + name: Available + type: integer + - description: The number of machines with UpToDate condition true + jsonPath: .status.upToDateReplicas + name: Up-to-date + type: integer + - description: Reconciliation paused + jsonPath: .status.conditions[?(@.type=="Paused")].status + name: Paused + priority: 10 + type: string + - description: Time duration since creation of MachineSet + jsonPath: .metadata.creationTimestamp + name: Age + type: date + - description: Kubernetes version associated with this MachineSet + jsonPath: .spec.template.spec.version + name: Version + type: string + name: v1beta2 + schema: + openAPIV3Schema: + description: MachineSet is the Schema for the machinesets API. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec is the desired state of MachineSet. + properties: + clusterName: + description: clusterName is the name of the Cluster this object belongs + to. + maxLength: 63 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options for MachineSet + deletion. + minProperties: 1 + properties: + order: + description: |- + order defines the order in which Machines are deleted when downscaling. + Defaults to "Random". Valid values are "Random, "Newest", "Oldest" + enum: + - Random + - Newest + - Oldest + type: string + type: object + machineNaming: + description: |- + machineNaming allows changing the naming pattern used when creating Machines. + Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines. + minProperties: 1 + properties: + template: + description: |- + template defines the template to use for generating the names of the + Machine objects. + If not defined, it will fallback to `{{ .machineSet.name }}-{{ .random }}`. + If the generated name string exceeds 63 characters, it will be trimmed to + 58 characters and will + get concatenated with a random suffix of length 5. + Length of the template string must not exceed 256 characters. + The template allows the following variables `.cluster.name`, + `.machineSet.name` and `.random`. + The variable `.cluster.name` retrieves the name of the cluster object + that owns the Machines being created. + The variable `.machineSet.name` retrieves the name of the MachineSet + object that owns the Machines being created. + The variable `.random` is substituted with random alphanumeric string, + without vowels, of length 5. This variable is required part of the + template. If not provided, validation will fail. + maxLength: 256 + minLength: 1 + type: string + type: object + replicas: + description: |- + replicas is the number of desired replicas. + This is a pointer to distinguish between explicit zero and unspecified. + + Defaults to: + * if the Kubernetes autoscaler min size and max size annotations are set: + - if it's a new MachineSet, use min size + - if the replicas field of the old MachineSet is < min size, use min size + - if the replicas field of the old MachineSet is > max size, use max size + - if the replicas field of the old MachineSet is in the (min size, max size) range, keep the value from the oldMS + * otherwise use 1 + Note: Defaulting will be run whenever the replicas field is not set: + * A new MachineSet is created with replicas not set. + * On an existing MachineSet the replicas field was first set and is now unset. + Those cases are especially relevant for the following Kubernetes autoscaler use cases: + * A new MachineSet is created and replicas should be managed by the autoscaler + * An existing MachineSet which initially wasn't controlled by the autoscaler + should be later controlled by the autoscaler + format: int32 + type: integer + selector: + description: |- + selector is a label query over machines that should match the replica count. + Label keys and values that must match in order to be controlled by this MachineSet. + It must match the machine template's labels. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. + The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector applies + to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + template: + description: |- + template is the object that describes the machine that will be created if + insufficient replicas are detected. + Object references to custom resources are treated as templates. + properties: + metadata: + description: |- + metadata is the standard object's metadata. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + minProperties: 1 + properties: + annotations: + additionalProperties: + type: string + description: |- + annotations is an unstructured key value map stored with a resource that may be + set by external tools to store and retrieve arbitrary metadata. They are not + queryable and should be preserved when modifying objects. + More info: http://kubernetes.io/docs/user-guide/annotations + type: object + labels: + additionalProperties: + type: string + description: |- + labels is a map of string keys and values that can be used to organize and categorize + (scope and select) objects. May match selectors of replication controllers + and services. + More info: http://kubernetes.io/docs/user-guide/labels + type: object + type: object + spec: + description: |- + spec is the specification of the desired behavior of the machine. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + properties: + bootstrap: + description: |- + bootstrap is a reference to a local struct which encapsulates + fields to configure the Machine’s bootstrapping mechanism. + properties: + configRef: + description: |- + configRef is a reference to a bootstrap provider-specific resource + that holds configuration details. The reference is optional to + allow users/operators to specify Bootstrap.DataSecretName without + the need of a controller. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + dataSecretName: + description: |- + dataSecretName is the name of the secret that stores the bootstrap data script. + If nil, the Machine should remain in the Pending state. + maxLength: 253 + minLength: 0 + type: string + type: object + clusterName: + description: clusterName is the name of the Cluster this object + belongs to. + maxLength: 63 + minLength: 1 + type: string + deletion: + description: deletion contains configuration options for Machine + deletion. + minProperties: 1 + properties: + nodeDeletionTimeoutSeconds: + description: |- + nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + Defaults to 10 seconds. + format: int32 + minimum: 0 + type: integer + nodeDrainTimeoutSeconds: + description: |- + nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + The default value is 0, meaning that the node can be drained without any time limitations. + NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + format: int32 + minimum: 0 + type: integer + nodeVolumeDetachTimeoutSeconds: + description: |- + nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + format: int32 + minimum: 0 + type: integer + type: object + failureDomain: + description: |- + failureDomain is the failure domain the machine will be created in. + Must match the name of a FailureDomain from the Cluster status. + maxLength: 256 + minLength: 1 + type: string + infrastructureRef: + description: |- + infrastructureRef is a required reference to a custom resource + offered by an infrastructure provider. + properties: + apiGroup: + description: |- + apiGroup is the group of the resource being referenced. + apiGroup must be fully qualified domain name. + The corresponding version for this reference will be looked up from the contract + labels of the corresponding CRD of the resource being referenced. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + kind: + description: |- + kind of the resource being referenced. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ + type: string + name: + description: |- + name of the resource being referenced. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ + type: string + required: + - apiGroup + - kind + - name + type: object + minReadySeconds: + description: |- + minReadySeconds is the minimum number of seconds for which a Machine should be ready before considering it available. + Defaults to 0 (Machine will be considered available as soon as the Machine is ready) + format: int32 + minimum: 0 + type: integer + providerID: + description: |- + providerID is the identification ID of the machine provided by the provider. + This field must match the provider ID as seen on the node object corresponding to this machine. + This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler + with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out + machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a + generic out-of-tree provider for autoscaler, this field is required by autoscaler to be + able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver + and then a comparison is done to find out unregistered machines and are marked for delete. + This field will be set by the actuators and consumed by higher level entities like autoscaler that will + be interfacing with cluster-api as generic provider. + maxLength: 512 + minLength: 1 + type: string + readinessGates: + description: |- + readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + + This field can be used e.g. by Cluster API control plane providers to extend the semantic of the + Ready condition for the Machine they control, like the kubeadm control provider adding ReadinessGates + for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + + Another example are external controllers, e.g. responsible to install special software/hardware on the Machines; + they can include the status of those components with a new condition and add this condition to ReadinessGates. + + NOTE: In case readinessGates conditions start with the APIServer, ControllerManager, Scheduler prefix, and all those + readiness gates condition are reporting the same message, when computing the Machine's Ready condition those + readinessGates will be replaced by a single entry reporting "Control plane components: " + message. + This helps to improve readability of conditions bubbling up to the Machine's owner resource / to the Cluster). + items: + description: MachineReadinessGate contains the type of a + Machine condition to be used as a readiness gate. + properties: + conditionType: + description: |- + conditionType refers to a condition with matching type in the Machine's condition list. + If the conditions doesn't exist, it will be treated as unknown. + Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + maxLength: 316 + minLength: 1 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + polarity: + description: |- + polarity of the conditionType specified in this readinessGate. + Valid values are Positive, Negative and omitted. + When omitted, the default behaviour will be Positive. + A positive polarity means that the condition should report a true status under normal conditions. + A negative polarity means that the condition should report a false status under normal conditions. + enum: + - Positive + - Negative + type: string + required: + - conditionType + type: object + maxItems: 32 + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - conditionType + x-kubernetes-list-type: map + version: + description: |- + version defines the desired Kubernetes version. + This field is meant to be optionally used by bootstrap providers. + maxLength: 256 + minLength: 1 + type: string + required: + - bootstrap + - clusterName + - infrastructureRef + type: object + required: + - spec + type: object + required: + - clusterName + - selector + - template + type: object + status: + description: status is the observed state of MachineSet. + minProperties: 1 + properties: + availableReplicas: + description: availableReplicas is the number of available replicas + for this MachineSet. A machine is considered available when Machine's + Available condition is true. + format: int32 + type: integer + conditions: + description: |- + conditions represents the observations of a MachineSet's current state. + Known condition types are MachinesReady, MachinesUpToDate, ScalingUp, ScalingDown, Remediating, Deleting, Paused. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. + properties: + v1beta1: + description: v1beta1 groups all the status fields that are deprecated + and will be removed when support for v1beta1 will be dropped. + properties: + availableReplicas: + description: |- + availableReplicas is the number of available replicas (ready for at least minReadySeconds) for this MachineSet. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + conditions: + description: |- + conditions defines current service state of the MachineSet. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + failureMessage: + description: |- + failureMessage will be set in the event that there is a terminal problem + reconciling the Machine and will contain a more verbose string suitable + for logging and human consumption. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + maxLength: 10240 + minLength: 1 + type: string + failureReason: + description: |- + failureReason will be set in the event that there is a terminal problem + reconciling the Machine and will contain a succinct value suitable + for machine interpretation. + + In the event that there is a terminal problem reconciling the + replicas, both FailureReason and FailureMessage will be set. FailureReason + will be populated with a succinct value suitable for machine + interpretation, while FailureMessage will contain a more verbose + string suitable for logging and human consumption. + + These fields should not be set for transitive errors that a + controller faces that are expected to be fixed automatically over + time (like service outages), but instead indicate that something is + fundamentally wrong with the MachineTemplate's spec or the configuration of + the machine controller, and that manual intervention is required. Examples + of terminal errors would be invalid combinations of settings in the + spec, values that are unsupported by the machine controller, or the + responsible machine controller itself being critically misconfigured. + + Any transient errors that occur during the reconciliation of Machines + can be added as events to the MachineSet object and/or logged in the + controller's output. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + type: string + fullyLabeledReplicas: + description: |- + fullyLabeledReplicas is the number of replicas that have labels matching the labels of the machine template of the MachineSet. + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + readyReplicas: + description: |- + readyReplicas is the number of ready replicas for this MachineSet. A machine is considered ready when the node has been created and is "Ready". + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + format: int32 + type: integer + type: object + type: object + observedGeneration: + description: observedGeneration reflects the generation of the most + recently observed MachineSet. + format: int64 + minimum: 1 + type: integer + readyReplicas: + description: readyReplicas is the number of ready replicas for this + MachineSet. A machine is considered ready when Machine's Ready condition + is true. + format: int32 + type: integer + replicas: + description: replicas is the most recently observed number of replicas. + format: int32 + type: integer + selector: + description: |- + selector is the same as the label selector but in the string format to avoid introspection + by clients. The string will be in the same format as the query-param syntax. + More info about label selectors: http://kubernetes.io/docs/user-guide/labels#label-selectors + maxLength: 4096 + minLength: 1 + type: string + upToDateReplicas: + description: upToDateReplicas is the number of up-to-date replicas + for this MachineSet. A machine is considered up-to-date when Machine's + UpToDate condition is true. + format: int32 + type: integer + type: object + required: + - spec + type: object + served: true storage: true subresources: scale: diff --git a/cmd/install/assets/cluster-api/ipam.cluster.x-k8s.io_ipaddressclaims.yaml b/cmd/install/assets/cluster-api/ipam.cluster.x-k8s.io_ipaddressclaims.yaml index c71b32ad3135..68a3dc3c5533 100644 --- a/cmd/install/assets/cluster-api/ipam.cluster.x-k8s.io_ipaddressclaims.yaml +++ b/cmd/install/assets/cluster-api/ipam.cluster.x-k8s.io_ipaddressclaims.yaml @@ -29,7 +29,7 @@ spec: jsonPath: .metadata.creationTimestamp name: Age type: date - name: v1beta1 + name: v1beta2 schema: openAPIV3Schema: description: IPAddressClaim is the Schema for the ipaddressclaim API. @@ -66,163 +66,187 @@ spec: properties: apiGroup: description: |- - APIGroup is the group for the resource being referenced. - If APIGroup is not specified, the specified Kind must be in the core API group. - For any other third-party types, APIGroup is required. + apiGroup of the IPPool. + apiGroup must be fully qualified domain name. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string kind: - description: Kind is the type of resource being referenced + description: |- + kind of the IPPool. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ type: string name: - description: Name is the name of resource being referenced + description: |- + name of the IPPool. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string required: + - apiGroup - kind - name type: object - x-kubernetes-map-type: atomic required: - poolRef type: object status: description: status is the observed state of IPAddressClaim. + minProperties: 1 properties: addressRef: description: addressRef is a reference to the address that was created for this claim. properties: name: - default: "" description: |- - Name of the referent. - This field is effectively required, but due to backwards compatibility is - allowed to be empty. Instances of this type with an empty value here are - almost certainly wrong. - More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + name of the IPAddress. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string + required: + - name type: object - x-kubernetes-map-type: atomic conditions: - description: conditions summarises the current state of the IPAddressClaim + description: |- + conditions represents the observations of a IPAddressClaim's current state. + Known condition types are Ready. items: - description: Condition defines an observation of a Cluster API resource - operational state. + description: Condition contains details for one aspect of the current + state of this API Resource. properties: lastTransitionTime: description: |- lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. format: date-time type: string message: description: |- message is a human readable message indicating details about the transition. - This field may be empty. - maxLength: 10240 - minLength: 1 + This may be an empty string. + maxLength: 32768 type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer reason: description: |- - reason is the reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may be empty. - maxLength: 256 + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 minLength: 1 - type: string - severity: - description: |- - severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - maxLength: 32 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ type: string status: description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown type: string type: - description: |- - type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - maxLength: 256 - minLength: 1 + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ type: string required: - lastTransitionTime + - message + - reason - status - type type: object + maxItems: 32 type: array - v1beta2: - description: v1beta2 groups all the fields that will be added or modified - in IPAddressClaim's status with the V1Beta2 version. + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + deprecated: + description: deprecated groups all the status fields that are deprecated + and will be removed when all the nested field are removed. properties: - conditions: - description: conditions represents the observations of a IPAddressClaim's - current state. - items: - description: Condition contains details for one aspect of the - current state of this API Resource. - properties: - lastTransitionTime: - description: |- - lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - message is a human readable message indicating details about the transition. - This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: |- - observedGeneration represents the .metadata.generation that the condition was set based upon. - For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date - with respect to the current state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: |- - reason contains a programmatic identifier indicating the reason for the condition's last transition. - Producers of specific condition types may define expected values and meanings for this field, - and whether the values are considered a guaranteed API. - The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, - Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - maxItems: 32 - type: array - x-kubernetes-list-map-keys: - - type - x-kubernetes-list-type: map + v1beta1: + description: v1beta1 groups all the status fields that are deprecated + and will be removed when support for v1beta1 will be dropped. + properties: + conditions: + description: |- + conditions summarises the current state of the IPAddressClaim + + Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + items: + description: Condition defines an observation of a Cluster + API resource operational state. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when + the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This field may be empty. + maxLength: 10240 + minLength: 1 + type: string + reason: + description: |- + reason is the reason for the condition's last transition in CamelCase. + The specific API may choose whether or not this field is considered a guaranteed API. + This field may be empty. + maxLength: 256 + minLength: 1 + type: string + severity: + description: |- + severity provides an explicit classification of Reason code, so the users or machines can immediately + understand the current situation and act accordingly. + The Severity field MUST be set only when Status=False. + maxLength: 32 + type: string + status: + description: status of the condition, one of True, False, + Unknown. + type: string + type: + description: |- + type of condition in CamelCase or in foo.example.com/CamelCase. + Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + can be useful (see .node.status.conditions), the ability to deconflict is important. + maxLength: 256 + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + type: object type: object type: object + required: + - spec type: object served: true storage: true diff --git a/cmd/install/assets/cluster-api/ipam.cluster.x-k8s.io_ipaddresses.yaml b/cmd/install/assets/cluster-api/ipam.cluster.x-k8s.io_ipaddresses.yaml index 2019fa2a5330..a6549f5e9cfd 100644 --- a/cmd/install/assets/cluster-api/ipam.cluster.x-k8s.io_ipaddresses.yaml +++ b/cmd/install/assets/cluster-api/ipam.cluster.x-k8s.io_ipaddresses.yaml @@ -33,7 +33,7 @@ spec: jsonPath: .metadata.creationTimestamp name: Age type: date - name: v1beta1 + name: v1beta2 schema: openAPIV3Schema: description: IPAddress is the Schema for the ipaddress API. @@ -68,16 +68,16 @@ spec: created for. properties: name: - default: "" description: |- - Name of the referent. - This field is effectively required, but due to backwards compatibility is - allowed to be empty. Instances of this type with an empty value here are - almost certainly wrong. - More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + name of the IPAddressClaim. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string + required: + - name type: object - x-kubernetes-map-type: atomic gateway: description: gateway is the network gateway of the network the address is from. @@ -90,23 +90,38 @@ spec: properties: apiGroup: description: |- - APIGroup is the group for the resource being referenced. - If APIGroup is not specified, the specified Kind must be in the core API group. - For any other third-party types, APIGroup is required. + apiGroup of the IPPool. + apiGroup must be fully qualified domain name. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string kind: - description: Kind is the type of resource being referenced + description: |- + kind of the IPPool. + kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + maxLength: 63 + minLength: 1 + pattern: ^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$ type: string name: - description: Name is the name of resource being referenced + description: |- + name of the IPPool. + name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + maxLength: 253 + minLength: 1 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string required: + - apiGroup - kind - name type: object - x-kubernetes-map-type: atomic prefix: description: prefix is the prefix of the address. + format: int32 + maximum: 128 + minimum: 0 type: integer required: - address @@ -114,6 +129,8 @@ spec: - poolRef - prefix type: object + required: + - spec type: object served: true storage: true diff --git a/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-Hypershift-Default.yaml b/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-Hypershift-Default.yaml index dafa030ea845..9b77b0a53630 100644 --- a/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-Hypershift-Default.yaml +++ b/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-Hypershift-Default.yaml @@ -21,6 +21,9 @@ { "name": "AROHCPManagedIdentities" }, + { + "name": "ExternalOIDCWithUpstreamParity" + }, { "name": "OpenStack" }, diff --git a/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-Hypershift-TechPreviewNoUpgrade.yaml b/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-Hypershift-TechPreviewNoUpgrade.yaml index 3fd33ceac830..6bf6115cb585 100644 --- a/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-Hypershift-TechPreviewNoUpgrade.yaml +++ b/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-Hypershift-TechPreviewNoUpgrade.yaml @@ -40,6 +40,9 @@ { "name": "ExternalOIDCWithUIDAndExtraClaimMappings" }, + { + "name": "ExternalOIDCWithUpstreamParity" + }, { "name": "GCPPlatform" }, diff --git a/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-SelfManagedHA-Default.yaml b/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-SelfManagedHA-Default.yaml index 84bf5a8e1d73..e39f3861a86f 100644 --- a/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-SelfManagedHA-Default.yaml +++ b/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-SelfManagedHA-Default.yaml @@ -18,6 +18,9 @@ { "name": "AutoNodeKarpenter", }, + { + "name": "ExternalOIDCWithUpstreamParity" + }, { "name": "AROHCPManagedIdentities" }, diff --git a/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-SelfManagedHA-TechPreviewNoUpgrade.yaml b/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-SelfManagedHA-TechPreviewNoUpgrade.yaml index 479143480aa2..be4bd6ea1c9e 100644 --- a/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-SelfManagedHA-TechPreviewNoUpgrade.yaml +++ b/cmd/install/assets/hypershift-operator/payload-manifests/featuregates/featureGate-SelfManagedHA-TechPreviewNoUpgrade.yaml @@ -40,6 +40,9 @@ { "name": "ExternalOIDCWithUIDAndExtraClaimMappings" }, + { + "name": "ExternalOIDCWithUpstreamParity" + }, { "name": "GCPPlatform" }, diff --git a/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-CustomNoUpgrade.crd.yaml b/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-CustomNoUpgrade.crd.yaml index 5427da20aa98..9f3f2340d95c 100644 --- a/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-CustomNoUpgrade.crd.yaml +++ b/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-CustomNoUpgrade.crd.yaml @@ -8468,6 +8468,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-Default.crd.yaml b/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-Default.crd.yaml index a80aa8b4a8dd..586716a432b5 100644 --- a/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-Default.crd.yaml +++ b/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-Default.crd.yaml @@ -7046,6 +7046,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-TechPreviewNoUpgrade.crd.yaml b/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-TechPreviewNoUpgrade.crd.yaml index aae75c3c0761..13d06bb62df0 100644 --- a/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-TechPreviewNoUpgrade.crd.yaml +++ b/cmd/install/assets/hypershift-operator/zz_generated.crd-manifests/hostedcontrolplanes-Hypershift-TechPreviewNoUpgrade.crd.yaml @@ -8368,6 +8368,22 @@ spec: is managed by an external service. https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 type: boolean + initialization: + description: |- + initialization contains observations of the HostedControlPlane initialization process. + This satisfies the CAPI v1beta2 ControlPlane provider contract: + https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + minProperties: 1 + properties: + controlPlaneInitialized: + default: false + description: |- + controlPlaneInitialized is true when the control plane is functional enough to accept requests. + Once this condition is marked true, its value is never changed. See the Ready condition for an + indication of the current readiness of the cluster's control plane. + This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + type: boolean + type: object initialized: default: false description: |- diff --git a/cmd/install/install.go b/cmd/install/install.go index 5c6b9d252aae..bba443621acd 100644 --- a/cmd/install/install.go +++ b/cmd/install/install.go @@ -849,28 +849,42 @@ func setupCRDs(ctx context.Context, client crclient.Client, opts Options, operat } return true }, func(crd *apiextensionsv1.CustomResourceDefinition) { - if crd.Spec.Group == "hypershift.openshift.io" { - if !opts.EnableConversionWebhook { - return - } - if crd.Annotations != nil { - crd.Annotations = map[string]string{} - } - crd.Annotations["service.beta.openshift.io/inject-cabundle"] = "true" - crd.Spec.Conversion = &apiextensionsv1.CustomResourceConversion{ - Strategy: apiextensionsv1.WebhookConverter, - Webhook: &apiextensionsv1.WebhookConversion{ - ClientConfig: &apiextensionsv1.WebhookClientConfig{ - Service: &apiextensionsv1.ServiceReference{ - Namespace: operatorNamespace.Name, - Name: operatorService.Name, - Port: ptr.To[int32](443), - Path: ptr.To("/convert"), - }, + // Check if this CRD needs a conversion webhook + var needsConversion bool + var conversionReviewVersions []string + + // Hypershift conversion can be toggled with a flag + if crd.Spec.Group == "hypershift.openshift.io" && opts.EnableConversionWebhook { + needsConversion = true + conversionReviewVersions = []string{"v1beta1", "v1alpha1"} + + // CAPI conversion is always required during v1beta1 -> v1beta2 transition period + // to support older CPO versions (e.g. 4.21 HC) that still use v1beta1 CAPI types. + } else if override, ok := assets.CAPICRDOverrides[crd.Name]; ok && override.NeedsConversion { + needsConversion = true + conversionReviewVersions = []string{"v1beta1", "v1beta2"} + } + + if !needsConversion { + return + } + if crd.Annotations == nil { + crd.Annotations = map[string]string{} + } + crd.Annotations["service.beta.openshift.io/inject-cabundle"] = "true" + crd.Spec.Conversion = &apiextensionsv1.CustomResourceConversion{ + Strategy: apiextensionsv1.WebhookConverter, + Webhook: &apiextensionsv1.WebhookConversion{ + ClientConfig: &apiextensionsv1.WebhookClientConfig{ + Service: &apiextensionsv1.ServiceReference{ + Namespace: operatorNamespace.Name, + Name: operatorService.Name, + Port: ptr.To[int32](443), + Path: ptr.To("/convert"), }, - ConversionReviewVersions: []string{"v1beta1", "v1alpha1"}, }, - } + ConversionReviewVersions: conversionReviewVersions, + }, } }, )..., diff --git a/control-plane-operator/controllers/hostedcontrolplane/hostedcontrolplane_controller.go b/control-plane-operator/controllers/hostedcontrolplane/hostedcontrolplane_controller.go index be1d7ccbaa10..61c2a6cfeb4f 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/hostedcontrolplane_controller.go +++ b/control-plane-operator/controllers/hostedcontrolplane/hostedcontrolplane_controller.go @@ -809,6 +809,10 @@ func (r *HostedControlPlaneReconciler) Reconcile(ctx context.Context, req ctrl.R } hostedControlPlane.Status.Initialized = true + // Set status.initialization.controlPlaneInitialized for CAPI 1.11 v1beta2 contract. + // CAPI reads this field from the ControlPlane provider object to determine if the + // control plane is initialized (ControlPlaneInitialized condition on the CAPI Cluster). + hostedControlPlane.Status.Initialization.ControlPlaneInitialized = ptr.To(true) meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, util.GenerateReconciliationActiveCondition(hostedControlPlane.Spec.PausedUntil, hostedControlPlane.Generation)) // Always update status based on the current state of the world. diff --git a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kubeconfig.go b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kubeconfig.go index 75763a890df7..14127d81ac81 100644 --- a/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kubeconfig.go +++ b/control-plane-operator/controllers/hostedcontrolplane/v2/kas/kubeconfig.go @@ -17,7 +17,7 @@ import ( clientcmd "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/control-plane-operator/hostedclusterconfigoperator/api/scheme.go b/control-plane-operator/hostedclusterconfigoperator/api/scheme.go index 43957d5aedaf..dd7fd922de5e 100644 --- a/control-plane-operator/hostedclusterconfigoperator/api/scheme.go +++ b/control-plane-operator/hostedclusterconfigoperator/api/scheme.go @@ -26,7 +26,7 @@ import ( clientgoscheme "k8s.io/client-go/kubernetes/scheme" apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" snapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v6/apis/volumesnapshot/v1" operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1" diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/globalps_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/globalps_test.go index 2c68f5a296e2..7e9ee0528ee8 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/globalps_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/globalps/globalps_test.go @@ -16,7 +16,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) @@ -82,7 +82,7 @@ func TestReconcileGlobalPullSecret(t *testing.T) { Labels: map[string]string{"machineset": "test"}, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{Name: "test-node-1"}, + NodeRef: capiv1.MachineNodeReference{Name: "test-node-1"}, }, }, }, @@ -156,7 +156,7 @@ func TestReconcileGlobalPullSecret(t *testing.T) { Labels: map[string]string{"machineset": "test"}, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{Name: "test-node-1"}, + NodeRef: capiv1.MachineNodeReference{Name: "test-node-1"}, }, }, }, @@ -273,7 +273,7 @@ func TestReconcileGlobalPullSecret(t *testing.T) { Labels: map[string]string{"machineset": "test"}, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{Name: "test-node-1"}, + NodeRef: capiv1.MachineNodeReference{Name: "test-node-1"}, }, }, }, @@ -325,7 +325,7 @@ func TestReconcileGlobalPullSecret(t *testing.T) { Labels: map[string]string{"machineset": "inplace"}, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{Name: "inplace-node-1"}, + NodeRef: capiv1.MachineNodeReference{Name: "inplace-node-1"}, }, }, }, diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader.go b/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader.go index 3ceb122e833e..ffaaac023de2 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader.go @@ -20,7 +20,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" @@ -687,7 +687,7 @@ func getNodesForMachineSet(ctx context.Context, c client.Reader, hostedClusterCl var nodes []*corev1.Node nodeToMachine := make(map[string]*capiv1.Machine) for i, machine := range machineSetOwnedMachines { - if machine.Status.NodeRef != nil { + if machine.Status.NodeRef.IsDefined() { node := &corev1.Node{} if err := hostedClusterClient.Get(ctx, client.ObjectKey{Name: machine.Status.NodeRef.Name}, node); err != nil { return nil, nil, fmt.Errorf("error getting node: %w", err) diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader_test.go index a2f28becfa44..82cfbe637ebe 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/inplaceupgrader_test.go @@ -15,7 +15,7 @@ import ( "k8s.io/client-go/kubernetes/scheme" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) @@ -56,7 +56,7 @@ func TestGetNodesForMachineSet(t *testing.T) { Labels: selector, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{ + NodeRef: capiv1.MachineNodeReference{ Name: "test", }, }, @@ -75,7 +75,7 @@ func TestGetNodesForMachineSet(t *testing.T) { Labels: selector, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{ + NodeRef: capiv1.MachineNodeReference{ Name: "otherOwner", }, }, @@ -96,7 +96,7 @@ func TestGetNodesForMachineSet(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{ + NodeRef: capiv1.MachineNodeReference{ Name: "otherSelector", }, }, @@ -631,7 +631,7 @@ func TestReconcileInPlaceUpgradeAnnotatesMachineWithNodePoolVersion(t *testing.T }, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{Name: "test-node"}, + NodeRef: capiv1.MachineNodeReference{Name: "test-node"}, }, } @@ -651,7 +651,7 @@ func TestReconcileInPlaceUpgradeAnnotatesMachineWithNodePoolVersion(t *testing.T }, }, Status: capiv1.MachineStatus{ - NodeRef: &corev1.ObjectReference{Name: "upgrading-node"}, + NodeRef: capiv1.MachineNodeReference{Name: "upgrading-node"}, }, } diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/setup.go b/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/setup.go index 22092f08d136..7db84b423a93 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/setup.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/inplaceupgrader/setup.go @@ -8,7 +8,7 @@ import ( corev1 "k8s.io/api/core/v1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/handler" diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/machine/machine.go b/control-plane-operator/hostedclusterconfigoperator/controllers/machine/machine.go index c0f9876fe8eb..58f369eac1e2 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/machine/machine.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/machine/machine.go @@ -18,7 +18,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/machine/machine_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/machine/machine_test.go index 54455beb85a4..fc90baed5a22 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/machine/machine_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/machine/machine_test.go @@ -17,7 +17,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -98,7 +98,7 @@ func TestReconcileDefaultIngressEndpoints(t *testing.T) { TypeMeta: machineTypeMeta, ObjectMeta: worker1Meta, Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ + InfrastructureRef: capiv1.ContractVersionedObjectReference{ Name: vmWorker1Meta.Name, }, }, @@ -120,7 +120,7 @@ func TestReconcileDefaultIngressEndpoints(t *testing.T) { TypeMeta: machineTypeMeta, ObjectMeta: worker2Meta, Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ + InfrastructureRef: capiv1.ContractVersionedObjectReference{ Name: vmWorker2Meta.Name, }, }, @@ -426,7 +426,7 @@ func TestReconcileDefaultIngressEndpoints(t *testing.T) { }, { name: "With Failing machine with internal addresses and passthrow service should mark endpointslices as not ready/not serving", - machines: pairOfDualStackMachines(capiv1.MachinePhaseRunning, capiv1.MachinePhaseFailed), + machines: pairOfDualStackMachines(capiv1.MachinePhaseRunning, capiv1.MachinePhaseUnknown), virtualMachines: pairOfVirtualMachines, services: []corev1.Service{defaultIngressService}, expectedServices: []corev1.Service{defaultIngressService}, diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/machine/setup.go b/control-plane-operator/hostedclusterconfigoperator/controllers/machine/setup.go index 4cd245a84f5d..74bb1d0a09ad 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/machine/setup.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/machine/setup.go @@ -14,7 +14,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/rest" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/node/node.go b/control-plane-operator/hostedclusterconfigoperator/controllers/node/node.go index d43a6d48e7d6..81ff4a61d6bd 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/node/node.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/node/node.go @@ -15,7 +15,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/node/node_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/node/node_test.go index eddda9f6fd89..2a8c1e7fd4b5 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/node/node_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/node/node_test.go @@ -11,7 +11,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/scheme" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation.go b/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation.go index 1696a9ad7c03..55a22c4fab43 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation.go @@ -9,7 +9,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" diff --git a/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation_test.go b/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation_test.go index 7163740d5fce..6e569faa4f57 100644 --- a/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation_test.go +++ b/control-plane-operator/hostedclusterconfigoperator/controllers/spotremediation/spotremediation_test.go @@ -12,7 +12,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" diff --git a/docs/content/reference/aggregated-docs.md b/docs/content/reference/aggregated-docs.md index e895208cfcfa..9c0ad198060a 100644 --- a/docs/content/reference/aggregated-docs.md +++ b/docs/content/reference/aggregated-docs.md @@ -38367,6 +38367,41 @@ ConfigurationStatus +###HostedControlPlaneInitializationStatus { #hypershift.openshift.io/v1beta1.HostedControlPlaneInitializationStatus } +

+(Appears on: +HostedControlPlaneStatus) +

+

+

HostedControlPlaneInitializationStatus provides observations of the HostedControlPlane initialization process. +This satisfies the CAPI v1beta2 ControlPlane provider contract: +https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1361-L1379

+

+ + + + + + + + + + + + + +
FieldDescription
+controlPlaneInitialized
+ +bool + +
+(Optional) +

controlPlaneInitialized is true when the control plane is functional enough to accept requests. +Once this condition is marked true, its value is never changed. See the Ready condition for an +indication of the current readiness of the cluster’s control plane. +This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379

+
###HostedControlPlaneSpec { #hypershift.openshift.io/v1beta1.HostedControlPlaneSpec }

HostedControlPlaneSpec defines the desired state of HostedControlPlane

@@ -38933,6 +38968,22 @@ This satisfies CAPI contract +HostedControlPlaneInitializationStatus + + + + +(Optional) +

initialization contains observations of the HostedControlPlane initialization process. +This satisfies the CAPI v1beta2 ControlPlane provider contract: +https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379

+ + + + externalManagedControlPlane
bool diff --git a/docs/content/reference/api.md b/docs/content/reference/api.md index bb69b40a7f43..e6255f88761b 100644 --- a/docs/content/reference/api.md +++ b/docs/content/reference/api.md @@ -9450,6 +9450,41 @@ ConfigurationStatus +###HostedControlPlaneInitializationStatus { #hypershift.openshift.io/v1beta1.HostedControlPlaneInitializationStatus } +

+(Appears on: +HostedControlPlaneStatus) +

+

+

HostedControlPlaneInitializationStatus provides observations of the HostedControlPlane initialization process. +This satisfies the CAPI v1beta2 ControlPlane provider contract: +https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1361-L1379

+

+ + + + + + + + + + + + + +
FieldDescription
+controlPlaneInitialized
+ +bool + +
+(Optional) +

controlPlaneInitialized is true when the control plane is functional enough to accept requests. +Once this condition is marked true, its value is never changed. See the Ready condition for an +indication of the current readiness of the cluster’s control plane. +This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379

+
###HostedControlPlaneSpec { #hypershift.openshift.io/v1beta1.HostedControlPlaneSpec }

HostedControlPlaneSpec defines the desired state of HostedControlPlane

@@ -10016,6 +10051,22 @@ This satisfies CAPI contract +HostedControlPlaneInitializationStatus + +
+ + +(Optional) +

initialization contains observations of the HostedControlPlane initialization process. +This satisfies the CAPI v1beta2 ControlPlane provider contract: +https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379

+ + + + externalManagedControlPlane
bool diff --git a/go.mod b/go.mod index 57995b043647..2ebe8385abd5 100644 --- a/go.mod +++ b/go.mod @@ -14,12 +14,12 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.4.0 github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 github.com/Azure/msi-dataplane v0.4.3 - github.com/IBM-Cloud/power-go-client v1.11.0 - github.com/IBM/go-sdk-core/v5 v5.19.1 - github.com/IBM/ibm-cos-sdk-go v1.12.2 - github.com/IBM/networking-go-sdk v0.51.4 - github.com/IBM/platform-services-go-sdk v0.81.0 - github.com/IBM/vpc-go-sdk v0.68.0 + github.com/IBM-Cloud/power-go-client v1.12.0 + github.com/IBM/go-sdk-core/v5 v5.21.0 + github.com/IBM/ibm-cos-sdk-go v1.12.3 + github.com/IBM/networking-go-sdk v0.51.11 + github.com/IBM/platform-services-go-sdk v0.86.1 + github.com/IBM/vpc-go-sdk v0.71.1 github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/aws/aws-sdk-go-v2 v1.41.2 github.com/aws/aws-sdk-go-v2/config v1.32.7 @@ -64,7 +64,7 @@ require ( github.com/openshift/api v0.0.0-20260304122341-cf5d8996109f github.com/openshift/client-go v0.0.0-20251202151200-fb4471581cf8 github.com/openshift/cloud-credential-operator v0.0.0-20250225003505-216fd1a30ec3 - github.com/openshift/cluster-api-provider-agent/api v0.0.0-20250624174747-899af6573f5f + github.com/openshift/cluster-api-provider-agent/api v0.0.0-20260120122324-898e638ec7d1 github.com/openshift/cluster-autoscaler-operator v0.0.1-0.20241204142113-43631b045675 github.com/openshift/cluster-node-tuning-operator v0.0.0-20250225115807-f166846b7256 github.com/openshift/custom-resource-status v1.1.3-0.20220503160415-f2fdb4999d87 @@ -105,29 +105,29 @@ require ( k8s.io/apimachinery v0.34.3 k8s.io/apiserver v0.34.3 k8s.io/autoscaler/vertical-pod-autoscaler v1.3.0 - k8s.io/cli-runtime v0.34.2 + k8s.io/cli-runtime v0.34.3 k8s.io/client-go v0.34.3 k8s.io/component-base v0.34.3 k8s.io/klog v1.0.0 k8s.io/klog/v2 v2.130.1 k8s.io/kube-aggregator v0.34.2 k8s.io/kube-scheduler v0.34.2 - k8s.io/kubectl v0.34.2 + k8s.io/kubectl v0.34.3 k8s.io/pod-security-admission v0.34.2 k8s.io/utils v0.0.0-20260108192941-914a6e750570 kubevirt.io/api v1.7.1 kubevirt.io/containerized-data-importer-api v1.64.0 - sigs.k8s.io/cluster-api v1.10.4 - sigs.k8s.io/cluster-api-provider-aws/v2 v2.8.2-0.20250820205306-645f38e4c152 - sigs.k8s.io/cluster-api-provider-azure v1.21.0 - sigs.k8s.io/cluster-api-provider-gcp v1.10.0 - sigs.k8s.io/cluster-api-provider-ibmcloud v0.11.0 - sigs.k8s.io/cluster-api-provider-kubevirt v0.1.9 - sigs.k8s.io/cluster-api-provider-openstack v0.12.1 + sigs.k8s.io/cluster-api v1.11.5 + sigs.k8s.io/cluster-api-provider-aws/v2 v2.10.0 + sigs.k8s.io/cluster-api-provider-azure v1.22.0 + sigs.k8s.io/cluster-api-provider-gcp v1.11.0 + sigs.k8s.io/cluster-api-provider-ibmcloud v0.12.0 + sigs.k8s.io/cluster-api-provider-kubevirt v0.11.1 + sigs.k8s.io/cluster-api-provider-openstack v0.13.3 sigs.k8s.io/controller-runtime v0.22.4 sigs.k8s.io/karpenter v1.8.2 sigs.k8s.io/secrets-store-csi-driver v1.4.8 - sigs.k8s.io/structured-merge-diff/v6 v6.3.0 + sigs.k8s.io/structured-merge-diff/v6 v6.3.1 sigs.k8s.io/yaml v1.6.0 ) @@ -139,9 +139,9 @@ require ( cyphar.com/go-pathrs v0.2.1 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.7.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.3.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 // indirect - github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect + github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect github.com/MakeNowJust/heredoc v1.0.0 // indirect github.com/Masterminds/semver/v3 v3.4.0 // indirect @@ -170,7 +170,7 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/speakeasy v0.2.0 // indirect github.com/blang/semver/v4 v4.0.0 // indirect - github.com/cenkalti/backoff/v5 v5.0.2 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chai2010/gettext-go v1.0.3 // indirect github.com/cheggaaa/pb/v3 v3.1.6 // indirect @@ -182,26 +182,37 @@ require ( github.com/docker/go-metrics v0.0.1 // indirect github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect github.com/dustin/go-humanize v1.0.1 // indirect - github.com/emicklei/go-restful/v3 v3.12.2 // indirect + github.com/emicklei/go-restful/v3 v3.13.0 // indirect github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f // indirect github.com/fatih/color v1.18.0 // indirect github.com/felixge/fgprof v0.9.4 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect - github.com/gabriel-vasile/mimetype v1.4.8 // indirect + github.com/gabriel-vasile/mimetype v1.4.9 // indirect github.com/go-errors/errors v1.5.1 // indirect github.com/go-jose/go-jose/v4 v4.1.3 // indirect - github.com/go-openapi/analysis v0.21.5 // indirect + github.com/go-openapi/analysis v0.23.0 // indirect github.com/go-openapi/errors v0.22.1 // indirect - github.com/go-openapi/jsonpointer v0.21.1 // indirect - github.com/go-openapi/jsonreference v0.21.0 // indirect - github.com/go-openapi/loads v0.21.3 // indirect - github.com/go-openapi/runtime v0.26.2 // indirect - github.com/go-openapi/spec v0.20.12 // indirect + github.com/go-openapi/jsonpointer v0.22.4 // indirect + github.com/go-openapi/jsonreference v0.21.4 // indirect + github.com/go-openapi/loads v0.22.0 // indirect + github.com/go-openapi/runtime v0.28.0 // indirect + github.com/go-openapi/spec v0.21.0 // indirect github.com/go-openapi/strfmt v0.23.0 // indirect - github.com/go-openapi/swag v0.23.1 // indirect - github.com/go-openapi/validate v0.22.4 // indirect + github.com/go-openapi/swag v0.25.4 // indirect + github.com/go-openapi/swag/cmdutils v0.25.4 // indirect + github.com/go-openapi/swag/conv v0.25.4 // indirect + github.com/go-openapi/swag/fileutils v0.25.4 // indirect + github.com/go-openapi/swag/jsonname v0.25.4 // indirect + github.com/go-openapi/swag/jsonutils v0.25.4 // indirect + github.com/go-openapi/swag/loading v0.25.4 // indirect + github.com/go-openapi/swag/mangling v0.25.4 // indirect + github.com/go-openapi/swag/netutils v0.25.4 // indirect + github.com/go-openapi/swag/stringutils v0.25.4 // indirect + github.com/go-openapi/swag/typeutils v0.25.4 // indirect + github.com/go-openapi/swag/yamlutils v0.25.4 // indirect + github.com/go-openapi/validate v0.24.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.26.0 // indirect @@ -213,31 +224,29 @@ require ( github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/google/btree v1.1.3 // indirect - github.com/google/gnostic-models v0.7.0 // indirect + github.com/google/gnostic-models v0.7.1 // indirect github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.12 // indirect github.com/googleapis/gax-go/v2 v2.17.0 // indirect - github.com/gophercloud/gophercloud/v2 v2.4.0 // indirect + github.com/gophercloud/gophercloud/v2 v2.10.0 // indirect github.com/gorilla/mux v1.8.1 // indirect github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.0.1 // indirect github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-retryablehttp v0.7.8 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jonboulle/clockwork v0.5.0 // indirect - github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/krishicks/yaml-patch v0.0.10 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect - github.com/mailru/easyjson v0.9.0 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.16 // indirect @@ -246,7 +255,7 @@ require ( github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/moby/spdystream v0.5.0 // indirect github.com/moby/sys/user v0.4.0 // indirect - github.com/moby/term v0.5.0 // indirect + github.com/moby/term v0.5.2 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect @@ -255,19 +264,19 @@ require ( github.com/oklog/ulid v1.3.1 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/opencontainers/selinux v1.13.0 // indirect + github.com/openshift-online/ocm-common v0.0.31 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/patrickmn/go-cache v2.1.0+incompatible // indirect github.com/peterbourgon/diskv v2.0.1+incompatible // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pkg/profile v1.7.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/procfs v0.16.1 // indirect + github.com/prometheus/procfs v0.19.2 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/robfig/cron v1.2.0 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/samber/lo v1.51.0 // indirect - github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect github.com/shopspring/decimal v1.4.0 // indirect github.com/sirupsen/logrus v1.9.4 // indirect github.com/soheilhy/cmux v0.1.5 // indirect @@ -281,21 +290,21 @@ require ( go.etcd.io/etcd/pkg/v3 v3.6.8 // indirect go.etcd.io/gofail v0.2.0 // indirect go.etcd.io/raft/v3 v3.6.0 // indirect - go.mongodb.org/mongo-driver v1.17.2 // indirect + go.mongodb.org/mongo-driver v1.17.3 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect go.opentelemetry.io/otel v1.40.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.39.0 // indirect go.opentelemetry.io/otel/metric v1.40.0 // indirect go.opentelemetry.io/otel/sdk v1.40.0 // indirect go.opentelemetry.io/otel/trace v1.40.0 // indirect - go.opentelemetry.io/proto/otlp v1.7.1 // indirect + go.opentelemetry.io/proto/otlp v1.9.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect + golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 // indirect golang.org/x/mod v0.33.0 // indirect golang.org/x/sys v0.41.0 // indirect golang.org/x/term v0.40.0 // indirect @@ -305,21 +314,21 @@ require ( google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260217215200-42d3e9bedb6d // indirect google.golang.org/protobuf v1.36.11 // indirect - gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect + gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect k8s.io/cloud-provider v0.34.1 // indirect - k8s.io/component-helpers v0.34.2 // indirect + k8s.io/component-helpers v0.34.3 // indirect k8s.io/csi-translation-lib v0.34.1 // indirect k8s.io/kms v0.34.3 // indirect - k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b // indirect + k8s.io/kube-openapi v0.0.0-20251125145642-4e65d59e963e // indirect k8s.io/kubelet v0.32.2 // indirect - kubevirt.io/controller-lifecycle-operator-sdk/api v0.0.0-20220329064328-f3cc58c6ed90 // indirect + kubevirt.io/controller-lifecycle-operator-sdk/api v0.2.4 // indirect sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.33.0 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/kube-storage-version-migrator v0.0.6-0.20230721195810-5c8923c5ff96 // indirect - sigs.k8s.io/kustomize/api v0.20.1 // indirect - sigs.k8s.io/kustomize/kyaml v0.20.1 // indirect + sigs.k8s.io/kustomize/api v0.21.0 // indirect + sigs.k8s.io/kustomize/kyaml v0.21.0 // indirect sigs.k8s.io/randfill v1.0.0 // indirect ) @@ -328,9 +337,6 @@ replace github.com/openshift/hypershift/api => ./api // orc currently lives in CAPO replace github.com/k-orc/openstack-resource-controller => sigs.k8s.io/cluster-api-provider-openstack/orc v0.0.0-20250113192833-e4f56a2b4f32 -// Fix K8s API v0.34+ fuzzer compatibility issue in cluster-api -replace sigs.k8s.io/cluster-api => github.com/csrwng/cluster-api v1.10.3-0.20251126211330-81cd715cb87e - // CVE-2025-30204 replace github.com/golang-jwt/jwt/v4 => github.com/golang-jwt/jwt/v4 v4.5.2 diff --git a/go.sum b/go.sum index fb54e9b5a14e..79ce9a12e888 100644 --- a/go.sum +++ b/go.sum @@ -43,16 +43,16 @@ github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1/go.mod h1:Ng3urmn6dYe8gnbCMoHHVl5APYz2txho3koEkV2o2HA= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.4.0 h1:E4MgwLBGeVB5f2MdcIVD3ELVAWpr+WD6MUe1i+tM/PA= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.4.0/go.mod h1:Y2b/1clN4zsAoUd/pgNAQHjLDnTis/6ROkUfyob6psM= -github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.3.1 h1:mrkDCdkMsD4l9wjFGhofFHFrV43Y3c53RSLKOCJ5+Ow= -github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.3.1/go.mod h1:hPv41DbqMmnxcGralanA/kVlfdH5jv3T4LxGku2E1BY= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0 h1:/g8S6wk65vfC6m3FIxJ+i5QDyN9JWwXI8Hb0Img10hU= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0/go.mod h1:gpl+q95AzZlKVI3xSoseF9QPrypk0hQqBiJYeB/cR/I= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 h1:nCYfgcSyHZXJI8J0IWE5MsCGlb2xp9fJiXyxWgmOFg4= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0/go.mod h1:ucUjca2JtSZboY8IoUqyQyuuXvwbMBVwFOm0vdQPNhA= github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 h1:jWQK1GI+LeGGUKBADtcH2rRqPxYB1Ljwms5gFA2LqrM= github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4/go.mod h1:8mwH4klAm9DUgR2EEHyEEAQlRDvLPyg5fQry3y+cDew= github.com/Azure/azure-service-operator/v2 v2.13.0 h1:24xDkuGOjSDKKkthECRo/I76slmlt3u0buYQ4rvX3pQ= github.com/Azure/azure-service-operator/v2 v2.13.0/go.mod h1:3xfZMZm4yjdcjr3lh1kWqP2dtvZS/nCy7wpNERYDatg= -github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= -github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/msi-dataplane v0.4.3 h1:dWPWzY4b54tLIR9T1Q014Xxd/1DxOsMIp6EjRFAJlQY= github.com/Azure/msi-dataplane v0.4.3/go.mod h1:yAfxdJyvcnvSDfSyOFV9qm4fReEQDl+nZLGeH2ZWSmw= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM= @@ -60,18 +60,18 @@ github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mo github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs= github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/IBM-Cloud/power-go-client v1.11.0 h1:4xlYXF2+S3s6Crb0D2+d5c1kb6gUE7eowMXLB7Q6cWY= -github.com/IBM-Cloud/power-go-client v1.11.0/go.mod h1:UDyXeIKEp6r7yWUXYu3r0ZnFSlNZ2YeQTHwM2Tmlgv0= -github.com/IBM/go-sdk-core/v5 v5.19.1 h1:sleVks1O4XjgF4YEGvyDh6PZbP6iZhlTPeDkQc8nWDs= -github.com/IBM/go-sdk-core/v5 v5.19.1/go.mod h1:Q3BYO6iDA2zweQPDGbNTtqft5tDcEpm6RTuqMlPcvbw= -github.com/IBM/ibm-cos-sdk-go v1.12.2 h1:71A4tDl8u6BZ548h71ecEe7fw5bBA7ECTVqYmeSQWQA= -github.com/IBM/ibm-cos-sdk-go v1.12.2/go.mod h1:ODYcmrmdpjo5hVguq9RbD6xmC8xb1XZMG7NefUbJNcc= -github.com/IBM/networking-go-sdk v0.51.4 h1:rkbR+gUkksLKjNYL5YEWEAMv3qddR0mUkxObDMa4l/s= -github.com/IBM/networking-go-sdk v0.51.4/go.mod h1:gjCFEp+UVP7FUlcq2C1RaoZAXFcD39CQdlUk7uVKko4= -github.com/IBM/platform-services-go-sdk v0.81.0 h1:jyVQYobEeC+l770YmKVtETFwPpD8DoapZfKY005f/jQ= -github.com/IBM/platform-services-go-sdk v0.81.0/go.mod h1:XOowH+JnIih3FA7uilLVM/9VH7XgCmJ4T/i6eZi7gkw= -github.com/IBM/vpc-go-sdk v0.68.0 h1:Zs65PWeWBG5IwafAJV0RdPVsi3hCjIkhFZkqr1sLt5g= -github.com/IBM/vpc-go-sdk v0.68.0/go.mod h1:VL7sy61ybg6tvA60SepoQx7TFe20m7JyNUt+se2tHP4= +github.com/IBM-Cloud/power-go-client v1.12.0 h1:tF9Mq5GLYHebpzQT6IYB89lIxEST1E9teuchjxSAaw0= +github.com/IBM-Cloud/power-go-client v1.12.0/go.mod h1:SpTK1ttW8bfMNUVQS8qOEuWn2KOkzaCLyzfze8MG1JE= +github.com/IBM/go-sdk-core/v5 v5.21.0 h1:DUnYhvC4SoC8T84rx5omnhY3+xcQg/Whyoa3mDPIMkk= +github.com/IBM/go-sdk-core/v5 v5.21.0/go.mod h1:Q3BYO6iDA2zweQPDGbNTtqft5tDcEpm6RTuqMlPcvbw= +github.com/IBM/ibm-cos-sdk-go v1.12.3 h1:kMIs1nfPY0UXAMcW6bq8O9WOd6KgqiDBnIMd0e/fMqA= +github.com/IBM/ibm-cos-sdk-go v1.12.3/go.mod h1:dt13UIqJRgfGIlSNlnf17JmAXlBXhfTgXLKV3as8ABk= +github.com/IBM/networking-go-sdk v0.51.11 h1:l+yMXcO9GDcb7JU9jl8riUOXjnHTvIKSLnXYFlYlKXo= +github.com/IBM/networking-go-sdk v0.51.11/go.mod h1:TAXWyBUk3C3R7aS1m84EfKdnDcBMZMAClwLfDj/SYZc= +github.com/IBM/platform-services-go-sdk v0.86.1 h1:ngBpaXvUF3gmLvbU1Z4lX1wowOSYgGoKBEBaR/urt30= +github.com/IBM/platform-services-go-sdk v0.86.1/go.mod h1:aGD045m6I8pfcB77wft8w2cHqWOJjcM3YSSV55BX0Js= +github.com/IBM/vpc-go-sdk v0.71.1 h1:SP5/uQs5JDb1QRvSJ1QC2BzE+BHEMq4jd2+JEcRuieE= +github.com/IBM/vpc-go-sdk v0.71.1/go.mod h1:K3vVlje72PYE3ZRt1iouE+jSIq+vCyYzT1HiFC06hUA= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= @@ -196,8 +196,8 @@ github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdn github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= -github.com/cenkalti/backoff/v5 v5.0.2 h1:rIfFVxEf1QsI7E1ZHfp/B4DF/6QBAUhmgkxc0H7Zss8= -github.com/cenkalti/backoff/v5 v5.0.2/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -222,8 +222,8 @@ github.com/cockroachdb/datadriven v1.0.2 h1:H9MtNqVoVhvd9nCBwOyDjUEdZCREqbIdCJD9 github.com/cockroachdb/datadriven v1.0.2/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= github.com/coredns/caddy v1.1.1 h1:2eYKZT7i6yxIfGP3qLJoJ7HAsDJqYB+X68g4NYjSrE0= github.com/coredns/caddy v1.1.1/go.mod h1:A6ntJQlAWuQfFlsd9hvigKbo2WS0VUs2l1e2F+BawD4= -github.com/coredns/corefile-migration v1.0.26 h1:xiiEkVB1Dwolb24pkeDUDBfygV9/XsOSq79yFCrhptY= -github.com/coredns/corefile-migration v1.0.26/go.mod h1:56DPqONc3njpVPsdilEnfijCwNGC3/kTJLl7i7SPavY= +github.com/coredns/corefile-migration v1.0.29 h1:g4cPYMXXDDs9uLE2gFYrJaPBuUAR07eEMGyh9JBE13w= +github.com/coredns/corefile-migration v1.0.29/go.mod h1:56DPqONc3njpVPsdilEnfijCwNGC3/kTJLl7i7SPavY= github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= @@ -238,8 +238,6 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= -github.com/csrwng/cluster-api v1.10.3-0.20251126211330-81cd715cb87e h1:NvT5z9IilmB4j5tVO+51I6JHXnY4yJTHKlt2sLr1fiY= -github.com/csrwng/cluster-api v1.10.3-0.20251126211330-81cd715cb87e/go.mod h1:68GJs286ZChsncp+TxYNj/vhy2NWokiPtH4+SA0afs0= github.com/cyphar/filepath-securejoin v0.6.0 h1:BtGB77njd6SVO6VztOHfPxKitJvd/VPT+OFBFMOi1Is= github.com/cyphar/filepath-securejoin v0.6.0/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1AX0a9kM5XL+NwKoYSc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -263,8 +261,8 @@ github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVo github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful v2.15.0+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= -github.com/emicklei/go-restful/v3 v3.12.2 h1:DhwDP0vY3k8ZzE0RunuJy8GhNpPL6zqLkDf9B/a0/xU= -github.com/emicklei/go-restful/v3 v3.12.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= +github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= @@ -289,8 +287,8 @@ github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= -github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= +github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY= +github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok= github.com/getkin/kin-openapi v0.76.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs= @@ -319,34 +317,62 @@ 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-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= -github.com/go-openapi/analysis v0.21.5 h1:3tHfEBh6Ia8eKc4M7khOGjPOAlWKJ10d877Cr9teujI= -github.com/go-openapi/analysis v0.21.5/go.mod h1:25YcZosX9Lwz2wBsrFrrsL8bmjjXdlyP6zsr2AMy29M= +github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU= +github.com/go-openapi/analysis v0.23.0/go.mod h1:9mz9ZWaSlV8TvjQHLl2mUW2PbZtemkE8yA5v22ohupo= github.com/go-openapi/errors v0.22.1 h1:kslMRRnK7NCb/CvR1q1VWuEQCEIsBGn5GgKD9e+HYhU= github.com/go-openapi/errors v0.22.1/go.mod h1:+n/5UdIqdVnLIJ6Q9Se8HNGUXYaY6CN8ImWzfi/Gzp0= 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.21.1 h1:whnzv/pNXtK2FbX/W9yJfRmE2gsmkfahjMKB0fZvcic= -github.com/go-openapi/jsonpointer v0.21.1/go.mod h1:50I1STOfbY1ycR8jGz8DaMeLCdXiI6aDteEdRNNzpdk= +github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4= +github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80= github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= github.com/go-openapi/jsonreference v0.19.5/go.mod h1:RdybgQwPxbL4UEjuAruzK1x3nE69AqPYEJeo/TWfEeg= github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= -github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= -github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= -github.com/go-openapi/loads v0.21.3 h1:8sSH2FIm/SnbDUGv572md4YqVMFne/a9Eubvcd3anew= -github.com/go-openapi/loads v0.21.3/go.mod h1:Y3aMR24iHbKHppOj91nQ/SHc0cuPbAr4ndY4a02xydc= -github.com/go-openapi/runtime v0.26.2 h1:elWyB9MacRzvIVgAZCBJmqTi7hBzU0hlKD4IvfX0Zl0= -github.com/go-openapi/runtime v0.26.2/go.mod h1:O034jyRZ557uJKzngbMDJXkcKJVzXJiymdSfgejrcRw= -github.com/go-openapi/spec v0.20.12 h1:cgSLbrsmziAP2iais+Vz7kSazwZ8rsUZd6TUzdDgkVI= -github.com/go-openapi/spec v0.20.12/go.mod h1:iSCgnBcwbMW9SfzJb8iYynXvcY6C/QFrI7otzF7xGM4= +github.com/go-openapi/jsonreference v0.21.4 h1:24qaE2y9bx/q3uRK/qN+TDwbok1NhbSmGjjySRCHtC8= +github.com/go-openapi/jsonreference v0.21.4/go.mod h1:rIENPTjDbLpzQmQWCj5kKj3ZlmEh+EFVbz3RTUh30/4= +github.com/go-openapi/loads v0.22.0 h1:ECPGd4jX1U6NApCGG1We+uEozOAvXvJSF4nnwHZ8Aco= +github.com/go-openapi/loads v0.22.0/go.mod h1:yLsaTCS92mnSAZX5WWoxszLj0u+Ojl+Zs5Stn1oF+rs= +github.com/go-openapi/runtime v0.28.0 h1:gpPPmWSNGo214l6n8hzdXYhPuJcGtziTOgUpvsFWGIQ= +github.com/go-openapi/runtime v0.28.0/go.mod h1:QN7OzcS+XuYmkQLw05akXk0jRH/eZ3kb18+1KwW9gyc= +github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= +github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c= github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4= 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.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZU= -github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0= -github.com/go-openapi/validate v0.22.4 h1:5v3jmMyIPKTR8Lv9syBAIRxG6lY0RqeBPB1LKEijzk8= -github.com/go-openapi/validate v0.22.4/go.mod h1:qm6O8ZIcPVdSY5219468Jv7kBdGvkiZLPOmqnqTUZ2A= +github.com/go-openapi/swag v0.25.4 h1:OyUPUFYDPDBMkqyxOTkqDYFnrhuhi9NR6QVUvIochMU= +github.com/go-openapi/swag v0.25.4/go.mod h1:zNfJ9WZABGHCFg2RnY0S4IOkAcVTzJ6z2Bi+Q4i6qFQ= +github.com/go-openapi/swag/cmdutils v0.25.4 h1:8rYhB5n6WawR192/BfUu2iVlxqVR9aRgGJP6WaBoW+4= +github.com/go-openapi/swag/cmdutils v0.25.4/go.mod h1:pdae/AFo6WxLl5L0rq87eRzVPm/XRHM3MoYgRMvG4A0= +github.com/go-openapi/swag/conv v0.25.4 h1:/Dd7p0LZXczgUcC/Ikm1+YqVzkEeCc9LnOWjfkpkfe4= +github.com/go-openapi/swag/conv v0.25.4/go.mod h1:3LXfie/lwoAv0NHoEuY1hjoFAYkvlqI/Bn5EQDD3PPU= +github.com/go-openapi/swag/fileutils v0.25.4 h1:2oI0XNW5y6UWZTC7vAxC8hmsK/tOkWXHJQH4lKjqw+Y= +github.com/go-openapi/swag/fileutils v0.25.4/go.mod h1:cdOT/PKbwcysVQ9Tpr0q20lQKH7MGhOEb6EwmHOirUk= +github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI= +github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag= +github.com/go-openapi/swag/jsonutils v0.25.4 h1:VSchfbGhD4UTf4vCdR2F4TLBdLwHyUDTd1/q4i+jGZA= +github.com/go-openapi/swag/jsonutils v0.25.4/go.mod h1:7OYGXpvVFPn4PpaSdPHJBtF0iGnbEaTk8AvBkoWnaAY= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4 h1:IACsSvBhiNJwlDix7wq39SS2Fh7lUOCJRmx/4SN4sVo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4/go.mod h1:Mt0Ost9l3cUzVv4OEZG+WSeoHwjWLnarzMePNDAOBiM= +github.com/go-openapi/swag/loading v0.25.4 h1:jN4MvLj0X6yhCDduRsxDDw1aHe+ZWoLjW+9ZQWIKn2s= +github.com/go-openapi/swag/loading v0.25.4/go.mod h1:rpUM1ZiyEP9+mNLIQUdMiD7dCETXvkkC30z53i+ftTE= +github.com/go-openapi/swag/mangling v0.25.4 h1:2b9kBJk9JvPgxr36V23FxJLdwBrpijI26Bx5JH4Hp48= +github.com/go-openapi/swag/mangling v0.25.4/go.mod h1:6dxwu6QyORHpIIApsdZgb6wBk/DPU15MdyYj/ikn0Hg= +github.com/go-openapi/swag/netutils v0.25.4 h1:Gqe6K71bGRb3ZQLusdI8p/y1KLgV4M/k+/HzVSqT8H0= +github.com/go-openapi/swag/netutils v0.25.4/go.mod h1:m2W8dtdaoX7oj9rEttLyTeEFFEBvnAx9qHd5nJEBzYg= +github.com/go-openapi/swag/stringutils v0.25.4 h1:O6dU1Rd8bej4HPA3/CLPciNBBDwZj9HiEpdVsb8B5A8= +github.com/go-openapi/swag/stringutils v0.25.4/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0= +github.com/go-openapi/swag/typeutils v0.25.4 h1:1/fbZOUN472NTc39zpa+YGHn3jzHWhv42wAJSN91wRw= +github.com/go-openapi/swag/typeutils v0.25.4/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE= +github.com/go-openapi/swag/yamlutils v0.25.4 h1:6jdaeSItEUb7ioS9lFoCZ65Cne1/RZtPBZ9A56h92Sw= +github.com/go-openapi/swag/yamlutils v0.25.4/go.mod h1:MNzq1ulQu+yd8Kl7wPOut/YHAAU/H6hL91fF+E2RFwc= +github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4= +github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg= +github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls= +github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= +github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= @@ -398,8 +424,8 @@ github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/cel-go v0.26.1 h1:iPbVVEdkhTX++hpe3lzSk7D3G3QSYqLGoHOcEio+UXQ= github.com/google/cel-go v0.26.1/go.mod h1:A9O8OU9rdvrK5MQyrqfIxo1a0u4g3sF8KB6PUIaryMM= -github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= -github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= +github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= +github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= 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= @@ -428,8 +454,8 @@ github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/googleapis/gnostic v0.5.1/go.mod h1:6U4PtQXGIEt/Z3h5MAT7FNofLnw9vXk2cUuW7uA/OeU= github.com/googleapis/gnostic v0.5.5/go.mod h1:7+EbHbldMins07ALC74bsA81Ovc97DwqyJO1AENw9kA= -github.com/gophercloud/gophercloud/v2 v2.4.0 h1:XhP5tVEH3ni66NSNK1+0iSO6kaGPH/6srtx6Cr+8eCg= -github.com/gophercloud/gophercloud/v2 v2.4.0/go.mod h1:uJWNpTgJPSl2gyzJqcU/pIAhFUWvIkp8eE8M15n9rs4= +github.com/gophercloud/gophercloud/v2 v2.10.0 h1:NRadC0aHNvy4iMoFXj5AFiPmut/Sj3hAPAo9B59VMGc= +github.com/gophercloud/gophercloud/v2 v2.10.0/go.mod h1:Ki/ILhYZr/5EPebrPL9Ej+tUg4lqx71/YH2JWVeU+Qk= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= @@ -446,8 +472,8 @@ github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.0 h1:FbSCl+KggFl+Ocym490i/E github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.0/go.mod h1:qOchhhIlmRcqk/O9uCo/puJlyo07YINaIqdZfZG3Jkc= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 h1:X5VWvz21y3gzm9Nw/kaUeku/1+uBhcekkmy4IkffJww= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1/go.mod h1:Zanoh4+gvIgluNqcfMVTJueD4wSS5hT7zTt4Mrutd90= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= @@ -474,7 +500,6 @@ github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I= github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung= @@ -516,8 +541,6 @@ github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4= -github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= github.com/maruel/natural v1.1.1 h1:Hja7XhhmvEFhcByqDoHz9QZbkWey+COd9xWfCfn1ioo= github.com/maruel/natural v1.1.1/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= @@ -546,8 +569,8 @@ github.com/moby/spdystream v0.5.0 h1:7r0J1Si3QO/kjRitvSLVVFUjxMEb/YLj6S9FF62JBCU github.com/moby/spdystream v0.5.0/go.mod h1:xBAYlnt/ay+11ShkdFKNAG7LsyK/tmNBVvVOwrfMgdI= github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs= github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs= -github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= -github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -597,6 +620,8 @@ github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJw github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/opencontainers/selinux v1.13.0 h1:Zza88GWezyT7RLql12URvoxsbLfjFx988+LGaWfbL84= github.com/opencontainers/selinux v1.13.0/go.mod h1:XxWTed+A/s5NNq4GmYScVy+9jzXhGBVEOAyucdRUY8s= +github.com/openshift-online/ocm-common v0.0.31 h1:csxB4UQAUhwhDOVBmOzUKgtemuwV9rhCkzMoeFX8zCQ= +github.com/openshift-online/ocm-common v0.0.31/go.mod h1:VEkuZp9aqbXtetZ5ycND6QpvhykvTuBF3oPsVM1X3vI= github.com/openshift/api v0.0.0-20260304122341-cf5d8996109f h1:M8y0oBq/KRkuSNFlUMQRAn2MrXJh1mzTCFgbLpPWQbM= github.com/openshift/api v0.0.0-20260304122341-cf5d8996109f/go.mod h1:d5uzF0YN2nQQFA0jIEWzzOZ+edmo6wzlGLvx5Fhz4uY= github.com/openshift/aws-karpenter-provider-aws v0.0.0-20260207025257-2e871ee4d207 h1:gLln7Mf87FFVV99cxf4Ai+LQohBopKIJ3OtXGz3Z2v4= @@ -605,8 +630,8 @@ github.com/openshift/client-go v0.0.0-20251202151200-fb4471581cf8 h1:97rgISdT4IO github.com/openshift/client-go v0.0.0-20251202151200-fb4471581cf8/go.mod h1:WVJnsrbSO1J8x8KceOmv1d5CpoN34Uzsaz1O4MIOKJI= github.com/openshift/cloud-credential-operator v0.0.0-20250225003505-216fd1a30ec3 h1:cr5nU1+O8sEvZHpAAk1mTTGu3NMbgj0dC2cFxFjwmzw= github.com/openshift/cloud-credential-operator v0.0.0-20250225003505-216fd1a30ec3/go.mod h1:WHi2cToOBZyHQea0Yq3qVnOQRl6OMTGBPJMi0c4/GS8= -github.com/openshift/cluster-api-provider-agent/api v0.0.0-20250624174747-899af6573f5f h1:bV9TkOD4E3lJwlb9z00VNBhjjVeuSOU8FjckL451Fxg= -github.com/openshift/cluster-api-provider-agent/api v0.0.0-20250624174747-899af6573f5f/go.mod h1:OzR0JFhrNsvrbXEY1BiwLzzBXQGp45/8EQMKplcj1kw= +github.com/openshift/cluster-api-provider-agent/api v0.0.0-20260120122324-898e638ec7d1 h1:TIHSRRDDxhbsziSrQcXORPyGu66yr1Fk8vLTCo7wY+Y= +github.com/openshift/cluster-api-provider-agent/api v0.0.0-20260120122324-898e638ec7d1/go.mod h1:/hEmyZ903PeqntDSxLgZcje96/2lC3PmvsnUABQpR8Q= github.com/openshift/cluster-autoscaler-operator v0.0.1-0.20241204142113-43631b045675 h1:hPFyXtaR42wqKKGMVP4G7M2vmp5iBxBqKetMguh4Td0= github.com/openshift/cluster-autoscaler-operator v0.0.1-0.20241204142113-43631b045675/go.mod h1:0tGCwMCgKq7KhJWDGr6Tsqqb6Sk3epz/b6tfFDFK1Ug= github.com/openshift/cluster-node-tuning-operator v0.0.0-20250225115807-f166846b7256 h1:YLqKXRH7DTukM1sxLOi++uUe7R2m0ivK7yqf0X6emok= @@ -664,8 +689,8 @@ github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxza github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= -github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= -github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= +github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws= +github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= @@ -681,8 +706,8 @@ github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/samber/lo v1.51.0 h1:kysRYLbHy/MB7kQZf5DSN50JHmMsNEdeY24VzJFu7wI= github.com/samber/lo v1.51.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0= -github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8= -github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= +github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= @@ -769,8 +794,8 @@ go.etcd.io/gofail v0.2.0 h1:p19drv16FKK345a09a1iubchlw/vmRuksmRzgBIGjcA= go.etcd.io/gofail v0.2.0/go.mod h1:nL3ILMGfkXTekKI3clMBNazKnjUZjYLKmBHzsVAnC1o= go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ= go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo= -go.mongodb.org/mongo-driver v1.17.2 h1:gvZyk8352qSfzyZ2UMWcpDpMSGEr1eqE4T793SqyhzM= -go.mongodb.org/mongo-driver v1.17.2/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= +go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ= +go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 h1:YH4g8lQroajqUwWbq/tr2QX1JFmEXaDLgG+ew9bLMWo= @@ -779,10 +804,10 @@ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6h go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms= go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 h1:Ahq7pZmv87yiyn3jeFz/LekZmPLLdKejuO3NcK9MssM= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0/go.mod h1:MJTqhM0im3mRLw1i8uGHnCvUEeS7VwRyxlLC78PA18M= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 h1:EtFWSnwW9hGObjkIdmlnWSydO+Qs8OwzfzXLUPg4xOc= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0/go.mod h1:QjUEoiGCPkvFZ/MjK6ZZfNOS6mfVEVKYE99dFhuN2LI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 h1:f0cb2XPmrqn4XMy9PNliTgRKJgS5WcL/u0/WRYGz4t0= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0/go.mod h1:vnakAaFckOMiMtOIhFI2MNH4FYrZzXCYxmb1LlhoGz8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.39.0 h1:in9O8ESIOlwJAEGTkkf34DesGRAc/Pn8qJ7k3r/42LM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.39.0/go.mod h1:Rp0EXBm5tfnv0WL+ARyO/PHBEaEAT8UUHQ6AGJcSq6c= go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g= go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc= go.opentelemetry.io/otel/sdk v1.40.0 h1:KHW/jUzgo6wsPh9At46+h4upjtccTmuZCFAc9OJ71f8= @@ -791,8 +816,8 @@ go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4A go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg= go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw= go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA= -go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4= -go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE= +go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A= +go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= @@ -817,8 +842,8 @@ golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDf golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o= -golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= +golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 h1:fQsdNF2N+/YewlRZiricy4P1iimyPKZ/xwniHj8Q2a0= +golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93/go.mod h1:EPRbTFwzwjXj9NpYyyrvenVh9Y+GFeEvMNh7Xuz7xgU= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= @@ -1000,8 +1025,8 @@ gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4= -gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= +gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= +gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= @@ -1037,19 +1062,19 @@ k8s.io/apiserver v0.34.3 h1:uGH1qpDvSiYG4HVFqc6A3L4CKiX+aBWDrrsxHYK0Bdo= k8s.io/apiserver v0.34.3/go.mod h1:QPnnahMO5C2m3lm6fPW3+JmyQbvHZQ8uudAu/493P2w= k8s.io/autoscaler/vertical-pod-autoscaler v1.3.0 h1:oVv4QrTPKM7vWyQRRzCDgDgi00NWo4Rjle5/nujP/dI= k8s.io/autoscaler/vertical-pod-autoscaler v1.3.0/go.mod h1:W4k7qGP8A9Xqp+UK+lM49AfsWkAdXzE80F/s8kxwWVI= -k8s.io/cli-runtime v0.34.2 h1:cct1GEuWc3IyVT8MSCoIWzRGw9HJ/C5rgP32H60H6aE= -k8s.io/cli-runtime v0.34.2/go.mod h1:X13tsrYexYUCIq8MarCBy8lrm0k0weFPTpcaNo7lms4= +k8s.io/cli-runtime v0.34.3 h1:YRyMhiwX0dT9lmG0AtZDaeG33Nkxgt9OlCTZhRXj9SI= +k8s.io/cli-runtime v0.34.3/go.mod h1:GVwL1L5uaGEgM7eGeKjaTG2j3u134JgG4dAI6jQKhMc= k8s.io/client-go v0.34.3 h1:wtYtpzy/OPNYf7WyNBTj3iUA0XaBHVqhv4Iv3tbrF5A= k8s.io/client-go v0.34.3/go.mod h1:OxxeYagaP9Kdf78UrKLa3YZixMCfP6bgPwPwNBQBzpM= k8s.io/cloud-provider v0.34.1 h1:FS+4C1vq9pIngd/5LR5Jha1sEbn+fo0HJitgZmUyBNc= k8s.io/cloud-provider v0.34.1/go.mod h1:ghyQYfQIWZAXKNS+TEgEiQ8wPuhzIVt3wFO6rKqS/rQ= -k8s.io/cluster-bootstrap v0.32.3 h1:AqIpsUhB6MUeaAsl1WvaUw54AHRd2hfZrESlKChtd8s= -k8s.io/cluster-bootstrap v0.32.3/go.mod h1:CHbBwgOb6liDV6JFUTkx5t85T2xidy0sChBDoyYw344= +k8s.io/cluster-bootstrap v0.34.3 h1:mLguWldCwTk0GvoWHg6tf6qgpVMDLCSvvtWUoL13RXg= +k8s.io/cluster-bootstrap v0.34.3/go.mod h1:50AJCDVJ8HMmw9W2EN0cHSbTsI9GYtyOM+eyxjVlAwg= k8s.io/code-generator v0.23.3/go.mod h1:S0Q1JVA+kSzTI1oUvbKAxZY/DYbA/ZUb4Uknog12ETk= k8s.io/component-base v0.34.3 h1:zsEgw6ELqK0XncCQomgO9DpUIzlrYuZYA0Cgo+JWpVk= k8s.io/component-base v0.34.3/go.mod h1:5iIlD8wPfWE/xSHTRfbjuvUul2WZbI2nOUK65XL0E/c= -k8s.io/component-helpers v0.34.2 h1:RIUGDdU+QFzeVKLZ9f05sXTNAtJrRJ3bnbMLrogCrvM= -k8s.io/component-helpers v0.34.2/go.mod h1:pLi+GByuRTeFjjcezln8gHL7LcT6HImkwVQ3A2SQaEE= +k8s.io/component-helpers v0.34.3 h1:Iws1GQfM89Lxo7IZITGmVdFOW0Bmyd7SVwwIu1/CCkE= +k8s.io/component-helpers v0.34.3/go.mod h1:S8HjjMTrUDVMVPo2EdNYRtQx9uIEIueQYdPMOe9UxJs= k8s.io/csi-translation-lib v0.34.1 h1:8+QMIWBwPGFsqWw9eAvimA2GaHXGgLLYT61I1NzDnXw= k8s.io/csi-translation-lib v0.34.1/go.mod h1:QXytPJ1KzYQaiMgVm82ANG+RGAUf276m8l9gFT+R6Xg= k8s.io/gengo v0.0.0-20210813121822-485abfe95c7c/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= @@ -1068,12 +1093,12 @@ k8s.io/kube-aggregator v0.34.2 h1:Nn0Vksj67WHBL2x7bJ6vuxL44RbMTK6uRtXX+3vMVJk= k8s.io/kube-aggregator v0.34.2/go.mod h1:/tp4cc/1p2AvICsS4mjjSJakdrbhcGbRmj0mdHTdR2Q= k8s.io/kube-openapi v0.0.0-20211115234752-e816edb12b65/go.mod h1:sX9MT8g7NVZM5lVL/j8QyCCJe8YSMW30QvGZWaCIDIk= k8s.io/kube-openapi v0.0.0-20220124234850-424119656bbf/go.mod h1:sX9MT8g7NVZM5lVL/j8QyCCJe8YSMW30QvGZWaCIDIk= -k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b h1:MloQ9/bdJyIu9lb1PzujOPolHyvO06MXG5TUIj2mNAA= -k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b/go.mod h1:UZ2yyWbFTpuhSbFhv24aGNOdoRdJZgsIObGBUaYVsts= +k8s.io/kube-openapi v0.0.0-20251125145642-4e65d59e963e h1:iW9ChlU0cU16w8MpVYjXk12dqQ4BPFBEgif+ap7/hqQ= +k8s.io/kube-openapi v0.0.0-20251125145642-4e65d59e963e/go.mod h1:kdmbQkyfwUagLfXIad1y2TdrjPFWp2Q89B3qkRwf/pQ= k8s.io/kube-scheduler v0.34.2 h1:TtLcaXeIpkqgzMr2ch7Ap8Cluq4M182XUDRlnOPDdoc= k8s.io/kube-scheduler v0.34.2/go.mod h1:PTn4QYiSet8/00VQ2qGO/HWdo5iNJlVRCXz/7R3Ut5I= -k8s.io/kubectl v0.34.2 h1:+fWGrVlDONMUmmQLDaGkQ9i91oszjjRAa94cr37hzqA= -k8s.io/kubectl v0.34.2/go.mod h1:X2KTOdtZZNrTWmUD4oHApJ836pevSl+zvC5sI6oO2YQ= +k8s.io/kubectl v0.34.3 h1:vpM6//153gh5gvsYHXWHVJ4l4xmN5QFwTSmlfd8icm8= +k8s.io/kubectl v0.34.3/go.mod h1:zZQHtIZoUqTP1bAnPzq/3W1jfc0NeOeunFgcswrfg1c= k8s.io/kubelet v0.32.2 h1:WFTSYdt3BB1aTApDuKNI16x/4MYqqX8WBBBBh3KupDg= k8s.io/kubelet v0.32.2/go.mod h1:cC1ms5RS+lu0ckVr6AviCQXHLSPKEBC3D5oaCBdTGkI= k8s.io/pod-security-admission v0.34.2 h1:r77cRPmc2kEPtX2DKh5thmb8zmcFCZhAHUHvVYrjFvA= @@ -1086,22 +1111,24 @@ kubevirt.io/api v1.7.1 h1:7MB7TG2FIJmL4CpZ1IBiy1CRR4YDrHAwbXUlE3+rCy8= kubevirt.io/api v1.7.1/go.mod h1:PumvcKaNhXxLLoDPQtjwFKkooTr910m3ebSlxUb6b10= kubevirt.io/containerized-data-importer-api v1.64.0 h1:yBLY6qEogUp8F+XSJvabIkx9uEEDeToYDfRr0mbUxJc= kubevirt.io/containerized-data-importer-api v1.64.0/go.mod h1:VGp35wxpLXU18b7cnEpmcThI3AjcZUSfg/Zfql44U4o= -kubevirt.io/controller-lifecycle-operator-sdk/api v0.0.0-20220329064328-f3cc58c6ed90 h1:QMrd0nKP0BGbnxTqakhDZAUhGKxPiPiN5gSDqKUmGGc= -kubevirt.io/controller-lifecycle-operator-sdk/api v0.0.0-20220329064328-f3cc58c6ed90/go.mod h1:018lASpFYBsYN6XwmA2TIrPCx6e0gviTd/ZNtSitKgc= +kubevirt.io/controller-lifecycle-operator-sdk/api v0.2.4 h1:fZYvD3/Vnitfkx6IJxjLAk8ugnZQ7CXVYcRfkSKmuZY= +kubevirt.io/controller-lifecycle-operator-sdk/api v0.2.4/go.mod h1:018lASpFYBsYN6XwmA2TIrPCx6e0gviTd/ZNtSitKgc= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.33.0 h1:qPrZsv1cwQiFeieFlRqT627fVZ+tyfou/+S5S0H5ua0= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.33.0/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw= -sigs.k8s.io/cluster-api-provider-aws/v2 v2.8.2-0.20250820205306-645f38e4c152 h1:Hs6qmsPSdKTZYbqjPUBtE1L4m8Q8OcGmpxdh8oth+/0= -sigs.k8s.io/cluster-api-provider-aws/v2 v2.8.2-0.20250820205306-645f38e4c152/go.mod h1:wdqD8SRkgbIAoj0L2geEItos4X4xmCr8yQpEOqIwLp4= -sigs.k8s.io/cluster-api-provider-azure v1.21.0 h1:8SYwQX4ANgy2CAa2NEk41mqBZrmyAH03Xlk214qvxCA= -sigs.k8s.io/cluster-api-provider-azure v1.21.0/go.mod h1:NJMrRzRf/Ua5Uhm9qmuK4M/4Jl/f74jBpkgPqJN0vQQ= -sigs.k8s.io/cluster-api-provider-gcp v1.10.0 h1:gngUxo9bz8l+otpdw9v3ULEXwAvijyqiBx2v8HSoRwA= -sigs.k8s.io/cluster-api-provider-gcp v1.10.0/go.mod h1:VkmOqBgi3Jj+VR+YTZEHAlMMmyjqcKl4lXhpLsYnYok= -sigs.k8s.io/cluster-api-provider-ibmcloud v0.11.0 h1:aunR3nnDzQ5x1Qj1hJbR3Xq4SCZth4XyTWAyUCN46kE= -sigs.k8s.io/cluster-api-provider-ibmcloud v0.11.0/go.mod h1:9yPLATyiqLx4crMzbX11YQU+GuR5txjtiCt8z9sxDfM= -sigs.k8s.io/cluster-api-provider-kubevirt v0.1.9 h1:hQO7Y5GP7FMnH6Aono9WVE90I3vRLBxw/48iKHerjtg= -sigs.k8s.io/cluster-api-provider-kubevirt v0.1.9/go.mod h1:RlF7CASVT4vaBRLu45Y2dprAnEPoDGvMaImXz13Ntks= -sigs.k8s.io/cluster-api-provider-openstack v0.12.1 h1:IK8GRmQKTwgft6PwaLC4r69O5hV7ykr4l7eJ8pQ3EIU= -sigs.k8s.io/cluster-api-provider-openstack v0.12.1/go.mod h1:lm2AXy1bfJEVKU4RfxwPdJgPbJDNiUAfva+IIf8Gqzo= +sigs.k8s.io/cluster-api v1.11.5 h1:mKQAfB8+6l2uxtEvQ6Z5EIcTObdPNs3TL4DcJScchGo= +sigs.k8s.io/cluster-api v1.11.5/go.mod h1:n0d6BAo8s9+KRap8Wv/IllfmwnSN5XFTWNJuq2gKNlg= +sigs.k8s.io/cluster-api-provider-aws/v2 v2.10.0 h1:E28NopVRAtnenHsfh54VwS2uEpGAkW0bv6Y19bqAwCg= +sigs.k8s.io/cluster-api-provider-aws/v2 v2.10.0/go.mod h1:cuuFljMXGat8qW+lvSdYEWReR0DSauv19/rh+bpobl4= +sigs.k8s.io/cluster-api-provider-azure v1.22.0 h1:TL+QXMVCeY2zR41PSlH2jyhQivDXXPGT8wqG4LX92ss= +sigs.k8s.io/cluster-api-provider-azure v1.22.0/go.mod h1:ivn6SfniydSCKi+pzGUaNlH1rFcavqRKw0iy1g9l7Nc= +sigs.k8s.io/cluster-api-provider-gcp v1.11.0 h1:I3sroBY64nAGCzt3aerpGMM76WU3UyjP429kEC0vJ5Y= +sigs.k8s.io/cluster-api-provider-gcp v1.11.0/go.mod h1:vUbA5VeL+YRoxzNQ/vBzRcoHcFMMkWwgcX8DdG3Xcuc= +sigs.k8s.io/cluster-api-provider-ibmcloud v0.12.0 h1:0+jfWLg+UmnGOdHZ9SrEpnUJgQPyyXpcjXGdkN5E5M4= +sigs.k8s.io/cluster-api-provider-ibmcloud v0.12.0/go.mod h1:OENB/2pEx2IgYAovlV7qHvOJYyBoKc94TxNqnjjyWYs= +sigs.k8s.io/cluster-api-provider-kubevirt v0.11.1 h1:6He4EkFNVsEpYsObVRh1agt1/CxhqdqsOvEvyjRWWzk= +sigs.k8s.io/cluster-api-provider-kubevirt v0.11.1/go.mod h1:so1WRGRRsxT4lqS0htpUqXrXLy0guBklh9UPVxoilLY= +sigs.k8s.io/cluster-api-provider-openstack v0.13.3 h1:qBPgWG1E3wiiK8+VR5a3jnKGTyDPo6ZbXruTLOXw/3w= +sigs.k8s.io/cluster-api-provider-openstack v0.13.3/go.mod h1:McuqrgmgsbK4yaC1HKqJ7dxKnOERmXQedUUL15sqelQ= sigs.k8s.io/cluster-api-provider-openstack/orc v0.0.0-20250113192833-e4f56a2b4f32 h1:AkFSgi+dAnPLtg+SXjtCf3rDzjI/mskDiJ1PWHZoRno= sigs.k8s.io/cluster-api-provider-openstack/orc v0.0.0-20250113192833-e4f56a2b4f32/go.mod h1:hQOMZZjzuAt9pdLaE/tj5ByDTVNBkqNaP10ijnqNZfU= sigs.k8s.io/controller-runtime v0.19.7 h1:DLABZfMr20A+AwCZOHhcbcu+TqBXnJZaVBri9K3EO48= @@ -1111,18 +1138,18 @@ sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5E sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/kube-storage-version-migrator v0.0.6-0.20230721195810-5c8923c5ff96 h1:PFWFSkpArPNJxFX4ZKWAk9NSeRoZaXschn+ULa4xVek= sigs.k8s.io/kube-storage-version-migrator v0.0.6-0.20230721195810-5c8923c5ff96/go.mod h1:EOBQyBowOUsd7U4CJnMHNE0ri+zCXyouGdLwC/jZU+I= -sigs.k8s.io/kustomize/api v0.20.1 h1:iWP1Ydh3/lmldBnH/S5RXgT98vWYMaTUL1ADcr+Sv7I= -sigs.k8s.io/kustomize/api v0.20.1/go.mod h1:t6hUFxO+Ph0VxIk1sKp1WS0dOjbPCtLJ4p8aADLwqjM= -sigs.k8s.io/kustomize/kyaml v0.20.1 h1:PCMnA2mrVbRP3NIB6v9kYCAc38uvFLVs8j/CD567A78= -sigs.k8s.io/kustomize/kyaml v0.20.1/go.mod h1:0EmkQHRUsJxY8Ug9Niig1pUMSCGHxQ5RklbpV/Ri6po= +sigs.k8s.io/kustomize/api v0.21.0 h1:I7nry5p8iDJbuRdYS7ez8MUvw7XVNPcIP5GkzzuXIIQ= +sigs.k8s.io/kustomize/api v0.21.0/go.mod h1:XGVQuR5n2pXKWbzXHweZU683pALGw/AMVO4zU4iS8SE= +sigs.k8s.io/kustomize/kyaml v0.21.0 h1:7mQAf3dUwf0wBerWJd8rXhVcnkk5Tvn/q91cGkaP6HQ= +sigs.k8s.io/kustomize/kyaml v0.21.0/go.mod h1:hmxADesM3yUN2vbA5z1/YTBnzLJ1dajdqpQonwBL1FQ= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= sigs.k8s.io/secrets-store-csi-driver v1.4.8 h1:YmL0lx9HMYqeZCnLyOZRMuGAZXmP/e42UGCCAnMKjgE= sigs.k8s.io/secrets-store-csi-driver v1.4.8/go.mod h1:IawZyjzh3xGt6hHdckJUf3ls04O0zG5H550PEZz/beo= sigs.k8s.io/structured-merge-diff/v4 v4.0.2/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.2.1/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= -sigs.k8s.io/structured-merge-diff/v6 v6.3.0 h1:jTijUJbW353oVOd9oTlifJqOGEkUw2jB/fXCbTiQEco= -sigs.k8s.io/structured-merge-diff/v6 v6.3.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/structured-merge-diff/v6 v6.3.1 h1:JrhdFMqOd/+3ByqlP2I45kTOZmTRLBUm5pvRjeheg7E= +sigs.k8s.io/structured-merge-diff/v6 v6.3.1/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= diff --git a/hypershift-operator/controllers/hostedcluster/hostedcluster_controller.go b/hypershift-operator/controllers/hostedcluster/hostedcluster_controller.go index 3900d4f44b99..6846769ffe8b 100644 --- a/hypershift-operator/controllers/hostedcluster/hostedcluster_controller.go +++ b/hypershift-operator/controllers/hostedcluster/hostedcluster_controller.go @@ -54,7 +54,6 @@ import ( "github.com/openshift/hypershift/support/api" "github.com/openshift/hypershift/support/awsapi" "github.com/openshift/hypershift/support/azureutil" - "github.com/openshift/hypershift/support/backwardcompat" "github.com/openshift/hypershift/support/capabilities" "github.com/openshift/hypershift/support/certs" "github.com/openshift/hypershift/support/config" @@ -97,7 +96,7 @@ import ( "k8s.io/utils/clock" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/builder" "sigs.k8s.io/controller-runtime/pkg/client" @@ -1805,7 +1804,6 @@ func (r *HostedClusterReconciler) reconcile(ctx context.Context, req ctrl.Reques if err != nil { return ctrl.Result{}, err } - if err := r.reconcileAWSSubnets(ctx, createOrUpdate, infraCR, req.Namespace, req.Name, controlPlaneNamespace.Name); err != nil { return ctrl.Result{}, err } @@ -1827,6 +1825,17 @@ func (r *HostedClusterReconciler) reconcile(ctx context.Context, req ctrl.Reques if err != nil { return ctrl.Result{}, fmt.Errorf("failed to reconcile capi cluster: %w", err) } + // Patch InfrastructureProvisioned on the CAPI Cluster status once infrastructure + // is confirmed ready. This is done via a dedicated Status patch (not in + // reconcileCAPICluster) to keep spec and status concerns separate. + // Gate on HCP.InfrastructureReady to match CAPI 1.10 timing where CAPA set + // AWSCluster.status.ready only after infrastructure was verified, preventing + // premature control plane convergence that breaks e2e timing assumptions. + if hcp != nil && meta.IsStatusConditionTrue(hcp.Status.Conditions, string(hyperv1.InfrastructureReady)) { + if err := patchInfrastructureInitializationProvisioned(ctx, r.Client, capiCluster); err != nil { + return ctrl.Result{}, fmt.Errorf("failed to patch CAPI cluster InfrastructureProvisioned: %w", err) + } + } } // Reconcile the monitoring dashboard if configured @@ -2530,18 +2539,6 @@ func (r *HostedClusterReconciler) reconcileCAPIManager(cpContext controlplanecom imageOverride := hcluster.Annotations[hyperv1.ClusterAPIManagerImage] - if imageOverride == "" { - pullSecret, err := hyperutil.GetPullSecretBytes(cpContext, r.Client, hcluster) - if err != nil { - return err - } - - imageOverride, err = backwardcompat.GetBackwardCompatibleCAPIImage(cpContext, pullSecret, r.RegistryProvider.GetReleaseProvider(), releaseVersion, ImageStreamCAPI) - if err != nil { - return err - } - } - capiManager := capimanagerv2.NewComponent(imageOverride) if err := capiManager.Reconcile(cpContext); err != nil { return fmt.Errorf("failed to reconcile capi manager component: %w", err) @@ -2898,11 +2895,36 @@ func reconcilecontrolPlaneOperatorIngressOperatorRoleBinding(binding *rbacv1.Rol return nil } +// patchInfrastructureInitializationProvisioned sets InfrastructureProvisioned=True on +// the CAPI Cluster status via a dedicated Status patch. For externally managed infra +// (ManagedByAnnotation="external"), CAPI skips InfrastructureCluster reconciliation so +// it cannot determine infra readiness itself. HyperShift fulfills this part of the CAPI +// contract here, gated on HCP.InfrastructureReady=True. +func patchInfrastructureInitializationProvisioned(ctx context.Context, c client.Client, capiCluster *capiv1.Cluster) error { + if ptr.Deref(capiCluster.Status.Initialization.InfrastructureProvisioned, false) { + return nil + } + original := capiCluster.DeepCopy() + capiCluster.Status.Initialization.InfrastructureProvisioned = ptr.To(true) + return c.Status().Patch(ctx, capiCluster, client.MergeFrom(original)) +} + func reconcileCAPICluster(cluster *capiv1.Cluster, hcluster *hyperv1.HostedCluster, hcp *hyperv1.HostedControlPlane, infraCR client.Object) error { + // Note: InfrastructureProvisioned is NOT set here. It is managed by + // patchInfrastructureInitializationProvisioned which does a dedicated Status + // patch gated on HCP.InfrastructureReady=True. This preserves CAPI 1.10 + // timing semantics and keeps this function focused on spec-only changes. + // Note: ControlPlaneInitialized is intentionally NOT set here. CAPI's cluster + // controller will set it naturally when HCP.Status.Initialized=True (via v1beta1 + // contract reading status.initialized). This preserves CAPI 1.10 timing where + // machines were only created after the guest cluster bootstrap RBAC was set up by + // HCCO. Setting it unconditionally caused machines to boot before HCCO had finished + // configuring the guest cluster, resulting in bootstrap authentication failures. + // We only create this resource once and then let CAPI own it if !cluster.CreationTimestamp.IsZero() { // make sure cluster is not paused. - cluster.Spec.Paused = false + cluster.Spec.Paused = ptr.To(false) return nil } infraCRGVK, err := apiutil.GVKForObject(infraCR, api.Scheme) @@ -2915,17 +2937,15 @@ func reconcileCAPICluster(cluster *capiv1.Cluster, hcluster *hyperv1.HostedClust } cluster.Spec = capiv1.ClusterSpec{ ControlPlaneEndpoint: capiv1.APIEndpoint{}, - ControlPlaneRef: &corev1.ObjectReference{ - APIVersion: "hypershift.openshift.io/v1beta1", - Kind: "HostedControlPlane", - Namespace: hcp.Namespace, - Name: hcp.Name, + ControlPlaneRef: capiv1.ContractVersionedObjectReference{ + APIGroup: "hypershift.openshift.io", + Kind: "HostedControlPlane", + Name: hcp.Name, }, - InfrastructureRef: &corev1.ObjectReference{ - APIVersion: infraCRGVK.GroupVersion().String(), - Kind: infraCRGVK.Kind, - Namespace: infraCR.GetNamespace(), - Name: infraCR.GetName(), + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + APIGroup: infraCRGVK.Group, + Kind: infraCRGVK.Kind, + Name: infraCR.GetName(), }, } @@ -2947,8 +2967,8 @@ func pauseCAPICluster(ctx context.Context, c client.Client, hc *hyperv1.HostedCl return nil } - if capiCluster.Spec.Paused != paused { - capiCluster.Spec.Paused = paused + if ptr.Deref(capiCluster.Spec.Paused, false) != paused { + capiCluster.Spec.Paused = ptr.To(paused) if err := c.Update(ctx, capiCluster); err != nil { return fmt.Errorf("failed to update CAPI Cluster: %w", err) } @@ -2961,7 +2981,7 @@ func reconcileCAPIManagerClusterRole(role *rbacv1.ClusterRole) error { { APIGroups: []string{"apiextensions.k8s.io"}, Resources: []string{"customresourcedefinitions"}, - Verbs: []string{"get", "list", "watch"}, + Verbs: []string{"get", "list", "patch", "watch"}, }, } return nil @@ -2980,6 +3000,11 @@ func reconcileCAPIManagerClusterRoleBinding(binding *rbacv1.ClusterRoleBinding, Name: sa.Name, Namespace: sa.Namespace, }, + { + Kind: "ServiceAccount", + Name: "capi-provider", + Namespace: sa.Namespace, + }, } return nil } diff --git a/hypershift-operator/controllers/hostedcluster/hostedcluster_controller_test.go b/hypershift-operator/controllers/hostedcluster/hostedcluster_controller_test.go index 56020d185c0d..9943ed5d7b68 100644 --- a/hypershift-operator/controllers/hostedcluster/hostedcluster_controller_test.go +++ b/hypershift-operator/controllers/hostedcluster/hostedcluster_controller_test.go @@ -61,7 +61,7 @@ import ( capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" capibmv1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" - "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" crclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -1097,12 +1097,12 @@ func TestServicePublishingStrategyByType(t *testing.T) { func TestReconcileCAPICluster(t *testing.T) { testCases := []struct { name string - capiCluster *v1beta1.Cluster + capiCluster *capiv1.Cluster hostedCluster *hyperv1.HostedCluster hostedControlPlane *hyperv1.HostedControlPlane infraCR crclient.Object - expectedCAPICluster *v1beta1.Cluster + expectedCAPICluster *capiv1.Cluster }{ { name: "IBM Cloud cluster", @@ -1137,7 +1137,7 @@ func TestReconcileCAPICluster(t *testing.T) { Namespace: "master-cluster1", }, }, - expectedCAPICluster: &v1beta1.Cluster{ + expectedCAPICluster: &capiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ hyperutil.HostedClusterAnnotation: "master/cluster1", @@ -1145,21 +1145,22 @@ func TestReconcileCAPICluster(t *testing.T) { Namespace: "master-cluster1", Name: "cluster1", }, - Spec: v1beta1.ClusterSpec{ - ControlPlaneEndpoint: v1beta1.APIEndpoint{}, - ControlPlaneRef: &corev1.ObjectReference{ - APIVersion: "hypershift.openshift.io/v1beta1", - Kind: "HostedControlPlane", - Namespace: "master-cluster1", - Name: "cluster1", + Spec: capiv1.ClusterSpec{ + ControlPlaneEndpoint: capiv1.APIEndpoint{}, + ControlPlaneRef: capiv1.ContractVersionedObjectReference{ + APIGroup: "hypershift.openshift.io", + Kind: "HostedControlPlane", + Name: "cluster1", }, - InfrastructureRef: &corev1.ObjectReference{ - APIVersion: capibmv1.GroupVersion.String(), - Kind: "IBMVPCCluster", - Namespace: "master-cluster1", - Name: "cluster1", + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + APIGroup: capibmv1.GroupVersion.Group, + Kind: "IBMVPCCluster", + Name: "cluster1", }, }, + Status: capiv1.ClusterStatus{ + Initialization: capiv1.ClusterInitializationStatus{}, + }, }, }, { @@ -1195,7 +1196,7 @@ func TestReconcileCAPICluster(t *testing.T) { Namespace: "master-cluster1", }, }, - expectedCAPICluster: &v1beta1.Cluster{ + expectedCAPICluster: &capiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ hyperutil.HostedClusterAnnotation: "master/cluster1", @@ -1203,21 +1204,22 @@ func TestReconcileCAPICluster(t *testing.T) { Namespace: "master-cluster1", Name: "cluster1", }, - Spec: v1beta1.ClusterSpec{ - ControlPlaneEndpoint: v1beta1.APIEndpoint{}, - ControlPlaneRef: &corev1.ObjectReference{ - APIVersion: "hypershift.openshift.io/v1beta1", - Kind: "HostedControlPlane", - Namespace: "master-cluster1", - Name: "cluster1", + Spec: capiv1.ClusterSpec{ + ControlPlaneEndpoint: capiv1.APIEndpoint{}, + ControlPlaneRef: capiv1.ContractVersionedObjectReference{ + APIGroup: "hypershift.openshift.io", + Kind: "HostedControlPlane", + Name: "cluster1", }, - InfrastructureRef: &corev1.ObjectReference{ - APIVersion: capiaws.GroupVersion.String(), - Kind: "AWSCluster", - Namespace: "master-cluster1", - Name: "cluster1", + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + APIGroup: capiaws.GroupVersion.Group, + Kind: "AWSCluster", + Name: "cluster1", }, }, + Status: capiv1.ClusterStatus{ + Initialization: capiv1.ClusterInitializationStatus{}, + }, }, }, } @@ -2743,7 +2745,7 @@ func TestPauseCAPICluster(t *testing.T) { inputHostedCluster *hyperv1.HostedCluster inputObjects []crclient.Object paused bool - expectedCAPICluster *v1beta1.Cluster + expectedCAPICluster *capiv1.Cluster }{ { name: "When CAPI cluster exists and is paused, it should unpause when paused=false", @@ -2757,24 +2759,24 @@ func TestPauseCAPICluster(t *testing.T) { }, }, inputObjects: []crclient.Object{ - &v1beta1.Cluster{ + &capiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Namespace: controlPlaneNamespace, Name: fakeInfraID, }, - Spec: v1beta1.ClusterSpec{ - Paused: true, + Spec: capiv1.ClusterSpec{ + Paused: ptr.To(true), }, }, }, paused: false, - expectedCAPICluster: &v1beta1.Cluster{ + expectedCAPICluster: &capiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Namespace: controlPlaneNamespace, Name: fakeInfraID, }, - Spec: v1beta1.ClusterSpec{ - Paused: false, + Spec: capiv1.ClusterSpec{ + Paused: ptr.To(false), }, }, }, @@ -2790,24 +2792,24 @@ func TestPauseCAPICluster(t *testing.T) { }, }, inputObjects: []crclient.Object{ - &v1beta1.Cluster{ + &capiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Namespace: controlPlaneNamespace, Name: fakeInfraID, }, - Spec: v1beta1.ClusterSpec{ - Paused: false, + Spec: capiv1.ClusterSpec{ + Paused: ptr.To(false), }, }, }, paused: true, - expectedCAPICluster: &v1beta1.Cluster{ + expectedCAPICluster: &capiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Namespace: controlPlaneNamespace, Name: fakeInfraID, }, - Spec: v1beta1.ClusterSpec{ - Paused: true, + Spec: capiv1.ClusterSpec{ + Paused: ptr.To(true), }, }, }, @@ -2845,24 +2847,24 @@ func TestPauseCAPICluster(t *testing.T) { }, }, inputObjects: []crclient.Object{ - &v1beta1.Cluster{ + &capiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Namespace: controlPlaneNamespace, Name: fakeInfraID, }, - Spec: v1beta1.ClusterSpec{ - Paused: true, + Spec: capiv1.ClusterSpec{ + Paused: ptr.To(true), }, }, }, paused: true, - expectedCAPICluster: &v1beta1.Cluster{ + expectedCAPICluster: &capiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Namespace: controlPlaneNamespace, Name: fakeInfraID, }, - Spec: v1beta1.ClusterSpec{ - Paused: true, + Spec: capiv1.ClusterSpec{ + Paused: ptr.To(true), }, }, }, diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/agent/agent.go b/hypershift-operator/controllers/hostedcluster/internal/platform/agent/agent.go index f78fa42e05a7..875627845edf 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/agent/agent.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/agent/agent.go @@ -21,7 +21,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/agent/agent_test.go b/hypershift-operator/controllers/hostedcluster/internal/platform/agent/agent_test.go index 108b86c5b337..cbf448d50a75 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/agent/agent_test.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/agent/agent_test.go @@ -19,7 +19,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/aws/aws.go b/hypershift-operator/controllers/hostedcluster/internal/platform/aws/aws.go index fd67faa00687..ac588320f15e 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/aws/aws.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/aws/aws.go @@ -22,7 +22,7 @@ import ( "k8s.io/utils/ptr" capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/azure/azure.go b/hypershift-operator/controllers/hostedcluster/internal/platform/azure/azure.go index 4be2ca914d86..909f429f9cc9 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/azure/azure.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/azure/azure.go @@ -26,7 +26,7 @@ import ( "k8s.io/utils/ptr" capiazure "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/blang/semver" diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/gcp/gcp.go b/hypershift-operator/controllers/hostedcluster/internal/platform/gcp/gcp.go index df5f33c15ae3..891414f62e42 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/gcp/gcp.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/gcp/gcp.go @@ -36,7 +36,7 @@ import ( "k8s.io/utils/ptr" capigcp "sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/blang/semver" @@ -87,7 +87,6 @@ func New(utilitiesImage string, capiProviderImage string, payloadVersion *semver func (p GCP) ReconcileCAPIInfraCR(ctx context.Context, c client.Client, createOrUpdate upsert.CreateOrUpdateFN, hcluster *hyperv1.HostedCluster, controlPlaneNamespace string, apiEndpoint hyperv1.APIEndpoint) (client.Object, error) { - // Create GCPCluster object following AWS pattern gcpCluster := &capigcp.GCPCluster{ ObjectMeta: metav1.ObjectMeta{ @@ -298,7 +297,6 @@ func (p GCP) buildVolumes(hcluster *hyperv1.HostedCluster) []corev1.Volume { func (p GCP) ReconcileCredentials(ctx context.Context, c client.Client, createOrUpdate upsert.CreateOrUpdateFN, hcluster *hyperv1.HostedCluster, controlPlaneNamespace string) error { - // Validate GCP platform configuration is present if hcluster.Spec.Platform.GCP == nil { setCondition(hcluster, hyperv1.ValidGCPWorkloadIdentity, metav1.ConditionFalse, "MissingGCPConfiguration", "GCP platform configuration is missing") @@ -494,7 +492,6 @@ func buildGCPWorkloadIdentityCredentials(wif hyperv1.GCPWorkloadIdentityConfig, func (p GCP) ReconcileSecretEncryption(ctx context.Context, c client.Client, createOrUpdate upsert.CreateOrUpdateFN, hcluster *hyperv1.HostedCluster, controlPlaneNamespace string) error { - // TODO: Implement GCP KMS secret encryption return nil } diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/ibmcloud/ibmcloud.go b/hypershift-operator/controllers/hostedcluster/internal/platform/ibmcloud/ibmcloud.go index d90bd5e9acbe..55f4ec11ee43 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/ibmcloud/ibmcloud.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/ibmcloud/ibmcloud.go @@ -15,7 +15,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" capiibmv1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/ibmcloud/ibmcloud_test.go b/hypershift-operator/controllers/hostedcluster/internal/platform/ibmcloud/ibmcloud_test.go index fafb9c30d2ed..7d841db0b5fc 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/ibmcloud/ibmcloud_test.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/ibmcloud/ibmcloud_test.go @@ -13,7 +13,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" capiibmv1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/kubevirt/kubevirt.go b/hypershift-operator/controllers/hostedcluster/internal/platform/kubevirt/kubevirt.go index b8a00a3daa5f..a536ac1df6a2 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/kubevirt/kubevirt.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/kubevirt/kubevirt.go @@ -18,7 +18,7 @@ import ( "k8s.io/utils/ptr" capikubevirt "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" cdicore "kubevirt.io/containerized-data-importer-api/pkg/apis/core" diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/kubevirt/kubevirt_test.go b/hypershift-operator/controllers/hostedcluster/internal/platform/kubevirt/kubevirt_test.go index a16845df131c..4770f61e179d 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/kubevirt/kubevirt_test.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/kubevirt/kubevirt_test.go @@ -11,7 +11,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" capikubevirt "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack.go b/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack.go index 404e72dd76da..523b81a6f342 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack.go @@ -20,7 +20,7 @@ import ( "k8s.io/utils/ptr" capo "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/blang/semver" diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack_test.go b/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack_test.go index 3620e88ca4ad..7196d200d50d 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack_test.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/openstack/openstack_test.go @@ -15,7 +15,7 @@ import ( "k8s.io/utils/ptr" capo "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "github.com/blang/semver" "github.com/google/go-cmp/cmp" diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/platform.go b/hypershift-operator/controllers/hostedcluster/internal/platform/platform.go index c58ff77be3d2..552f4803d8cd 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/platform.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/platform.go @@ -14,7 +14,6 @@ import ( "github.com/openshift/hypershift/hypershift-operator/controllers/hostedcluster/internal/platform/none" "github.com/openshift/hypershift/hypershift-operator/controllers/hostedcluster/internal/platform/openstack" "github.com/openshift/hypershift/hypershift-operator/controllers/hostedcluster/internal/platform/powervs" - "github.com/openshift/hypershift/support/backwardcompat" "github.com/openshift/hypershift/support/releaseinfo" "github.com/openshift/hypershift/support/upsert" imgUtil "github.com/openshift/hypershift/support/util" @@ -108,16 +107,6 @@ func GetPlatform(ctx context.Context, hcluster *hyperv1.HostedCluster, releasePr if err != nil { return nil, fmt.Errorf("failed to fetch payload version: %w", err) } - - if payloadVersion != nil { - imageOverride, err := backwardcompat.GetBackwardCompatibleCAPIImage(ctx, pullSecretBytes, releaseProvider, *payloadVersion, AWSCAPIProvider) - if err != nil { - return nil, err - } - if imageOverride != "" { - capiImageProvider = imageOverride - } - } } platform = aws.New(utilitiesImage, capiImageProvider, payloadVersion) @@ -139,16 +128,6 @@ func GetPlatform(ctx context.Context, hcluster *hyperv1.HostedCluster, releasePr if err != nil { return nil, fmt.Errorf("failed to fetch payload version: %w", err) } - - if payloadVersion != nil { - imageOverride, err := backwardcompat.GetBackwardCompatibleCAPIImage(ctx, pullSecretBytes, releaseProvider, *payloadVersion, AzureCAPIProvider) - if err != nil { - return nil, err - } - if imageOverride != "" { - capiImageProvider = imageOverride - } - } } platform = azure.New(utilitiesImage, capiImageProvider, payloadVersion) diff --git a/hypershift-operator/controllers/hostedcluster/internal/platform/powervs/powervs.go b/hypershift-operator/controllers/hostedcluster/internal/platform/powervs/powervs.go index 49ca1c279bfe..c0f1215b731b 100644 --- a/hypershift-operator/controllers/hostedcluster/internal/platform/powervs/powervs.go +++ b/hypershift-operator/controllers/hostedcluster/internal/platform/powervs/powervs.go @@ -18,7 +18,7 @@ import ( "k8s.io/utils/ptr" capiibmv1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/hypershift-operator/controllers/manifests/controlplaneoperator/manifests.go b/hypershift-operator/controllers/manifests/controlplaneoperator/manifests.go index 914d7eb28a4d..bf60e6108a9f 100644 --- a/hypershift-operator/controllers/manifests/controlplaneoperator/manifests.go +++ b/hypershift-operator/controllers/manifests/controlplaneoperator/manifests.go @@ -8,7 +8,7 @@ import ( rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" prometheusoperatorv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" ) diff --git a/hypershift-operator/controllers/nodepool/aws.go b/hypershift-operator/controllers/nodepool/aws.go index 2c6bfbd29cb2..7f8075ccd35e 100644 --- a/hypershift-operator/controllers/nodepool/aws.go +++ b/hypershift-operator/controllers/nodepool/aws.go @@ -13,7 +13,7 @@ import ( "k8s.io/utils/ptr" capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" diff --git a/hypershift-operator/controllers/nodepool/aws_test.go b/hypershift-operator/controllers/nodepool/aws_test.go index e23ffd3f4eae..ee1824a5c394 100644 --- a/hypershift-operator/controllers/nodepool/aws_test.go +++ b/hypershift-operator/controllers/nodepool/aws_test.go @@ -20,7 +20,7 @@ import ( "k8s.io/utils/ptr" capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -512,7 +512,7 @@ func TestAWSMachineTemplate(t *testing.T) { md := &capiv1.MachineDeployment{ ObjectMeta: metav1.ObjectMeta{Name: tc.nodePool.GetName(), Namespace: namespace}, Spec: capiv1.MachineDeploymentSpec{Template: capiv1.MachineTemplateSpec{Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{Name: tc.existingTemplate.Name}, + InfrastructureRef: capiv1.ContractVersionedObjectReference{Name: tc.existingTemplate.Name}, }}}, } existingObjs = append(existingObjs, md) @@ -520,7 +520,7 @@ func TestAWSMachineTemplate(t *testing.T) { ms := &capiv1.MachineSet{ ObjectMeta: metav1.ObjectMeta{Name: tc.nodePool.GetName(), Namespace: namespace}, Spec: capiv1.MachineSetSpec{Template: capiv1.MachineTemplateSpec{Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{Name: tc.existingTemplate.Name}, + InfrastructureRef: capiv1.ContractVersionedObjectReference{Name: tc.existingTemplate.Name}, }}}, } existingObjs = append(existingObjs, ms) diff --git a/hypershift-operator/controllers/nodepool/azure_test.go b/hypershift-operator/controllers/nodepool/azure_test.go index 7b5e996ab8fc..f2580c24f28d 100644 --- a/hypershift-operator/controllers/nodepool/azure_test.go +++ b/hypershift-operator/controllers/nodepool/azure_test.go @@ -15,7 +15,7 @@ import ( "k8s.io/utils/ptr" capiazure "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) func TestAzureMachineTemplateSpec(t *testing.T) { diff --git a/hypershift-operator/controllers/nodepool/capi.go b/hypershift-operator/controllers/nodepool/capi.go index 39917b81a22c..9906f8ee82b4 100644 --- a/hypershift-operator/controllers/nodepool/capi.go +++ b/hypershift-operator/controllers/nodepool/capi.go @@ -29,7 +29,7 @@ import ( capigcp "sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1" capikubevirt "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" capiopenstackv1beta1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" @@ -245,9 +245,15 @@ func (c *CAPI) cleanupMachineTemplates(ctx context.Context, log logr.Logger, nod ref := filtered[0].Spec.Template.Spec.InfrastructureRef machineTemplates := new(unstructured.UnstructuredList) - machineTemplates.SetAPIVersion(ref.APIVersion) + // v1beta2 ContractVersionedObjectReference has no APIVersion; reconstruct from scheme. + versions := api.Scheme.VersionsForGroupKind(schema.GroupKind{Group: ref.APIGroup, Kind: ref.Kind}) + if len(versions) == 0 { + return fmt.Errorf("no versions registered for GroupKind %s/%s", ref.APIGroup, ref.Kind) + } + apiVersion := schema.GroupVersion{Group: ref.APIGroup, Version: versions[0].Version}.String() + machineTemplates.SetAPIVersion(apiVersion) machineTemplates.SetKind(ref.Kind) - if err := c.Client.List(ctx, machineTemplates, client.InNamespace(ref.Namespace)); err != nil { + if err := c.Client.List(ctx, machineTemplates, client.InNamespace(controlPlaneNamespace)); err != nil { return fmt.Errorf("failed to list MachineTemplates: %w", err) } @@ -419,11 +425,6 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, } machineDeployment.Labels[capiv1.ClusterNameLabel] = capiClusterName - // Set defaults. These are normally set by the CAPI machinedeployment webhook. - // However, since we don't run the webhook, CAPI updates the machinedeployment - // after it has been created with defaults. - machineDeployment.Spec.MinReadySeconds = ptr.To[int32](0) - machineDeployment.Spec.ClusterName = capiClusterName if machineDeployment.Spec.Selector.MatchLabels == nil { machineDeployment.Spec.Selector.MatchLabels = map[string]string{} @@ -455,17 +456,18 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, // Keep current user data for later check. DataSecretName: machineDeployment.Spec.Template.Spec.Bootstrap.DataSecretName, }, - InfrastructureRef: corev1.ObjectReference{ - Kind: gvk.Kind, - APIVersion: gvk.GroupVersion().String(), - Namespace: machineTemplateCR.GetNamespace(), + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: gvk.Kind, + APIGroup: gvk.Group, // keep current template name for later check. Name: machineDeployment.Spec.Template.Spec.InfrastructureRef.Name, }, // Keep current version for later check. - Version: machineDeployment.Spec.Template.Spec.Version, - NodeDrainTimeout: nodePool.Spec.NodeDrainTimeout, - NodeVolumeDetachTimeout: nodePool.Spec.NodeVolumeDetachTimeout, + Version: machineDeployment.Spec.Template.Spec.Version, + Deletion: capiv1.MachineDeletionSpec{ + NodeDrainTimeoutSeconds: durationToSeconds(nodePool.Spec.NodeDrainTimeout), + NodeVolumeDetachTimeoutSeconds: durationToSeconds(nodePool.Spec.NodeVolumeDetachTimeout), + }, }, } @@ -478,14 +480,14 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, // The CAPI provider for OpenStack uses the FailureDomain field to set the availability zone. if c.nodePool.Spec.Platform.Type == hyperv1.OpenStackPlatform && c.nodePool.Spec.Platform.OpenStack != nil { if c.nodePool.Spec.Platform.OpenStack.AvailabilityZone != "" { - machineDeployment.Spec.Template.Spec.FailureDomain = ptr.To(c.nodePool.Spec.Platform.OpenStack.AvailabilityZone) + machineDeployment.Spec.Template.Spec.FailureDomain = c.nodePool.Spec.Platform.OpenStack.AvailabilityZone } } // The CAPI provider for GCP uses the FailureDomain field to set the zone. if c.nodePool.Spec.Platform.Type == hyperv1.GCPPlatform && c.nodePool.Spec.Platform.GCP != nil { if c.nodePool.Spec.Platform.GCP.Zone != "" { - machineDeployment.Spec.Template.Spec.FailureDomain = ptr.To(c.nodePool.Spec.Platform.GCP.Zone) + machineDeployment.Spec.Template.Spec.FailureDomain = c.nodePool.Spec.Platform.GCP.Zone } } @@ -543,10 +545,9 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, } // Set strategy - machineDeployment.Spec.Strategy = &capiv1.MachineDeploymentStrategy{} - machineDeployment.Spec.Strategy.Type = capiv1.MachineDeploymentStrategyType(nodePool.Spec.Management.Replace.Strategy) + machineDeployment.Spec.Rollout.Strategy.Type = capiv1.MachineDeploymentRolloutStrategyType(nodePool.Spec.Management.Replace.Strategy) if nodePool.Spec.Management.Replace.RollingUpdate != nil { - machineDeployment.Spec.Strategy.RollingUpdate = &capiv1.MachineRollingUpdateDeployment{ + machineDeployment.Spec.Rollout.Strategy.RollingUpdate = capiv1.MachineDeploymentRolloutStrategyRollingUpdate{ MaxUnavailable: nodePool.Spec.Management.Replace.RollingUpdate.MaxUnavailable, MaxSurge: nodePool.Spec.Management.Replace.RollingUpdate.MaxSurge, } @@ -565,7 +566,7 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, "current", machineDeployment.Spec.Template.Spec.Bootstrap.DataSecretName, "target", userDataSecret.Name) - if targetVersion != ptr.Deref(machineDeployment.Spec.Template.Spec.Version, "") { + if targetVersion != machineDeployment.Spec.Template.Spec.Version { log.Info("Starting version update: Propagating new version to the MachineDeployment", "releaseImage", nodePool.Spec.Release.Image, "target", targetVersion) } @@ -574,7 +575,7 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, log.Info("Starting config update: Propagating new config to the MachineDeployment", "current", nodePool.Annotations[nodePoolAnnotationCurrentConfig], "target", targetConfigHash) } - machineDeployment.Spec.Template.Spec.Version = &targetVersion + machineDeployment.Spec.Template.Spec.Version = targetVersion machineDeployment.Spec.Template.Spec.Bootstrap.DataSecretName = ptr.To(userDataSecret.Name) isUpdating = true } @@ -596,9 +597,27 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, return nil } + // List MachineSets owned by this MachineDeployment to pass to MachineDeploymentComplete. + // Direct MachineSet spec comparison avoids the CAPI v1beta2 async-condition race where + // ObservedGeneration advances before UpToDateReplicas is recomputed. + msList := &capiv1.MachineSetList{} + if err := c.List(ctx, msList, client.InNamespace(machineDeployment.Namespace)); err != nil { + return fmt.Errorf("failed to list MachineSets: %w", err) + } + var ownedMachineSets []*capiv1.MachineSet + for idx := range msList.Items { + ms := &msList.Items[idx] + for _, ref := range ms.OwnerReferences { + if ref.Kind == "MachineDeployment" && ref.Name == machineDeployment.Name { + ownedMachineSets = append(ownedMachineSets, ms) + break + } + } + } + // If the MachineDeployment is now processing we know // is at the expected version (spec.version) and config (userData Secret) so we reconcile status and annotation. - if MachineDeploymentComplete(machineDeployment) { + if MachineDeploymentComplete(machineDeployment, ownedMachineSets) { if nodePool.Status.Version != targetVersion { log.Info("Version update complete", "previous", nodePool.Status.Version, "new", targetVersion) @@ -623,11 +642,11 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, } // Bubble up AvailableReplicas and Ready condition from MachineDeployment. - nodePool.Status.Replicas = machineDeployment.Status.AvailableReplicas + nodePool.Status.Replicas = ptr.Deref(machineDeployment.Status.AvailableReplicas, 0) for _, c := range machineDeployment.Status.Conditions { - // This condition should aggregate and summarize readiness from underlying MachineSets and Machines + // In CAPI v1beta2 "Ready" was replaced by "MachinesReady" (True when all machines are ready). // https://github.com/kubernetes-sigs/cluster-api/issues/3486. - if c.Type == capiv1.ReadyCondition { + if c.Type == capiv1.MachinesReadyCondition { // this is so api server does not complain // invalid value: \"\": status.conditions.reason in body should be at least 1 chars long" reason := hyperv1.AsExpectedReason @@ -637,7 +656,7 @@ func (c *CAPI) reconcileMachineDeployment(ctx context.Context, log logr.Logger, SetStatusCondition(&nodePool.Status.Conditions, hyperv1.NodePoolCondition{ Type: hyperv1.NodePoolReadyConditionType, - Status: c.Status, + Status: corev1.ConditionStatus(c.Status), ObservedGeneration: nodePool.Generation, Message: c.Message, Reason: reason, @@ -658,6 +677,16 @@ func taintsToJSON(taints []hyperv1.Taint) (string, error) { return string(taintsInJSON), nil } +// durationToSeconds converts a *metav1.Duration to *int32 seconds. +// CAPI v1beta2 uses integer seconds for timeouts instead of metav1.Duration. +func durationToSeconds(d *metav1.Duration) *int32 { + if d == nil { + return nil + } + s := int32(d.Seconds()) + return &s +} + func (c *CAPI) reconcileMachineHealthCheck(ctx context.Context, mhc *capiv1.MachineHealthCheck) error { @@ -721,6 +750,8 @@ func (c *CAPI) reconcileMachineHealthCheck(ctx context.Context, } resourcesName := generateName(capiClusterName, nodePool.Spec.ClusterName, nodePool.GetName()) + timeoutSec := int32(timeOut.Seconds()) + startupSec := int32(nodeStartupTimeout.Seconds()) mhc.Spec = capiv1.MachineHealthCheckSpec{ ClusterName: capiClusterName, Selector: metav1.LabelSelector{ @@ -728,25 +759,25 @@ func (c *CAPI) reconcileMachineHealthCheck(ctx context.Context, resourcesName: resourcesName, }, }, - UnhealthyConditions: []capiv1.UnhealthyCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionFalse, - Timeout: metav1.Duration{ - Duration: timeOut, + Checks: capiv1.MachineHealthCheckChecks{ + NodeStartupTimeoutSeconds: &startupSec, + UnhealthyNodeConditions: []capiv1.UnhealthyNodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionFalse, + TimeoutSeconds: &timeoutSec, }, - }, - { - Type: corev1.NodeReady, - Status: corev1.ConditionUnknown, - Timeout: metav1.Duration{ - Duration: timeOut, + { + Type: corev1.NodeReady, + Status: corev1.ConditionUnknown, + TimeoutSeconds: &timeoutSec, }, }, }, - MaxUnhealthy: &maxUnhealthy, - NodeStartupTimeout: &metav1.Duration{ - Duration: nodeStartupTimeout, + Remediation: capiv1.MachineHealthCheckRemediation{ + TriggerIf: capiv1.MachineHealthCheckRemediationTriggerIf{ + UnhealthyLessThanOrEqualTo: &maxUnhealthy, + }, }, } return nil @@ -880,7 +911,6 @@ func (c *CAPI) reconcileMachineSet(ctx context.Context, machineSet.Labels[capiv1.ClusterNameLabel] = capiClusterName resourcesName := generateName(capiClusterName, nodePool.Spec.ClusterName, nodePool.GetName()) - machineSet.Spec.MinReadySeconds = int32(0) gvk, err := apiutil.GVKForObject(machineTemplateCR, api.Scheme) if err != nil { @@ -922,17 +952,18 @@ func (c *CAPI) reconcileMachineSet(ctx context.Context, // Keep current user data for later check. DataSecretName: machineSet.Spec.Template.Spec.Bootstrap.DataSecretName, }, - InfrastructureRef: corev1.ObjectReference{ - Kind: gvk.Kind, - APIVersion: gvk.GroupVersion().String(), - Namespace: machineTemplateCR.GetNamespace(), - // Keep current version for later check. + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: gvk.Kind, + APIGroup: gvk.Group, + // Keep current template name for later check. Name: machineSet.Spec.Template.Spec.InfrastructureRef.Name, }, // Keep current version for later check. - Version: machineSet.Spec.Template.Spec.Version, - NodeDrainTimeout: nodePool.Spec.NodeDrainTimeout, - NodeVolumeDetachTimeout: nodePool.Spec.NodeVolumeDetachTimeout, + Version: machineSet.Spec.Template.Spec.Version, + Deletion: capiv1.MachineDeletionSpec{ + NodeDrainTimeoutSeconds: durationToSeconds(nodePool.Spec.NodeDrainTimeout), + NodeVolumeDetachTimeoutSeconds: durationToSeconds(nodePool.Spec.NodeVolumeDetachTimeout), + }, }, } @@ -966,7 +997,7 @@ func (c *CAPI) reconcileMachineSet(ctx context.Context, "target", userDataSecret.Name) // TODO (alberto): possibly compare with NodePool here instead so we don't rely on impl details to drive decisions. - if targetVersion != ptr.Deref(machineSet.Spec.Template.Spec.Version, "") { + if targetVersion != machineSet.Spec.Template.Spec.Version { log.Info("Starting version upgrade: Propagating new version to the MachineSet", "releaseImage", nodePool.Spec.Release.Image, "target", targetVersion) } @@ -975,7 +1006,7 @@ func (c *CAPI) reconcileMachineSet(ctx context.Context, log.Info("Starting config upgrade: Propagating new config to the MachineSet", "current", nodePool.Annotations[nodePoolAnnotationCurrentConfig], "target", targetConfigHash) } - machineSet.Spec.Template.Spec.Version = &targetVersion + machineSet.Spec.Template.Spec.Version = targetVersion machineSet.Spec.Template.Spec.Bootstrap.DataSecretName = ptr.To(userDataSecret.Name) // Signal in-place upgrade request. @@ -1031,11 +1062,11 @@ func (c *CAPI) reconcileMachineSet(ctx context.Context, } // Bubble up AvailableReplicas and Ready condition from MachineSet. - nodePool.Status.Replicas = machineSet.Status.AvailableReplicas + nodePool.Status.Replicas = ptr.Deref(machineSet.Status.AvailableReplicas, 0) for _, c := range machineSet.Status.Conditions { - // This condition should aggregate and summarize readiness from underlying MachineSets and Machines + // In CAPI v1beta2 "Ready" was replaced by "MachinesReady" (True when all machines are ready). // https://github.com/kubernetes-sigs/cluster-api/issues/3486. - if c.Type == capiv1.ReadyCondition { + if c.Type == capiv1.MachinesReadyCondition { // this is so api server does not complain // invalid value: \"\": status.conditions.reason in body should be at least 1 chars long" reason := hyperv1.AsExpectedReason @@ -1045,7 +1076,7 @@ func (c *CAPI) reconcileMachineSet(ctx context.Context, SetStatusCondition(&nodePool.Status.Conditions, hyperv1.NodePoolCondition{ Type: hyperv1.NodePoolReadyConditionType, - Status: c.Status, + Status: corev1.ConditionStatus(c.Status), ObservedGeneration: nodePool.Generation, Message: c.Message, Reason: reason, @@ -1169,6 +1200,8 @@ func (c *CAPI) reconcileSpotMachineHealthCheck(ctx context.Context, mhc *capiv1. timeOut := 8 * time.Minute nodeStartupTimeout := 20 * time.Minute + timeoutSec := int32(timeOut.Seconds()) + startupSec := int32(nodeStartupTimeout.Seconds()) mhc.Spec = capiv1.MachineHealthCheckSpec{ ClusterName: c.capiClusterName, Selector: metav1.LabelSelector{ @@ -1176,25 +1209,25 @@ func (c *CAPI) reconcileSpotMachineHealthCheck(ctx context.Context, mhc *capiv1. interruptibleInstanceLabel: "", }, }, - UnhealthyConditions: []capiv1.UnhealthyCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionFalse, - Timeout: metav1.Duration{ - Duration: timeOut, + Checks: capiv1.MachineHealthCheckChecks{ + NodeStartupTimeoutSeconds: &startupSec, + UnhealthyNodeConditions: []capiv1.UnhealthyNodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionFalse, + TimeoutSeconds: &timeoutSec, }, - }, - { - Type: corev1.NodeReady, - Status: corev1.ConditionUnknown, - Timeout: metav1.Duration{ - Duration: timeOut, + { + Type: corev1.NodeReady, + Status: corev1.ConditionUnknown, + TimeoutSeconds: &timeoutSec, }, }, }, - MaxUnhealthy: &maxUnhealthy, - NodeStartupTimeout: &metav1.Duration{ - Duration: nodeStartupTimeout, + Remediation: capiv1.MachineHealthCheckRemediation{ + TriggerIf: capiv1.MachineHealthCheckRemediationTriggerIf{ + UnhealthyLessThanOrEqualTo: &maxUnhealthy, + }, }, } diff --git a/hypershift-operator/controllers/nodepool/capi_test.go b/hypershift-operator/controllers/nodepool/capi_test.go index d651ffd38b13..c425198c0684 100644 --- a/hypershift-operator/controllers/nodepool/capi_test.go +++ b/hypershift-operator/controllers/nodepool/capi_test.go @@ -26,7 +26,7 @@ import ( capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" capiazure "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1" capikubevirt "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" @@ -810,11 +810,10 @@ func TestCleanupMachineTemplates(t *testing.T) { Spec: capiv1.MachineSetSpec{ Template: capiv1.MachineTemplateSpec{ Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ - Kind: gvk.Kind, - APIVersion: gvk.GroupVersion().String(), - Name: template1.Name, - Namespace: template1.Namespace, + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: gvk.Kind, + APIGroup: gvk.Group, + Name: template1.Name, }, }, }, @@ -1089,6 +1088,8 @@ func TestReconcileMachineHealthCheck(t *testing.T) { healthcheck := func(opts ...func(*capiv1.MachineHealthCheck)) *capiv1.MachineHealthCheck { mhc := &capiv1.MachineHealthCheck{ObjectMeta: metav1.ObjectMeta{Namespace: "ns-cluster", Name: "nodepool"}} resName := generateName("cluster", "cluster", "nodepool") + timeoutSec := int32((8 * time.Minute).Seconds()) + startupSec := int32((20 * time.Minute).Seconds()) mhc.Spec = capiv1.MachineHealthCheckSpec{ ClusterName: "cluster", Selector: metav1.LabelSelector{ @@ -1096,25 +1097,17 @@ func TestReconcileMachineHealthCheck(t *testing.T) { resName: resName, }, }, - UnhealthyConditions: []capiv1.UnhealthyCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionFalse, - Timeout: metav1.Duration{ - Duration: time.Duration(8 * time.Minute), - }, - }, - { - Type: corev1.NodeReady, - Status: corev1.ConditionUnknown, - Timeout: metav1.Duration{ - Duration: time.Duration(8 * time.Minute), - }, + Checks: capiv1.MachineHealthCheckChecks{ + NodeStartupTimeoutSeconds: &startupSec, + UnhealthyNodeConditions: []capiv1.UnhealthyNodeCondition{ + {Type: corev1.NodeReady, Status: corev1.ConditionFalse, TimeoutSeconds: &timeoutSec}, + {Type: corev1.NodeReady, Status: corev1.ConditionUnknown, TimeoutSeconds: &timeoutSec}, }, }, - MaxUnhealthy: &defaultMaxUnhealthy, - NodeStartupTimeout: &metav1.Duration{ - Duration: 20 * time.Minute, + Remediation: capiv1.MachineHealthCheckRemediation{ + TriggerIf: capiv1.MachineHealthCheckRemediationTriggerIf{ + UnhealthyLessThanOrEqualTo: &defaultMaxUnhealthy, + }, }, } for _, o := range opts { @@ -1146,8 +1139,9 @@ func TestReconcileMachineHealthCheck(t *testing.T) { } withTimeout := func(d time.Duration) func(*capiv1.MachineHealthCheck) { return func(mhc *capiv1.MachineHealthCheck) { - for i := range mhc.Spec.UnhealthyConditions { - mhc.Spec.UnhealthyConditions[i].Timeout = metav1.Duration{Duration: d} + s := int32(d.Seconds()) + for i := range mhc.Spec.Checks.UnhealthyNodeConditions { + mhc.Spec.Checks.UnhealthyNodeConditions[i].TimeoutSeconds = &s } } } @@ -1163,7 +1157,8 @@ func TestReconcileMachineHealthCheck(t *testing.T) { } withNodeStartupTimeout := func(d time.Duration) func(*capiv1.MachineHealthCheck) { return func(mhc *capiv1.MachineHealthCheck) { - mhc.Spec.NodeStartupTimeout = &metav1.Duration{Duration: d} + s := int32(d.Seconds()) + mhc.Spec.Checks.NodeStartupTimeoutSeconds = &s } } @@ -1333,13 +1328,10 @@ func TestCAPIReconcile(t *testing.T) { Spec: capiv1.MachineSetSpec{ Template: capiv1.MachineTemplateSpec{ Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ - Kind: "AWSMachineTemplate", - APIVersion: "infrastructure.cluster.x-k8s.io/v1beta2", - Namespace: "test-namespace-test-cluster", - // This is the generated name by machineTemplateBuilders. - // So reconciliation doesn't create a new AWSMachineTemplate but reconcile this one. - Name: awsMachineTemplateName, + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: "AWSMachineTemplate", + APIGroup: "infrastructure.cluster.x-k8s.io", + Name: awsMachineTemplateName, }, }, }, @@ -1429,13 +1421,10 @@ func TestCAPIReconcile(t *testing.T) { Spec: capiv1.MachineSetSpec{ Template: capiv1.MachineTemplateSpec{ Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ - Kind: "AWSMachineTemplate", - APIVersion: "infrastructure.cluster.x-k8s.io/v1beta2", - Namespace: "test-namespace-test-cluster", - // This is the generated name by machineTemplateBuilders. - // So reconciliation doesn't create a new AWSMachineTemplate but reconcile this one. - Name: awsMachineTemplateName, + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: "AWSMachineTemplate", + APIGroup: "infrastructure.cluster.x-k8s.io", + Name: awsMachineTemplateName, }, }, }, @@ -1536,13 +1525,10 @@ func TestCAPIReconcile(t *testing.T) { Spec: capiv1.MachineSetSpec{ Template: capiv1.MachineTemplateSpec{ Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ - Kind: "AWSMachineTemplate", - APIVersion: "infrastructure.cluster.x-k8s.io/v1beta2", - Namespace: "test-namespace-test-cluster", - // This is the generated name by machineTemplateBuilders. - // So reconciliation doesn't create a new AWSMachineTemplate but reconcile this one. - Name: awsMachineTemplateName, + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: "AWSMachineTemplate", + APIGroup: "infrastructure.cluster.x-k8s.io", + Name: awsMachineTemplateName, }, }, }, @@ -1650,11 +1636,10 @@ func TestCAPIReconcile(t *testing.T) { Spec: capiv1.MachineSetSpec{ Template: capiv1.MachineTemplateSpec{ Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ - Kind: "AWSMachineTemplate", - APIVersion: "infrastructure.cluster.x-k8s.io/v1beta2", - Namespace: "test-namespace-test-cluster", - Name: awsMachineTemplateName, + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: "AWSMachineTemplate", + APIGroup: "infrastructure.cluster.x-k8s.io", + Name: awsMachineTemplateName, }, }, }, @@ -1752,9 +1737,9 @@ func TestCAPIReconcile(t *testing.T) { g.Expect(md.Annotations).To(HaveKeyWithValue(nodePoolAnnotation, "test-namespace/test-nodepool")) // Check MachineDeployment spec. - g.Expect(md.Spec.Strategy.Type).To(Equal(capiv1.MachineDeploymentStrategyType("RollingUpdate"))) - g.Expect(md.Spec.Strategy.RollingUpdate.MaxUnavailable.IntValue()).To(Equal(0)) - g.Expect(md.Spec.Strategy.RollingUpdate.MaxSurge.IntValue()).To(Equal(1)) + g.Expect(md.Spec.Rollout.Strategy.Type).To(Equal(capiv1.MachineDeploymentRolloutStrategyType("RollingUpdate"))) + g.Expect(md.Spec.Rollout.Strategy.RollingUpdate.MaxUnavailable.IntValue()).To(Equal(0)) + g.Expect(md.Spec.Rollout.Strategy.RollingUpdate.MaxSurge.IntValue()).To(Equal(1)) // Check MachineDeployment labels. g.Expect(md.Labels).To(HaveKeyWithValue(capiv1.ClusterNameLabel, capiClusterName)) @@ -1767,14 +1752,13 @@ func TestCAPIReconcile(t *testing.T) { // Check MachineDeployment template spec g.Expect(md.Spec.Template.Spec.ClusterName).To(Equal(capiClusterName)) - g.Expect(md.Spec.Template.Spec.InfrastructureRef.APIVersion).To(Equal("infrastructure.cluster.x-k8s.io/v1beta2")) + g.Expect(md.Spec.Template.Spec.InfrastructureRef.APIGroup).To(Equal("infrastructure.cluster.x-k8s.io")) g.Expect(md.Spec.Template.Spec.InfrastructureRef.Kind).To(Equal("AWSMachineTemplate")) - g.Expect(md.Spec.Template.Spec.InfrastructureRef.Namespace).To(Equal(controlpaneNamespace)) g.Expect(md.Spec.Template.Spec.InfrastructureRef.Name).To(Equal(awsMachineTemplateName)) - g.Expect(*md.Spec.Template.Spec.Version).To(Equal("target-version")) - g.Expect(md.Spec.Template.Spec.NodeDrainTimeout).To(Equal(tt.nodePool.Spec.NodeDrainTimeout)) - g.Expect(md.Spec.Template.Spec.NodeVolumeDetachTimeout).To(Equal(tt.nodePool.Spec.NodeVolumeDetachTimeout)) + g.Expect(md.Spec.Template.Spec.Version).To(Equal("target-version")) + g.Expect(md.Spec.Template.Spec.Deletion.NodeDrainTimeoutSeconds).To(Equal(durationToSeconds(tt.nodePool.Spec.NodeDrainTimeout))) + g.Expect(md.Spec.Template.Spec.Deletion.NodeVolumeDetachTimeoutSeconds).To(Equal(durationToSeconds(tt.nodePool.Spec.NodeVolumeDetachTimeout))) // Check Bootstrap DataSecretName. g.Expect(md.Spec.Template.Spec.Bootstrap.DataSecretName).NotTo(BeNil()) @@ -1829,10 +1813,10 @@ func TestCAPIReconcile(t *testing.T) { g.Expect(err).NotTo(HaveOccurred()) // Update MachineDeployment status to indicate rollout is complete. - md.Status.Replicas = *tt.nodePool.Spec.Replicas - md.Status.UpdatedReplicas = *tt.nodePool.Spec.Replicas - md.Status.ReadyReplicas = *tt.nodePool.Spec.Replicas - md.Status.AvailableReplicas = *tt.nodePool.Spec.Replicas + md.Status.Replicas = tt.nodePool.Spec.Replicas + md.Status.UpToDateReplicas = tt.nodePool.Spec.Replicas + md.Status.ReadyReplicas = tt.nodePool.Spec.Replicas + md.Status.AvailableReplicas = tt.nodePool.Spec.Replicas md.Status.ObservedGeneration = md.Generation err = capi.Client.Update(t.Context(), md) g.Expect(err).NotTo(HaveOccurred()) @@ -1841,6 +1825,20 @@ func TestCAPIReconcile(t *testing.T) { err = capi.Client.Get(t.Context(), client.ObjectKey{Namespace: controlpaneNamespace, Name: tt.nodePool.GetName()}, md) g.Expect(err).NotTo(HaveOccurred()) + // MachineDeploymentComplete checks owned MachineSets; fake client doesn't auto-create them. + ownedMS := &capiv1.MachineSet{ + ObjectMeta: metav1.ObjectMeta{ + Name: md.Name + "-owned", Namespace: controlpaneNamespace, + OwnerReferences: []metav1.OwnerReference{{Kind: "MachineDeployment", Name: md.Name, APIVersion: capiv1.GroupVersion.String()}}, + }, + Spec: capiv1.MachineSetSpec{Replicas: tt.nodePool.Spec.Replicas, Template: md.Spec.Template}, + } + err = capi.Client.Create(t.Context(), ownedMS) + g.Expect(err).NotTo(HaveOccurred()) + ownedMS.Status.Replicas = tt.nodePool.Spec.Replicas + err = capi.Client.Update(t.Context(), ownedMS) + g.Expect(err).NotTo(HaveOccurred()) + // Re-run reconcile. err = capi.Reconcile(t.Context()) g.Expect(err).NotTo(HaveOccurred()) @@ -1936,11 +1934,10 @@ func TestGlobalPSManagedLabelOnMachines(t *testing.T) { Spec: capiv1.MachineSetSpec{ Template: capiv1.MachineTemplateSpec{ Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ - Kind: "AWSMachineTemplate", - APIVersion: "infrastructure.cluster.x-k8s.io/v1beta2", - Namespace: controlPlaneNamespace, - Name: awsMachineTemplateName, + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: "AWSMachineTemplate", + APIGroup: "infrastructure.cluster.x-k8s.io", + Name: awsMachineTemplateName, }, }, }, @@ -2084,11 +2081,10 @@ func TestGlobalPSManagedLabelOnMachines(t *testing.T) { Spec: capiv1.MachineSetSpec{ Template: capiv1.MachineTemplateSpec{ Spec: capiv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ - Kind: "AWSMachineTemplate", - APIVersion: "infrastructure.cluster.x-k8s.io/v1beta2", - Namespace: controlPlaneNamespace, - Name: awsMachineTemplateName, + InfrastructureRef: capiv1.ContractVersionedObjectReference{ + Kind: "AWSMachineTemplate", + APIGroup: "infrastructure.cluster.x-k8s.io", + Name: awsMachineTemplateName, }, }, }, diff --git a/hypershift-operator/controllers/nodepool/conditions.go b/hypershift-operator/controllers/nodepool/conditions.go index d357e2038a5c..ecf3ddadd6ed 100644 --- a/hypershift-operator/controllers/nodepool/conditions.go +++ b/hypershift-operator/controllers/nodepool/conditions.go @@ -20,7 +20,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" crclient "sigs.k8s.io/controller-runtime/pkg/client" @@ -99,7 +99,7 @@ func FindStatusCondition(conditions []hyperv1.NodePoolCondition, conditionType s } // FindStatusCondition finds the conditionType in conditions. -func findCAPIStatusCondition(conditions []capiv1.Condition, conditionType capiv1.ConditionType) *capiv1.Condition { +func findCAPIStatusCondition(conditions []metav1.Condition, conditionType string) *metav1.Condition { for i := range conditions { if conditions[i].Type == conditionType { return &conditions[i] @@ -618,7 +618,7 @@ func (r *NodePoolReconciler) setAllNodesHealthyCondition(nodePool *hyperv1.NodeP for _, machine := range machines { condition := findCAPIStatusCondition(machine.Status.Conditions, capiv1.MachineNodeHealthyCondition) - if condition != nil && condition.Status != corev1.ConditionTrue { + if condition != nil && condition.Status != metav1.ConditionTrue { status = corev1.ConditionFalse reason = condition.Reason message = message + fmt.Sprintf("Machine %s: %s\n", machine.Name, condition.Reason) @@ -667,7 +667,7 @@ func (r *NodePoolReconciler) setAllMachinesReadyCondition(nodePool *hyperv1.Node for _, machine := range machines { readyCond := findCAPIStatusCondition(machine.Status.Conditions, capiv1.ReadyCondition) - if readyCond != nil && readyCond.Status != corev1.ConditionTrue { + if readyCond != nil && readyCond.Status != metav1.ConditionTrue { status = corev1.ConditionFalse numNotReady++ infraReadyCond := findCAPIStatusCondition(machine.Status.Conditions, capiv1.InfrastructureReadyCondition) @@ -680,7 +680,7 @@ func (r *NodePoolReconciler) setAllMachinesReadyCondition(nodePool *hyperv1.Node // status: "False" // type: Ready var mapReason, mapMessage string - if infraReadyCond != nil && infraReadyCond.Status != corev1.ConditionTrue && !isSetupCounterCondMessage.MatchString(infraReadyCond.Message) { + if infraReadyCond != nil && infraReadyCond.Status != metav1.ConditionTrue && !isSetupCounterCondMessage.MatchString(infraReadyCond.Message) { mapReason = infraReadyCond.Reason mapMessage = fmt.Sprintf("Machine %s: %s: %s\n", machine.Name, infraReadyCond.Reason, infraReadyCond.Message) } else { diff --git a/hypershift-operator/controllers/nodepool/conditions_test.go b/hypershift-operator/controllers/nodepool/conditions_test.go index 5767d131a48b..c52571f328cd 100644 --- a/hypershift-operator/controllers/nodepool/conditions_test.go +++ b/hypershift-operator/controllers/nodepool/conditions_test.go @@ -20,7 +20,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" - "sigs.k8s.io/cluster-api/api/v1beta1" + "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client/fake" "github.com/blang/semver" diff --git a/hypershift-operator/controllers/nodepool/gcp.go b/hypershift-operator/controllers/nodepool/gcp.go index 652cefd32a65..5151160faee2 100644 --- a/hypershift-operator/controllers/nodepool/gcp.go +++ b/hypershift-operator/controllers/nodepool/gcp.go @@ -12,7 +12,7 @@ import ( "k8s.io/utils/ptr" capigcp "sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/hypershift-operator/controllers/nodepool/metrics/metrics.go b/hypershift-operator/controllers/nodepool/metrics/metrics.go index da505b807d1d..25522fbacd18 100644 --- a/hypershift-operator/controllers/nodepool/metrics/metrics.go +++ b/hypershift-operator/controllers/nodepool/metrics/metrics.go @@ -16,7 +16,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/utils/clock" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" ctrllog "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/metrics" diff --git a/hypershift-operator/controllers/nodepool/nodepool_controller.go b/hypershift-operator/controllers/nodepool/nodepool_controller.go index eb515d893416..3536287d5b18 100644 --- a/hypershift-operator/controllers/nodepool/nodepool_controller.go +++ b/hypershift-operator/controllers/nodepool/nodepool_controller.go @@ -34,11 +34,12 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/workqueue" + "k8s.io/utils/ptr" capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" capiazure "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1" capiopenstackv1beta1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/cluster-api/util" "sigs.k8s.io/cluster-api/util/patch" ctrl "sigs.k8s.io/controller-runtime" @@ -772,12 +773,33 @@ func defaultNodePoolGCPImage(specifiedArch string, releaseImage *releaseinfo.Rel // MachineDeploymentComplete considers a MachineDeployment to be complete once all of its desired replicas // are updated and available, and no old machines are running. -func MachineDeploymentComplete(deployment *capiv1.MachineDeployment) bool { - newStatus := &deployment.Status - return newStatus.UpdatedReplicas == *(deployment.Spec.Replicas) && - newStatus.Replicas == *(deployment.Spec.Replicas) && - newStatus.AvailableReplicas == *(deployment.Spec.Replicas) && - newStatus.ObservedGeneration >= deployment.Generation +func MachineDeploymentComplete(deployment *capiv1.MachineDeployment, machineSets []*capiv1.MachineSet) bool { + replicas := ptr.Deref(deployment.Spec.Replicas, 0) + s := &deployment.Status + if ptr.Deref(s.Replicas, 0) != replicas || + ptr.Deref(s.AvailableReplicas, 0) != replicas || + s.ObservedGeneration < deployment.Generation { + return false + } + + desiredSecret := ptr.Deref(deployment.Spec.Template.Spec.Bootstrap.DataSecretName, "") + desiredVersion := deployment.Spec.Template.Spec.Version + desiredInfraRef := deployment.Spec.Template.Spec.InfrastructureRef.Name + for _, ms := range machineSets { + // Skip MachineSets that have been scaled to zero: they are being cleaned up after a + // rolling update and their stale spec should not block completion detection. + // Active MachineSets (spec.Replicas > 0) must all carry the desired spec; if any + // does not, the rolling update is still in progress. + if ptr.Deref(ms.Spec.Replicas, 0) == 0 { + continue + } + if ptr.Deref(ms.Spec.Template.Spec.Bootstrap.DataSecretName, "") != desiredSecret || + ms.Spec.Template.Spec.Version != desiredVersion || + ms.Spec.Template.Spec.InfrastructureRef.Name != desiredInfraRef { + return false + } + } + return true } // GetHostedClusterByName finds and return a HostedCluster object using the specified params. diff --git a/hypershift-operator/controllers/nodepool/nodepool_controller_test.go b/hypershift-operator/controllers/nodepool/nodepool_controller_test.go index 6da1240148ab..3570aa9b725e 100644 --- a/hypershift-operator/controllers/nodepool/nodepool_controller_test.go +++ b/hypershift-operator/controllers/nodepool/nodepool_controller_test.go @@ -34,7 +34,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -723,7 +723,6 @@ func TestGetHostedClusterVersion(t *testing.T) { g.Expect(version).ToNot(BeNil()) g.Expect(version.String()).To(Equal(tc.expectedVersion)) }) - } } @@ -785,10 +784,10 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, }, }, @@ -802,10 +801,10 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, }, }, @@ -836,16 +835,16 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "test message node 1", }, { Type: capiv1.MachineNodeHealthyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "test message node 1", }, @@ -861,16 +860,16 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "test message node 2", }, { Type: capiv1.MachineNodeHealthyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "test message node 2", }, @@ -904,22 +903,22 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "test message node 1", }, { Type: capiv1.InfrastructureReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "12 of 34 completed", }, { Type: capiv1.MachineNodeHealthyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "test message node 1", }, @@ -936,22 +935,22 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "test message node 2", }, { Type: capiv1.InfrastructureReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "some real failed message", }, { Type: capiv1.MachineNodeHealthyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "test message node 2", }, @@ -968,14 +967,14 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, { Type: capiv1.MachineNodeHealthyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, }, }, @@ -1007,22 +1006,22 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "test message node 1", }, { Type: capiv1.InfrastructureReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "some real failed message", }, { Type: capiv1.MachineNodeHealthyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "test message node 1", }, @@ -1039,22 +1038,22 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "test message node 2", }, { Type: capiv1.InfrastructureReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "12 of 34 completed", }, { Type: capiv1.MachineNodeHealthyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "test message node 2", }, @@ -1071,14 +1070,14 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, { Type: capiv1.MachineNodeHealthyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, }, }, @@ -1115,16 +1114,16 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: "not ready", }, { Type: capiv1.InfrastructureReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode1", Message: longMessage, }, @@ -1142,16 +1141,16 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: "not ready", }, { Type: capiv1.InfrastructureReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode2", Message: longMessage, }, @@ -1169,16 +1168,16 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode3", Message: "not ready", }, { Type: capiv1.InfrastructureReadyCondition, - Status: corev1.ConditionFalse, + Status: metav1.ConditionFalse, Reason: "TestReasonNode3", Message: longMessage, }, @@ -1196,10 +1195,10 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, }, }, @@ -1227,10 +1226,10 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, }, Addresses: capiv1.MachineAddresses{ @@ -1250,10 +1249,10 @@ func TestSetMachineAndNodeConditions(t *testing.T) { }, }, Status: capiv1.MachineStatus{ - Conditions: []capiv1.Condition{ + Conditions: []metav1.Condition{ { Type: capiv1.ReadyCondition, - Status: corev1.ConditionTrue, + Status: metav1.ConditionTrue, }, }, Addresses: capiv1.MachineAddresses{ @@ -1329,7 +1328,6 @@ func TestSetMachineAndNodeConditions(t *testing.T) { gg.Expect(cond).ToNot(BeNil()) tc.expectedCIDRCollision.Compare(gg, cond) } - }) } } @@ -1512,6 +1510,7 @@ func Test_validateHCPayloadSupportsNodePoolCPUArch(t *testing.T) { }) } } + func TestResolveHAProxyImage(t *testing.T) { const ( testAnnotationImage = "quay.io/test/haproxy:custom" diff --git a/hypershift-operator/controllers/nodepool/powervs.go b/hypershift-operator/controllers/nodepool/powervs.go index 24c22251af4d..a5da193166d8 100644 --- a/hypershift-operator/controllers/nodepool/powervs.go +++ b/hypershift-operator/controllers/nodepool/powervs.go @@ -12,7 +12,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" capipowervs "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" ) diff --git a/hypershift-operator/controllers/nodepool/scale_from_zero_test.go b/hypershift-operator/controllers/nodepool/scale_from_zero_test.go index c12c829a0c5c..281d8a31b655 100644 --- a/hypershift-operator/controllers/nodepool/scale_from_zero_test.go +++ b/hypershift-operator/controllers/nodepool/scale_from_zero_test.go @@ -15,7 +15,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) type mockProvider struct { diff --git a/hypershift-operator/controllers/nodepool/version.go b/hypershift-operator/controllers/nodepool/version.go index a13808688168..b95a99698f3b 100644 --- a/hypershift-operator/controllers/nodepool/version.go +++ b/hypershift-operator/controllers/nodepool/version.go @@ -7,9 +7,9 @@ import ( hyperv1 "github.com/openshift/hypershift/api/hypershift/v1beta1" - corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) // versionKey is used as a map key for grouping machines by version. @@ -53,7 +53,7 @@ func (r *NodePoolReconciler) nodeVersionsFromMachines(_ context.Context, machine // Determine node health from CAPI NodeHealthy condition. condition := findCAPIStatusCondition(machine.Status.Conditions, capiv1.MachineNodeHealthyCondition) - if condition != nil && condition.Status == corev1.ConditionTrue { + if condition != nil && condition.Status == metav1.ConditionTrue { versionCounts[key].ready++ } else { versionCounts[key].unready++ diff --git a/hypershift-operator/controllers/nodepool/version_test.go b/hypershift-operator/controllers/nodepool/version_test.go index e7eb1466b9eb..8d1b6b0bbe29 100644 --- a/hypershift-operator/controllers/nodepool/version_test.go +++ b/hypershift-operator/controllers/nodepool/version_test.go @@ -13,7 +13,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" - "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) @@ -21,7 +21,7 @@ import ( func TestNodeVersionsFromMachines(t *testing.T) { testCases := []struct { name string - machines []*v1beta1.Machine + machines []*capiv1.Machine nodePool *hyperv1.NodePool expected []hyperv1.NodeVersion }{ @@ -35,7 +35,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When all machines have the same version and are healthy it should return a single entry", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m2", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m3", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), @@ -49,7 +49,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When there are mixed versions during rolling upgrade it should return one entry per version", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m2", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m3", "v1.32.1", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.19.1"}), @@ -64,7 +64,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When there is mixed health it should report ready and unready counts per version", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m2", "v1.32.1", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.19.1"}), machineWithVersionAndHealth("m3", "v1.32.1", false, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.19.1"}), @@ -79,7 +79,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When NodeHealthy condition is absent it should count the node as unready", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ machineWithVersionAndConditions("m1", "v1.31.4", nil, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), }, nodePool: &hyperv1.NodePool{ @@ -91,14 +91,14 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When some machines have no NodeInfo it should skip them", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), { ObjectMeta: metav1.ObjectMeta{ Name: "m2", Annotations: map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.19.1"}, }, - Status: v1beta1.MachineStatus{ + Status: capiv1.MachineStatus{ // NodeInfo is nil — not yet provisioned }, }, @@ -112,10 +112,10 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When all machines have no NodeInfo it should return nil", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ { ObjectMeta: metav1.ObjectMeta{Name: "m1"}, - Status: v1beta1.MachineStatus{}, + Status: capiv1.MachineStatus{}, }, }, nodePool: &hyperv1.NodePool{ @@ -125,7 +125,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When machine has release-version annotation it should use it for ocpVersion", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), }, nodePool: &hyperv1.NodePool{ @@ -137,7 +137,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When machine has no annotation it should fall back to nodePool.Status.Version", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ machineWithVersionAndHealth("m1", "v1.31.4", true, nil), }, nodePool: &hyperv1.NodePool{ @@ -149,7 +149,7 @@ func TestNodeVersionsFromMachines(t *testing.T) { }, { name: "When there are multiple versions it should sort by ocpVersion then kubeletVersion", - machines: []*v1beta1.Machine{ + machines: []*capiv1.Machine{ machineWithVersionAndHealth("m1", "v1.32.1", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.19.1"}), machineWithVersionAndHealth("m2", "v1.31.4", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), machineWithVersionAndHealth("m3", "v1.31.5", true, map[string]string{hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12"}), @@ -214,7 +214,7 @@ func TestSetNodesInfoStatus(t *testing.T) { { name: "When machines exist with NodeInfo it should populate NodesInfo", machines: []client.Object{ - &v1beta1.Machine{ + &capiv1.Machine{ ObjectMeta: metav1.ObjectMeta{ Name: "m1", Namespace: "clusters-test-cluster", @@ -223,10 +223,10 @@ func TestSetNodesInfoStatus(t *testing.T) { hyperv1.NodePoolReleaseVersionAnnotation: "4.18.12", }, }, - Status: v1beta1.MachineStatus{ + Status: capiv1.MachineStatus{ NodeInfo: &corev1.NodeSystemInfo{KubeletVersion: "v1.31.4"}, - Conditions: v1beta1.Conditions{ - {Type: v1beta1.MachineNodeHealthyCondition, Status: corev1.ConditionTrue}, + Conditions: []metav1.Condition{ + {Type: capiv1.MachineNodeHealthyCondition, Status: metav1.ConditionTrue}, }, }, }, @@ -252,7 +252,7 @@ func TestSetNodesInfoStatus(t *testing.T) { { name: "When all machines lack NodeInfo it should clear previously set NodesInfo", machines: []client.Object{ - &v1beta1.Machine{ + &capiv1.Machine{ ObjectMeta: metav1.ObjectMeta{ Name: "m1", Namespace: "clusters-test-cluster", @@ -260,7 +260,7 @@ func TestSetNodesInfoStatus(t *testing.T) { nodePoolAnnotation: "clusters/test-nodepool", }, }, - Status: v1beta1.MachineStatus{}, + Status: capiv1.MachineStatus{}, }, }, nodePool: &hyperv1.NodePool{ @@ -303,23 +303,23 @@ func TestSetNodesInfoStatus(t *testing.T) { } } -func machineWithVersionAndHealth(name, kubeletVersion string, healthy bool, annotations map[string]string) *v1beta1.Machine { +func machineWithVersionAndHealth(name, kubeletVersion string, healthy bool, annotations map[string]string) *capiv1.Machine { healthStatus := corev1.ConditionTrue if !healthy { healthStatus = corev1.ConditionFalse } - return machineWithVersionAndConditions(name, kubeletVersion, v1beta1.Conditions{ - {Type: v1beta1.MachineNodeHealthyCondition, Status: healthStatus}, + return machineWithVersionAndConditions(name, kubeletVersion, []metav1.Condition{ + {Type: capiv1.MachineNodeHealthyCondition, Status: metav1.ConditionStatus(healthStatus)}, }, annotations) } -func machineWithVersionAndConditions(name, kubeletVersion string, conditions v1beta1.Conditions, annotations map[string]string) *v1beta1.Machine { - return &v1beta1.Machine{ +func machineWithVersionAndConditions(name, kubeletVersion string, conditions []metav1.Condition, annotations map[string]string) *capiv1.Machine { + return &capiv1.Machine{ ObjectMeta: metav1.ObjectMeta{ Name: name, Annotations: annotations, }, - Status: v1beta1.MachineStatus{ + Status: capiv1.MachineStatus{ NodeInfo: &corev1.NodeSystemInfo{KubeletVersion: kubeletVersion}, Conditions: conditions, }, diff --git a/support/api/capi_types.go b/support/api/capi_types.go index 50b72ab3d39b..4bd9e3f2cf7a 100644 --- a/support/api/capi_types.go +++ b/support/api/capi_types.go @@ -8,7 +8,7 @@ import ( _ "sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2" _ "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1" _ "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" - _ "sigs.k8s.io/cluster-api/api/addons/v1beta1" - _ "sigs.k8s.io/cluster-api/api/v1beta1" - _ "sigs.k8s.io/cluster-api/exp/api/v1beta1" + _ "sigs.k8s.io/cluster-api/api/addons/v1beta2" + _ "sigs.k8s.io/cluster-api/api/core/v1beta2" + _ "sigs.k8s.io/cluster-api/api/ipam/v1beta2" ) diff --git a/support/api/scheme.go b/support/api/scheme.go index 0d19f8ecb539..f8596dd637d2 100644 --- a/support/api/scheme.go +++ b/support/api/scheme.go @@ -51,8 +51,9 @@ import ( capikubevirt "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" capiopenstackv1alpha1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1" capiopenstackv1beta1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" - ipamv1 "sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1" + capiaddonsv1beta2 "sigs.k8s.io/cluster-api/api/addons/v1beta2" + capiv1beta2 "sigs.k8s.io/cluster-api/api/core/v1beta2" + ipamv1beta2 "sigs.k8s.io/cluster-api/api/ipam/v1beta2" karpenterapis "sigs.k8s.io/karpenter/pkg/apis" karpenterv1 "sigs.k8s.io/karpenter/pkg/apis/v1" secretsstorev1 "sigs.k8s.io/secrets-store-csi-driver/apis/v1" @@ -113,8 +114,9 @@ func init() { _ = schedulingv1alpha1.AddToScheme(scheme) _ = auditlogpersistencev1alpha1.AddToScheme(scheme) _ = certificatesv1alpha1.AddToScheme(scheme) - _ = capiv1.AddToScheme(scheme) - _ = ipamv1.AddToScheme(scheme) + _ = capiv1beta2.AddToScheme(scheme) + _ = ipamv1beta2.AddToScheme(scheme) + _ = capiaddonsv1beta2.AddToScheme(scheme) _ = configv1.AddToScheme(scheme) _ = securityv1.AddToScheme(scheme) _ = operatorv1.AddToScheme(scheme) diff --git a/support/upsert/upsert.go b/support/upsert/upsert.go index 0af51813edd4..50743fb632b1 100644 --- a/support/upsert/upsert.go +++ b/support/upsert/upsert.go @@ -22,7 +22,7 @@ import ( capigcp "sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1" capiibmv1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" capikubevirt "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" crclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" ) diff --git a/support/util/resources.go b/support/util/resources.go index 44004c15c5aa..592d60e971bf 100644 --- a/support/util/resources.go +++ b/support/util/resources.go @@ -14,7 +14,7 @@ import ( capiibmv1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" capikubevirt "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" capiopenstackv1beta1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" secretsstorev1 "sigs.k8s.io/secrets-store-csi-driver/apis/v1" ) diff --git a/test/e2e/autoscaling_test.go b/test/e2e/autoscaling_test.go index 481dfb7bc3b9..d3ab79e989f9 100644 --- a/test/e2e/autoscaling_test.go +++ b/test/e2e/autoscaling_test.go @@ -22,7 +22,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/util/retry" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -467,10 +468,13 @@ func testScaleFromZero(ctx context.Context, mgtClient crclient.Client, hostedClu g.Expect(err).NotTo(HaveOccurred(), "failed to create scale-from-zero nodepool") t.Logf("Created NodePool %s with autoscaling min=0, max=2", scaleFromZeroNP.Name) - // Verify MachineDeployment has capacity annotations - t.Log("Verifying MachineDeployment has capacity annotations") + // Verify capacity information is available either via Status.Capacity (CAPI 1.11+) + // or via annotations (pre-CAPI 1.11) + t.Log("Verifying scale-from-zero capacity information is available") md := &capiv1.MachineDeployment{} - e2eutil.EventuallyObject(t, ctx, "MachineDeployment to have capacity annotations", + var hasNativeCapacity bool + var capacitySource string + e2eutil.EventuallyObject(t, ctx, "MachineDeployment to have capacity information", func(ctx context.Context) (*capiv1.MachineDeployment, error) { // MachineDeployment is in the hosted cluster namespace with same name as NodePool err := mgtClient.Get(ctx, crclient.ObjectKey{ @@ -481,11 +485,43 @@ func testScaleFromZero(ctx context.Context, mgtClient crclient.Client, hostedClu }, []e2eutil.Predicate[*capiv1.MachineDeployment]{ func(md *capiv1.MachineDeployment) (done bool, reasons string, err error) { + // Check if we have a valid infrastructure reference + if md.Spec.Template.Spec.InfrastructureRef.Name == "" { + return false, "MachineDeployment missing infrastructureRef", nil + } + + // Get the AWSMachineTemplate to check for Status.Capacity + awsMachineTemplate := &capiaws.AWSMachineTemplate{} + err = mgtClient.Get(ctx, crclient.ObjectKey{ + Namespace: md.Namespace, + Name: md.Spec.Template.Spec.InfrastructureRef.Name, + }, awsMachineTemplate) + if err != nil { + return false, fmt.Sprintf("failed to get AWSMachineTemplate: %v", err), err + } + + // Check for native Status.Capacity (CAPI 1.11+) + if len(awsMachineTemplate.Status.Capacity) > 0 { + t.Logf("Found native Status.Capacity on AWSMachineTemplate %s", awsMachineTemplate.Name) + // Validate required capacity fields + if _, ok := awsMachineTemplate.Status.Capacity[corev1.ResourceCPU]; !ok { + return false, "Status.Capacity missing CPU", nil + } + if _, ok := awsMachineTemplate.Status.Capacity[corev1.ResourceMemory]; !ok { + return false, "Status.Capacity missing Memory", nil + } + hasNativeCapacity = true + capacitySource = "Status.Capacity" + return true, "native Status.Capacity present with CPU and Memory", nil + } + + // Fall back to checking annotations (pre-CAPI 1.11) + t.Logf("No Status.Capacity found, checking for workaround annotations on MachineDeployment") if _, ok := md.Annotations["machine.openshift.io/vCPU"]; !ok { - return false, "missing vCPU annotation", nil + return false, "missing both Status.Capacity and vCPU annotation", nil } if _, ok := md.Annotations["machine.openshift.io/memoryMb"]; !ok { - return false, "missing memoryMb annotation", nil + return false, "missing both Status.Capacity and memoryMb annotation", nil } // GPU annotation is optional - only set when instance type has GPUs labels, ok := md.Annotations["capacity.cluster-autoscaler.kubernetes.io/labels"] @@ -495,20 +531,44 @@ func testScaleFromZero(ctx context.Context, mgtClient crclient.Client, hostedClu if !strings.Contains(labels, "kubernetes.io/arch=") { return false, "capacity labels missing architecture", nil } + hasNativeCapacity = false + capacitySource = "annotations" return true, "all capacity annotations present", nil }, }, e2eutil.WithTimeout(5*time.Minute), ) - gpuValue := md.Annotations["machine.openshift.io/GPU"] - if gpuValue == "" { - gpuValue = "none (non-GPU instance)" + + // Log capacity information based on source + if hasNativeCapacity { + // Get the AWSMachineTemplate again to display capacity info + awsMachineTemplate := &capiaws.AWSMachineTemplate{} + err = mgtClient.Get(ctx, crclient.ObjectKey{ + Namespace: md.Namespace, + Name: md.Spec.Template.Spec.InfrastructureRef.Name, + }, awsMachineTemplate) + g.Expect(err).NotTo(HaveOccurred(), "failed to get AWSMachineTemplate for logging") + + cpuQty := awsMachineTemplate.Status.Capacity[corev1.ResourceCPU] + memQty := awsMachineTemplate.Status.Capacity[corev1.ResourceMemory] + gpuQty := awsMachineTemplate.Status.Capacity["nvidia.com/gpu"] + t.Logf("Capacity via %s: CPU=%s, Memory=%s, GPU=%s", + capacitySource, + cpuQty.String(), + memQty.String(), + gpuQty.String()) + } else { + gpuValue := md.Annotations["machine.openshift.io/GPU"] + if gpuValue == "" { + gpuValue = "none (non-GPU instance)" + } + t.Logf("Capacity via %s: vCPU=%s, memoryMb=%s, GPU=%s, labels=%s", + capacitySource, + md.Annotations["machine.openshift.io/vCPU"], + md.Annotations["machine.openshift.io/memoryMb"], + gpuValue, + md.Annotations["capacity.cluster-autoscaler.kubernetes.io/labels"]) } - t.Logf("MachineDeployment has capacity annotations: vCPU=%s, memoryMb=%s, GPU=%s, labels=%s", - md.Annotations["machine.openshift.io/vCPU"], - md.Annotations["machine.openshift.io/memoryMb"], - gpuValue, - md.Annotations["capacity.cluster-autoscaler.kubernetes.io/labels"]) // Verify NodePool autoscaling is enabled e2eutil.EventuallyObject(t, ctx, "NodePool autoscaling to be enabled", @@ -574,10 +634,6 @@ func testScaleFromZero(ctx context.Context, mgtClient crclient.Client, hostedClu }, }, }, - // Target only nodes from the scale-from-zero NodePool - NodeSelector: map[string]string{ - "scale-from-zero-test": "true", - }, RestartPolicy: corev1.RestartPolicyNever, }, }, diff --git a/test/e2e/nodepool_day2_tags_test.go b/test/e2e/nodepool_day2_tags_test.go index 2c0a1551cdca..c43eebe5d6b3 100644 --- a/test/e2e/nodepool_day2_tags_test.go +++ b/test/e2e/nodepool_day2_tags_test.go @@ -17,7 +17,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/test/e2e/nodepool_kv_advanced_multinet_test.go b/test/e2e/nodepool_kv_advanced_multinet_test.go index 1e8af94a5ead..4934ced402e5 100644 --- a/test/e2e/nodepool_kv_advanced_multinet_test.go +++ b/test/e2e/nodepool_kv_advanced_multinet_test.go @@ -22,7 +22,7 @@ import ( "k8s.io/utils/ptr" kubevirtv1 "kubevirt.io/api/core/v1" capkv1alpha1 "sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1" - clusterapiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterapiv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/cluster-api/util" "sigs.k8s.io/controller-runtime/pkg/client" crclient "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/test/e2e/nodepool_osp_advanced_test.go b/test/e2e/nodepool_osp_advanced_test.go index 8d85b932b37c..f7b726362ed5 100644 --- a/test/e2e/nodepool_osp_advanced_test.go +++ b/test/e2e/nodepool_osp_advanced_test.go @@ -16,7 +16,7 @@ import ( "k8s.io/utils/ptr" capiopenstackv1alpha1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1" capiopenstackv1beta1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/cluster-api/util" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -167,10 +167,10 @@ func (o OpenStackAdvancedTest) Run(t *testing.T, nodePool hyperv1.NodePool, _ [] }, []e2eutil.Predicate[*capiv1.Machine]{ func(machine *capiv1.Machine) (done bool, reasons string, err error) { - if machine.Spec.FailureDomain == nil { + if machine.Spec.FailureDomain == "" { return false, "Machine does not have a failure domain", nil } - want, got := getAZName(), *machine.Spec.FailureDomain + want, got := getAZName(), machine.Spec.FailureDomain return want == got, fmt.Sprintf("expected Machine to have failure domain %s, got %s", want, got), nil }, }, diff --git a/test/e2e/nodepool_rolling_upgrade_test.go b/test/e2e/nodepool_rolling_upgrade_test.go index 2fb6e871b6dd..6a3e9402c912 100644 --- a/test/e2e/nodepool_rolling_upgrade_test.go +++ b/test/e2e/nodepool_rolling_upgrade_test.go @@ -17,7 +17,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" capiaws "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" capiazure "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/cluster-api/util/labels/format" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/test/e2e/nodepool_spot_termination_handler_test.go b/test/e2e/nodepool_spot_termination_handler_test.go index 448a5f6f4a9a..7e9ee55e71b9 100644 --- a/test/e2e/nodepool_spot_termination_handler_test.go +++ b/test/e2e/nodepool_spot_termination_handler_test.go @@ -20,7 +20,7 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/test/e2e/upgrade_hypershift_operator_test.go b/test/e2e/upgrade_hypershift_operator_test.go index 4fadb87d28db..bf8aca31e9ef 100644 --- a/test/e2e/upgrade_hypershift_operator_test.go +++ b/test/e2e/upgrade_hypershift_operator_test.go @@ -14,7 +14,7 @@ import ( e2eutil "github.com/openshift/hypershift/test/e2e/util" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" - "sigs.k8s.io/cluster-api/api/v1beta1" + "sigs.k8s.io/cluster-api/api/core/v1beta1" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) diff --git a/test/e2e/util/util.go b/test/e2e/util/util.go index f1e117fcaea8..b1daa6460381 100644 --- a/test/e2e/util/util.go +++ b/test/e2e/util/util.go @@ -69,7 +69,7 @@ import ( "k8s.io/client-go/util/retry" "k8s.io/utils/ptr" - capiv1 "sigs.k8s.io/cluster-api/api/v1beta1" + capiv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" crclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/CHANGELOG.md index 7e7bc22c768e..2b4be66e8594 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/CHANGELOG.md @@ -1,5 +1,18 @@ # Release History +## 1.4.0 (2025-06-12) + +### Features Added +* Add fakes support (https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/samples/fakes) + +### Other Changes +* Upgraded to API service version `7.6` + +## 1.4.0-beta.1 (2025-04-09) + +### Other Changes +* Upgraded to API service version `7.6-preview.2` + ## 1.3.1 (2025-02-13) ### Other Changes diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/_metadata.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/_metadata.json new file mode 100644 index 000000000000..a5de6037c9ea --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/_metadata.json @@ -0,0 +1,4 @@ +{ + "apiVersion": "7.6", + "emitterVersion": "0.4.11" +} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/assets.json index f52f6f69bc84..1ad28a6b61d2 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/assets.json +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "go", "TagPrefix": "go/security/keyvault/azsecrets", - "Tag": "go/security/keyvault/azsecrets_f05a21134a" + "Tag": "go/security/keyvault/azsecrets_ac16bf6990" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/client.go index 8ae0185df576..1a0bd5d350cc 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/client.go @@ -29,12 +29,14 @@ type Client struct { // This operation requires the secrets/backup permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the secret. // - options - BackupSecretOptions contains the optional parameters for the Client.BackupSecret method. func (client *Client) BackupSecret(ctx context.Context, name string, options *BackupSecretOptions) (BackupSecretResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.BackupSecret", client.internal.Tracer(), nil) + const operationName = "Client.BackupSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.backupSecretCreateRequest(ctx, name, options) if err != nil { @@ -66,7 +68,7 @@ func (client *Client) backupSecretCreateRequest(ctx context.Context, name string return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -87,12 +89,14 @@ func (client *Client) backupSecretHandleResponse(resp *http.Response) (BackupSec // of a secret. This operation requires the secrets/delete permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the secret. // - options - DeleteSecretOptions contains the optional parameters for the Client.DeleteSecret method. func (client *Client) DeleteSecret(ctx context.Context, name string, options *DeleteSecretOptions) (DeleteSecretResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.DeleteSecret", client.internal.Tracer(), nil) + const operationName = "Client.DeleteSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.deleteSecretCreateRequest(ctx, name, options) if err != nil { @@ -124,7 +128,7 @@ func (client *Client) deleteSecretCreateRequest(ctx context.Context, name string return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -145,12 +149,14 @@ func (client *Client) deleteSecretHandleResponse(resp *http.Response) (DeleteSec // the secrets/get permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the secret. // - options - GetDeletedSecretOptions contains the optional parameters for the Client.GetDeletedSecret method. func (client *Client) GetDeletedSecret(ctx context.Context, name string, options *GetDeletedSecretOptions) (GetDeletedSecretResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.GetDeletedSecret", client.internal.Tracer(), nil) + const operationName = "Client.GetDeletedSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.getDeletedSecretCreateRequest(ctx, name, options) if err != nil { @@ -182,7 +188,7 @@ func (client *Client) getDeletedSecretCreateRequest(ctx context.Context, name st return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -202,14 +208,16 @@ func (client *Client) getDeletedSecretHandleResponse(resp *http.Response) (GetDe // The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the secret. // - version - The version of the secret. This URI fragment is optional. If not specified, the latest version of the secret // is returned. // - options - GetSecretOptions contains the optional parameters for the Client.GetSecret method. func (client *Client) GetSecret(ctx context.Context, name string, version string, options *GetSecretOptions) (GetSecretResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.GetSecret", client.internal.Tracer(), nil) + const operationName = "Client.GetSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.getSecretCreateRequest(ctx, name, version, options) if err != nil { @@ -242,7 +250,7 @@ func (client *Client) getSecretCreateRequest(ctx context.Context, name string, v return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -262,7 +270,7 @@ func (client *Client) getSecretHandleResponse(resp *http.Response) (GetSecretRes // The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. This // operation requires the secrets/list permission. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - options - ListDeletedSecretPropertiesOptions contains the optional parameters for the Client.NewListDeletedSecretPropertiesPager // method. func (client *Client) NewListDeletedSecretPropertiesPager(options *ListDeletedSecretPropertiesOptions) *runtime.Pager[ListDeletedSecretPropertiesResponse] { @@ -271,6 +279,7 @@ func (client *Client) NewListDeletedSecretPropertiesPager(options *ListDeletedSe return page.NextLink != nil && len(*page.NextLink) > 0 }, Fetcher: func(ctx context.Context, page *ListDeletedSecretPropertiesResponse) (ListDeletedSecretPropertiesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListDeletedSecretPropertiesPager") nextLink := "" if page != nil { nextLink = *page.NextLink @@ -288,7 +297,7 @@ func (client *Client) NewListDeletedSecretPropertiesPager(options *ListDeletedSe } // listDeletedSecretPropertiesCreateRequest creates the ListDeletedSecretProperties request. -func (client *Client) listDeletedSecretPropertiesCreateRequest(ctx context.Context, options *ListDeletedSecretPropertiesOptions) (*policy.Request, error) { +func (client *Client) listDeletedSecretPropertiesCreateRequest(ctx context.Context, _ *ListDeletedSecretPropertiesOptions) (*policy.Request, error) { host := "{vaultBaseUrl}" host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/deletedsecrets" @@ -297,7 +306,7 @@ func (client *Client) listDeletedSecretPropertiesCreateRequest(ctx context.Conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -318,7 +327,7 @@ func (client *Client) listDeletedSecretPropertiesHandleResponse(resp *http.Respo // are provided in the response. Individual secret versions are not listed in the response. This operation requires the secrets/list // permission. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - options - ListSecretPropertiesOptions contains the optional parameters for the Client.NewListSecretPropertiesPager method. func (client *Client) NewListSecretPropertiesPager(options *ListSecretPropertiesOptions) *runtime.Pager[ListSecretPropertiesResponse] { return runtime.NewPager(runtime.PagingHandler[ListSecretPropertiesResponse]{ @@ -326,6 +335,7 @@ func (client *Client) NewListSecretPropertiesPager(options *ListSecretProperties return page.NextLink != nil && len(*page.NextLink) > 0 }, Fetcher: func(ctx context.Context, page *ListSecretPropertiesResponse) (ListSecretPropertiesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListSecretPropertiesPager") nextLink := "" if page != nil { nextLink = *page.NextLink @@ -343,7 +353,7 @@ func (client *Client) NewListSecretPropertiesPager(options *ListSecretProperties } // listSecretPropertiesCreateRequest creates the ListSecretProperties request. -func (client *Client) listSecretPropertiesCreateRequest(ctx context.Context, options *ListSecretPropertiesOptions) (*policy.Request, error) { +func (client *Client) listSecretPropertiesCreateRequest(ctx context.Context, _ *ListSecretPropertiesOptions) (*policy.Request, error) { host := "{vaultBaseUrl}" host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/secrets" @@ -352,7 +362,7 @@ func (client *Client) listSecretPropertiesCreateRequest(ctx context.Context, opt return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -372,7 +382,7 @@ func (client *Client) listSecretPropertiesHandleResponse(resp *http.Response) (L // The full secret identifier and attributes are provided in the response. No values are returned for the secrets. This operations // requires the secrets/list permission. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the secret. // - options - ListSecretPropertiesVersionsOptions contains the optional parameters for the Client.NewListSecretPropertiesVersionsPager // method. @@ -382,6 +392,7 @@ func (client *Client) NewListSecretPropertiesVersionsPager(name string, options return page.NextLink != nil && len(*page.NextLink) > 0 }, Fetcher: func(ctx context.Context, page *ListSecretPropertiesVersionsResponse) (ListSecretPropertiesVersionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListSecretPropertiesVersionsPager") nextLink := "" if page != nil { nextLink = *page.NextLink @@ -399,7 +410,7 @@ func (client *Client) NewListSecretPropertiesVersionsPager(name string, options } // listSecretPropertiesVersionsCreateRequest creates the ListSecretPropertiesVersions request. -func (client *Client) listSecretPropertiesVersionsCreateRequest(ctx context.Context, name string, options *ListSecretPropertiesVersionsOptions) (*policy.Request, error) { +func (client *Client) listSecretPropertiesVersionsCreateRequest(ctx context.Context, name string, _ *ListSecretPropertiesVersionsOptions) (*policy.Request, error) { host := "{vaultBaseUrl}" host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/secrets/{secret-name}/versions" @@ -412,7 +423,7 @@ func (client *Client) listSecretPropertiesVersionsCreateRequest(ctx context.Cont return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -433,12 +444,14 @@ func (client *Client) listSecretPropertiesVersionsHandleResponse(resp *http.Resp // can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the secret. // - options - PurgeDeletedSecretOptions contains the optional parameters for the Client.PurgeDeletedSecret method. func (client *Client) PurgeDeletedSecret(ctx context.Context, name string, options *PurgeDeletedSecretOptions) (PurgeDeletedSecretResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.PurgeDeletedSecret", client.internal.Tracer(), nil) + const operationName = "Client.PurgeDeletedSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.purgeDeletedSecretCreateRequest(ctx, name, options) if err != nil { @@ -469,7 +482,7 @@ func (client *Client) purgeDeletedSecretCreateRequest(ctx context.Context, name return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -481,12 +494,14 @@ func (client *Client) purgeDeletedSecretCreateRequest(ctx context.Context, name // This operation requires the secrets/recover permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the deleted secret. // - options - RecoverDeletedSecretOptions contains the optional parameters for the Client.RecoverDeletedSecret method. func (client *Client) RecoverDeletedSecret(ctx context.Context, name string, options *RecoverDeletedSecretOptions) (RecoverDeletedSecretResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.RecoverDeletedSecret", client.internal.Tracer(), nil) + const operationName = "Client.RecoverDeletedSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.recoverDeletedSecretCreateRequest(ctx, name, options) if err != nil { @@ -518,7 +533,7 @@ func (client *Client) recoverDeletedSecretCreateRequest(ctx context.Context, nam return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -538,12 +553,14 @@ func (client *Client) recoverDeletedSecretHandleResponse(resp *http.Response) (R // Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - parameters - The parameters to restore the secret. // - options - RestoreSecretOptions contains the optional parameters for the Client.RestoreSecret method. func (client *Client) RestoreSecret(ctx context.Context, parameters RestoreSecretParameters, options *RestoreSecretOptions) (RestoreSecretResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.RestoreSecret", client.internal.Tracer(), nil) + const operationName = "Client.RestoreSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.restoreSecretCreateRequest(ctx, parameters, options) if err != nil { @@ -571,7 +588,7 @@ func (client *Client) restoreSecretCreateRequest(ctx context.Context, parameters return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} @@ -596,14 +613,16 @@ func (client *Client) restoreSecretHandleResponse(resp *http.Response) (RestoreS // version of that secret. This operation requires the secrets/set permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the secret. The value you provide may be copied globally for the purpose of running the service. The // value provided should not include personally identifiable or sensitive information. // - parameters - The parameters for setting the secret. // - options - SetSecretOptions contains the optional parameters for the Client.SetSecret method. func (client *Client) SetSecret(ctx context.Context, name string, parameters SetSecretParameters, options *SetSecretOptions) (SetSecretResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.SetSecret", client.internal.Tracer(), nil) + const operationName = "Client.SetSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.setSecretCreateRequest(ctx, name, parameters, options) if err != nil { @@ -635,7 +654,7 @@ func (client *Client) setSecretCreateRequest(ctx context.Context, name string, p return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} @@ -660,14 +679,16 @@ func (client *Client) setSecretHandleResponse(resp *http.Response) (SetSecretRes // request are left unchanged. The value of a secret itself cannot be changed. This operation requires the secrets/set permission. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 7.5 +// Generated from API version 7.6 // - name - The name of the secret. // - version - The version of the secret. // - parameters - The parameters for update secret operation. // - options - UpdateSecretPropertiesOptions contains the optional parameters for the Client.UpdateSecretProperties method. func (client *Client) UpdateSecretProperties(ctx context.Context, name string, version string, parameters UpdateSecretPropertiesParameters, options *UpdateSecretPropertiesOptions) (UpdateSecretPropertiesResponse, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, "Client.UpdateSecretProperties", client.internal.Tracer(), nil) + const operationName = "Client.UpdateSecretProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) defer func() { endSpan(err) }() req, err := client.updateSecretPropertiesCreateRequest(ctx, name, version, parameters, options) if err != nil { @@ -700,7 +721,7 @@ func (client *Client) updateSecretPropertiesCreateRequest(ctx context.Context, n return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "7.5") + reqQP.Set("api-version", "7.6") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} req.Raw().Header["Content-Type"] = []string{"application/json"} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/tsp-location.yaml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/tsp-location.yaml index aa3e8767b1a2..c70babed07a9 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/tsp-location.yaml +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/tsp-location.yaml @@ -1,6 +1,5 @@ directory: specification/keyvault/Security.KeyVault.Secrets -commit: 646edc1e47bb0653b995a9cf474cf30255188530 +commit: e4ee008e38fd34b530df834ef8b966835a641b13 repo: Azure/azure-rest-api-specs additionalDirectories: - specification/keyvault/Security.KeyVault.Common/ -# https://github.com/Azure/azure-rest-api-specs/tree/646edc1e47bb0653b995a9cf474cf30255188530/specification/keyvault/Security.KeyVault.Secrets diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/version.go index 02c6b6a3c5dc..0b6ca4900462 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets/version.go @@ -5,5 +5,5 @@ package azsecrets const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets" - version = "v1.3.1" + version = "v1.4.0" ) diff --git a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go index 593b10ab6963..194d5e9c94d3 100644 --- a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go +++ b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go @@ -11,21 +11,13 @@ func (oscState oscStringState) Handle(b byte) (s state, e error) { return nextState, err } - switch { - case isOscStringTerminator(b): + // There are several control characters and sequences which can + // terminate an OSC string. Most of them are handled by the baseState + // handler. The ANSI_BEL character is a special case which behaves as a + // terminator only for an OSC string. + if b == ANSI_BEL { return oscState.parser.ground, nil } return oscState, nil } - -// See below for OSC string terminators for linux -// http://man7.org/linux/man-pages/man4/console_codes.4.html -func isOscStringTerminator(b byte) bool { - - if b == ANSI_BEL || b == 0x5C { - return true - } - - return false -} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-instance.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-instance.go index d45682038f28..e6222e7a17a8 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-instance.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-instance.go @@ -56,7 +56,7 @@ func (f *IBMPIInstanceClient) GetAll() (*models.PVMInstances, error) { func (f *IBMPIInstanceClient) Create(body *models.PVMInstanceCreate) (*models.PVMInstanceList, error) { // Check for satellite differences in this endpoint if f.session.IsOnPrem() && (body.DeploymentTarget != nil || body.DeploymentType != "") { - return nil, fmt.Errorf("deployment target and deployment type parameters are not supported in satellite location") + return nil, fmt.Errorf("deployment target and deployment type parameters are not supported in on-prem location") } params := p_cloud_p_vm_instances.NewPcloudPvminstancesPostParams(). WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut). @@ -105,7 +105,7 @@ func (f *IBMPIInstanceClient) DeleteWithBody(id string, body *models.PVMInstance func (f *IBMPIInstanceClient) Update(id string, body *models.PVMInstanceUpdate) (*models.PVMInstanceUpdateResponse, error) { // Check for satellite differences in this endpoint if f.session.IsOnPrem() && body.SapProfileID != "" { - return nil, fmt.Errorf("sap profile id parameter is not supported in satellite location") + return nil, fmt.Errorf("sap profile id parameter is not supported in on-prem location") } params := p_cloud_p_vm_instances.NewPcloudPvminstancesPutParams(). WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut). diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-network.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-network.go index b8ab8ed41f91..86122fbfd73c 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-network.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-network.go @@ -56,10 +56,6 @@ func (f *IBMPINetworkClient) GetAll() (*models.Networks, error) { // Create a Network func (f *IBMPINetworkClient) Create(body *models.NetworkCreate) (*models.Network, error) { - // Check for satellite differences in this endpoint - if f.session.IsOnPrem() && body.Jumbo { - return nil, fmt.Errorf("jumbo parameter is not supported in satellite location, use mtu instead") - } params := p_cloud_networks.NewPcloudNetworksPostParams(). WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut). WithCloudInstanceID(f.cloudInstanceID).WithBody(body) @@ -199,6 +195,10 @@ func (f *IBMPINetworkClient) UpdatePort(id, networkPortID string, body *models.N // Create a network interface func (f *IBMPINetworkClient) CreateNetworkInterface(id string, body *models.NetworkInterfaceCreate) (*models.NetworkInterface, error) { + // Add check for on-prem location + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } params := networks.NewV1NetworksNetworkInterfacesPostParams().WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut).WithNetworkID(id).WithBody(body) resp, err := f.session.Power.Networks.V1NetworksNetworkInterfacesPost(params, f.session.AuthInfo(f.cloudInstanceID)) if err != nil { @@ -212,6 +212,10 @@ func (f *IBMPINetworkClient) CreateNetworkInterface(id string, body *models.Netw // Get all Create a network interface func (f *IBMPINetworkClient) GetAllNetworkInterfaces(id string) (*models.NetworkInterfaces, error) { + // Add check for on-prem location + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } params := networks.NewV1NetworksNetworkInterfacesGetallParams().WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut).WithNetworkID(id) resp, err := f.session.Power.Networks.V1NetworksNetworkInterfacesGetall(params, f.session.AuthInfo(f.cloudInstanceID)) if err != nil { @@ -225,6 +229,10 @@ func (f *IBMPINetworkClient) GetAllNetworkInterfaces(id string) (*models.Network // Get a network interface func (f *IBMPINetworkClient) GetNetworkInterface(id, netIntID string) (*models.NetworkInterface, error) { + // Add check for on-prem location + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } params := networks.NewV1NetworksNetworkInterfacesGetParams().WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut).WithNetworkID(id).WithNetworkInterfaceID(netIntID) resp, err := f.session.Power.Networks.V1NetworksNetworkInterfacesGet(params, f.session.AuthInfo(f.cloudInstanceID)) if err != nil { @@ -238,6 +246,10 @@ func (f *IBMPINetworkClient) GetNetworkInterface(id, netIntID string) (*models.N // Update a network interface func (f *IBMPINetworkClient) UpdateNetworkInterface(id, netIntID string, body *models.NetworkInterfaceUpdate) (*models.NetworkInterface, error) { + // Add check for on-prem location + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } params := networks.NewV1NetworksNetworkInterfacesPutParams().WithContext(f.ctx).WithTimeout(helpers.PIUpdateTimeOut).WithNetworkID(id).WithNetworkInterfaceID(netIntID).WithBody(body) resp, err := f.session.Power.Networks.V1NetworksNetworkInterfacesPut(params, f.session.AuthInfo(f.cloudInstanceID)) if err != nil { @@ -251,6 +263,10 @@ func (f *IBMPINetworkClient) UpdateNetworkInterface(id, netIntID string, body *m // Delete a network interface func (f *IBMPINetworkClient) DeleteNetworkInterface(id, netIntID string) error { + // Add check for on-prem location + if f.session.IsOnPrem() { + return fmt.Errorf(helpers.NotOnPremSupported) + } params := networks.NewV1NetworksNetworkInterfacesDeleteParams().WithContext(f.ctx).WithTimeout(helpers.PIDeleteTimeOut).WithNetworkID(id).WithNetworkInterfaceID(netIntID) _, err := f.session.Power.Networks.V1NetworksNetworkInterfacesDelete(params, f.session.AuthInfo(f.cloudInstanceID)) if err != nil { diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-routes.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-routes.go new file mode 100644 index 000000000000..811007fb2b22 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-routes.go @@ -0,0 +1,116 @@ +package instance + +import ( + "context" + "fmt" + + "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/ibmpisession" + "github.com/IBM-Cloud/power-go-client/power/client/routes" + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// IBMPIRouteClient +type IBMPIRouteClient struct { + IBMPIClient +} + +// NewIBMPIRouteClient +func NewIBMPIRouteClient(ctx context.Context, sess *ibmpisession.IBMPISession, cloudInstanceID string) *IBMPIRouteClient { + return &IBMPIRouteClient{ + *NewIBMPIClient(ctx, sess, cloudInstanceID), + } +} + +// Get a routing rule +func (f *IBMPIRouteClient) Get(id string) (*models.Route, error) { + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } + params := routes.NewV1RoutesGetParams().WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut).WithRouteID(id) + resp, err := f.session.Power.Routes.V1RoutesGet(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf("failed to get route %s: %w", id, err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to get route %s", id) + } + return resp.Payload, nil +} + +// Get all routes +func (f *IBMPIRouteClient) GetAll() (*models.Routes, error) { + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } + params := routes.NewV1RoutesGetallParams().WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut) + resp, err := f.session.Power.Routes.V1RoutesGetall(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf("failed to get all routes for cloud instance %s with: %w", f.cloudInstanceID, err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to get all routes for cloud instance %s", f.cloudInstanceID) + } + return resp.Payload, nil +} + +// Get route report +func (f *IBMPIRouteClient) GetRouteReport() (*models.RouteReport, error) { + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } + params := routes.NewV1RoutesReportGetParams().WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut) + resp, err := f.session.Power.Routes.V1RoutesReportGet(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf("failed to get route report: %w", err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to get route report for cloud instance %s", f.cloudInstanceID) + } + return resp.Payload, nil +} + +// Create a routing rule +func (f *IBMPIRouteClient) Create(body *models.RouteCreate) (*models.Route, error) { + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } + params := routes.NewV1RoutesPostParams().WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut).WithBody(body) + resp, err := f.session.Power.Routes.V1RoutesPost(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf("failed to create route: %s", err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to create route") + } + return resp.Payload, nil +} + +// Update routing rule +func (f *IBMPIRouteClient) Update(id string, body *models.RouteUpdate) (*models.Route, error) { + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } + params := routes.NewV1RoutesPutParams().WithContext(f.ctx).WithTimeout(helpers.PIUpdateTimeOut).WithRouteID(id).WithBody(body) + resp, err := f.session.Power.Routes.V1RoutesPut(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf("failed to update route %s: %w", id, err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to update route %s", id) + } + return resp.Payload, nil +} + +// Delete routing rule +func (f *IBMPIRouteClient) Delete(id string) error { + if f.session.IsOnPrem() { + return fmt.Errorf(helpers.NotOnPremSupported) + } + params := routes.NewV1RoutesDeleteParams().WithContext(f.ctx).WithTimeout(helpers.PIDeleteTimeOut).WithRouteID(id) + _, err := f.session.Power.Routes.V1RoutesDelete(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return fmt.Errorf("failed to delete route %s: %w", id, err) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-sap-instance.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-sap-instance.go index 33b608ab3c69..5f12548a657e 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-sap-instance.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-sap-instance.go @@ -81,3 +81,27 @@ func (f *IBMPISAPInstanceClient) GetAllSAPProfiles(cloudInstanceID string) (*mod } return resp.Payload, nil } + +// Get All SAP Profiles with filters +func (f *IBMPISAPInstanceClient) GetAllSAPProfilesWithFilters(cloudInstanceID string, filterMap map[string]string) (*models.SAPProfiles, error) { + if f.session.IsOnPrem() { + return nil, fmt.Errorf(helpers.NotOnPremSupported) + } + + familyFilter := filterMap[helpers.PISAPProfileFamilyFilterMapKey] + prefixFilter := filterMap[helpers.PISAPProfilePrefixFilterMapKey] + + params := p_cloud_s_a_p.NewPcloudSapGetallParams(). + WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut). + WithCloudInstanceID(f.cloudInstanceID).WithProfilePrefix(&prefixFilter). + WithProfileFamily(&familyFilter) + + resp, err := f.session.Power.PCloudsap.PcloudSapGetall(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf("failed to get all sap profiles for power instance %s: %w", cloudInstanceID, err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to get all sap profiles for power instance %s", cloudInstanceID) + } + return resp.Payload, nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-shared-processor-pool.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-shared-processor-pool.go index aa715fba77f7..df5ee1db39cd 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-shared-processor-pool.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-shared-processor-pool.go @@ -57,7 +57,7 @@ func (f *IBMPISharedProcessorPoolClient) GetAll() (*models.SharedProcessorPools, func (f *IBMPISharedProcessorPoolClient) Create(body *models.SharedProcessorPoolCreate) (*models.SharedProcessorPool, error) { // Check for satellite differences in this endpoint if f.session.IsOnPrem() && body.HostID != "" { - return nil, fmt.Errorf("host id parameter is not supported in satellite location, check documentation") + return nil, fmt.Errorf("host id parameter is not supported in on-prem location") } params := p_cloud_shared_processor_pools.NewPcloudSharedprocessorpoolsPostParams(). WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut). diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-ssh-key.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-ssh-key.go new file mode 100644 index 000000000000..5fad9e4b6162 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-ssh-key.go @@ -0,0 +1,98 @@ +package instance + +import ( + "context" + "fmt" + + "github.com/IBM-Cloud/power-go-client/errors" + "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/ibmpisession" + "github.com/IBM-Cloud/power-go-client/power/client/ssh_keys" + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// IBMPISSHKeyClient +type IBMPISSHKeyClient struct { + IBMPIClient +} + +// NewIBMPISSHKeyClient +func NewIBMPISSHKeyClient(ctx context.Context, sess *ibmpisession.IBMPISession, cloudInstanceID string) *IBMPISSHKeyClient { + return &IBMPISSHKeyClient{ + *NewIBMPIClient(ctx, sess, cloudInstanceID), + } +} + +// Get a SSH Key +func (f *IBMPISSHKeyClient) Get(id string) (*models.WorkspaceSSHKey, error) { + params := ssh_keys.NewV1SshkeysGetParams(). + WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut). + WithSshkeyID(id) + + resp, err := f.session.Power.SSHKeys.V1SshkeysGet(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf(errors.GetPISSHKeyOperationFailed, id, err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to Get PI SSH Key %s", id) + } + return resp.Payload, nil +} + +// Get All SSH Keys +func (f *IBMPISSHKeyClient) GetAll() (*models.WorkspaceSSHKeys, error) { + params := ssh_keys.NewV1SshkeysGetallParams(). + WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut) + + resp, err := f.session.Power.SSHKeys.V1SshkeysGetall(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf(errors.GetAllPISSHKeyOperationFailed, err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to Get all PI SSH Keys") + } + return resp.Payload, nil +} + +// Create a SSH Key +func (f *IBMPISSHKeyClient) Create(body *models.CreateWorkspaceSSHKey) (*models.WorkspaceSSHKey, error) { + params := ssh_keys.NewV1SshkeysPostParams(). + WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut). + WithBody(body) + resp, err := f.session.Power.SSHKeys.V1SshkeysPost(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf(errors.CreatePISSHKeyOperationFailed, err)) + } + if resp != nil && resp.Payload != nil { + return resp.Payload, nil + } + return nil, fmt.Errorf("failed to Create PI SSH Key") +} + +// Delete a SSH Key +func (f *IBMPISSHKeyClient) Delete(id string) error { + params := ssh_keys.NewV1SshkeysDeleteParams(). + WithContext(f.ctx).WithTimeout(helpers.PIDeleteTimeOut). + WithSshkeyID(id) + _, err := f.session.Power.SSHKeys.V1SshkeysDelete(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return fmt.Errorf(errors.DeletePISSHKeyOperationFailed, id, err) + } + return nil +} + +// Update an SSH Key +func (f *IBMPISSHKeyClient) Update(id string, body *models.UpdateWorkspaceSSHKey) (*models.WorkspaceSSHKey, error) { + params := ssh_keys.NewV1SshkeysPutParams(). + WithContext(f.ctx).WithTimeout(helpers.PIUpdateTimeOut). + WithSshkeyID(id).WithBody(body) + + resp, err := f.session.Power.SSHKeys.V1SshkeysPut(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf(errors.UpdatePISSHKeyOperationFailed, id, err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to update ssh key %s", id) + } + return resp.Payload, nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-virtual-serial-number.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-virtual-serial-number.go index 526d6a84d463..c4b4fdd29fa3 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-virtual-serial-number.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-virtual-serial-number.go @@ -54,7 +54,21 @@ func (f *IBMPIVSNClient) GetAll(pvmInstanceID *string) (models.VirtualSerialNumb return resp.Payload, nil } -// Update Virtual Serial Nunber +// Get All Supported IBMi Software Tiers +func (f *IBMPIVSNClient) GetAllSoftwareTiers() (models.SupportedSoftwareTierList, error) { + params := p_cloud_virtual_serial_number.NewPcloudVirtualserialnumberSoftwaretiersGetallParams(). + WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut) + resp, err := f.session.Power.PCloudVirtualSerialNumber.PcloudVirtualserialnumberSoftwaretiersGetall(params, f.session.AuthInfo(f.cloudInstanceID)) + if err != nil { + return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf("failed to get all supported IBMi software tiers in %s :%w", f.cloudInstanceID, err)) + } + if resp == nil || resp.Payload == nil { + return nil, fmt.Errorf("failed to get all supported IBMi software tiers in %s", f.cloudInstanceID) + } + return resp.Payload, nil +} + +// Update Virtual Serial Number func (f *IBMPIVSNClient) Update(id string, body *models.UpdateVirtualSerialNumber) (*models.GetServerVirtualSerialNumber, error) { params := p_cloud_virtual_serial_number.NewPcloudVirtualserialnumberPutParams(). WithContext(f.ctx).WithTimeout(helpers.PIUpdateTimeOut).WithVirtualSerialNumber(id). @@ -98,14 +112,17 @@ func (f *IBMPIVSNClient) PVMInstanceUpdateVSN(pvmInstanceID string, body *models params := p_cloud_virtual_serial_number.NewPcloudPvminstancesVirtualserialnumberPutParams(). WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut).WithCloudInstanceID(f.cloudInstanceID). WithPvmInstanceID(pvmInstanceID).WithBody(body) - resp, err := f.session.Power.PCloudVirtualSerialNumber.PcloudPvminstancesVirtualserialnumberPut(params, f.session.AuthInfo(f.cloudInstanceID)) + respOk, respAccepted, err := f.session.Power.PCloudVirtualSerialNumber.PcloudPvminstancesVirtualserialnumberPut(params, f.session.AuthInfo(f.cloudInstanceID)) if err != nil { return nil, ibmpisession.SDKFailWithAPIError(err, fmt.Errorf("failed to update virtual serial number for pvm instance %s :%w", pvmInstanceID, err)) } - if resp == nil || resp.Payload == nil { - return nil, fmt.Errorf("failed to update virtual serial number for pvm instance %s", pvmInstanceID) + if respOk != nil && respOk.Payload != nil { + return respOk.Payload, nil } - return resp.Payload, nil + if respAccepted != nil && respAccepted.Payload != nil { + return respAccepted.Payload, nil + } + return nil, fmt.Errorf("failed to update virtual serial number for pvm instance %s", pvmInstanceID) } // PVM Attach VSN diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-vpn-policy.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-vpn-policy.go index 9c94ecfe54d7..9013b3e559f6 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-vpn-policy.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-vpn-policy.go @@ -24,7 +24,7 @@ func NewIBMPIVpnPolicyClient(ctx context.Context, sess *ibmpisession.IBMPISessio } // IKE Policies -// Get an IKE Policy +// Deprecated Get an IKE Policy func (f *IBMPIVpnPolicyClient) GetIKEPolicy(id string) (*models.IKEPolicy, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -42,7 +42,7 @@ func (f *IBMPIVpnPolicyClient) GetIKEPolicy(id string) (*models.IKEPolicy, error return resp.Payload, nil } -// Create an IKE Policy +// Deprecated Create an IKE Policy func (f *IBMPIVpnPolicyClient) CreateIKEPolicy(body *models.IKEPolicyCreate) (*models.IKEPolicy, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -60,7 +60,7 @@ func (f *IBMPIVpnPolicyClient) CreateIKEPolicy(body *models.IKEPolicyCreate) (*m return nil, fmt.Errorf("failed to Create VPN Policy") } -// Update an IKE Policy +// Deprecated Update an IKE Policy func (f *IBMPIVpnPolicyClient) UpdateIKEPolicy(id string, body *models.IKEPolicyUpdate) (*models.IKEPolicy, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -79,7 +79,7 @@ func (f *IBMPIVpnPolicyClient) UpdateIKEPolicy(id string, body *models.IKEPolicy return nil, fmt.Errorf("failed to Update VPN Policy") } -// Get All IKE Policies +// Deprecated Get All IKE Policies func (f *IBMPIVpnPolicyClient) GetAllIKEPolicies() (*models.IKEPolicies, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -97,7 +97,7 @@ func (f *IBMPIVpnPolicyClient) GetAllIKEPolicies() (*models.IKEPolicies, error) return resp.Payload, nil } -// Delete an IKE Policy +// Deprecated Delete an IKE Policy func (f *IBMPIVpnPolicyClient) DeleteIKEPolicy(id string) error { if f.session.IsOnPrem() { return fmt.Errorf(helpers.NotOnPremSupported) @@ -113,7 +113,7 @@ func (f *IBMPIVpnPolicyClient) DeleteIKEPolicy(id string) error { } // IPSec Policies -// Get an IPSec Policy +// Deprecated Get an IPSec Policy func (f *IBMPIVpnPolicyClient) GetIPSecPolicy(id string) (*models.IPSecPolicy, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -131,7 +131,7 @@ func (f *IBMPIVpnPolicyClient) GetIPSecPolicy(id string) (*models.IPSecPolicy, e return resp.Payload, nil } -// Create an IPSec Policy +// Deprecated Create an IPSec Policy func (f *IBMPIVpnPolicyClient) CreateIPSecPolicy(body *models.IPSecPolicyCreate) (*models.IPSecPolicy, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -149,7 +149,7 @@ func (f *IBMPIVpnPolicyClient) CreateIPSecPolicy(body *models.IPSecPolicyCreate) return nil, fmt.Errorf("failed to Create VPN Policy") } -// Update an IPSec Policy +// Deprecated Update an IPSec Policy func (f *IBMPIVpnPolicyClient) UpdateIPSecPolicy(id string, body *models.IPSecPolicyUpdate) (*models.IPSecPolicy, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -168,7 +168,7 @@ func (f *IBMPIVpnPolicyClient) UpdateIPSecPolicy(id string, body *models.IPSecPo return nil, fmt.Errorf("failed to Update VPN Policy") } -// Get All IPSec Policies +// Deprecated Get All IPSec Policies func (f *IBMPIVpnPolicyClient) GetAllIPSecPolicies() (*models.IPSecPolicies, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -186,7 +186,7 @@ func (f *IBMPIVpnPolicyClient) GetAllIPSecPolicies() (*models.IPSecPolicies, err return resp.Payload, nil } -// Delete an IPSec Policy +// Deprecated Delete an IPSec Policy func (f *IBMPIVpnPolicyClient) DeleteIPSecPolicy(id string) error { if f.session.IsOnPrem() { return fmt.Errorf(helpers.NotOnPremSupported) diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-vpn.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-vpn.go index 0cdeae2e2981..f9b2a9c36beb 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-vpn.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-vpn.go @@ -23,7 +23,7 @@ func NewIBMPIVpnConnectionClient(ctx context.Context, sess *ibmpisession.IBMPISe } } -// Get a VPN Connection +// Deprecated Get a VPN Connection func (f *IBMPIVpnConnectionClient) Get(id string) (*models.VPNConnection, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -41,12 +41,12 @@ func (f *IBMPIVpnConnectionClient) Get(id string) (*models.VPNConnection, error) return resp.Payload, nil } -// Create a VPN Connection +// Deprecated Create a VPN Connection func (f *IBMPIVpnConnectionClient) Create(body *models.VPNConnectionCreate) (*models.VPNConnectionCreateResponse, error) { return nil, fmt.Errorf("Create VPN Connection is no longer supported") } -// Update a VPN Connection +// Deprecated Update a VPN Connection func (f *IBMPIVpnConnectionClient) Update(id string, body *models.VPNConnectionUpdate) (*models.VPNConnection, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -65,7 +65,7 @@ func (f *IBMPIVpnConnectionClient) Update(id string, body *models.VPNConnectionU return nil, fmt.Errorf("failed to Update VPN Connection %s", id) } -// Get All VPN Connections +// Deprecated Get All VPN Connections func (f *IBMPIVpnConnectionClient) GetAll() (*models.VPNConnections, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -83,7 +83,7 @@ func (f *IBMPIVpnConnectionClient) GetAll() (*models.VPNConnections, error) { return resp.Payload, nil } -// Delete a VPN Connection +// Deprecated Delete a VPN Connection func (f *IBMPIVpnConnectionClient) Delete(id string) (*models.JobReference, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -101,7 +101,7 @@ func (f *IBMPIVpnConnectionClient) Delete(id string) (*models.JobReference, erro return nil, nil } -// Get a VPN Connection's Network +// Deprecated Get a VPN Connection's Network func (f *IBMPIVpnConnectionClient) GetNetwork(id string) (*models.NetworkIDs, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -119,7 +119,7 @@ func (f *IBMPIVpnConnectionClient) GetNetwork(id string) (*models.NetworkIDs, er return resp.Payload, nil } -// Attach a Network to a VPN Connection +// Deprecated Attach a Network to a VPN Connection func (f *IBMPIVpnConnectionClient) AddNetwork(id, networkID string) (*models.JobReference, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -138,7 +138,7 @@ func (f *IBMPIVpnConnectionClient) AddNetwork(id, networkID string) (*models.Job return nil, nil } -// Detach a Network from a VPN Connection +// Deprecated Detach a Network from a VPN Connection func (f *IBMPIVpnConnectionClient) DeleteNetwork(id, networkID string) (*models.JobReference, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -157,7 +157,7 @@ func (f *IBMPIVpnConnectionClient) DeleteNetwork(id, networkID string) (*models. return nil, nil } -// Get a VPN Connection's Subnet +// Deprecated Get a VPN Connection's Subnet func (f *IBMPIVpnConnectionClient) GetSubnet(id string) (*models.PeerSubnets, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -175,7 +175,7 @@ func (f *IBMPIVpnConnectionClient) GetSubnet(id string) (*models.PeerSubnets, er return resp.Payload, nil } -// Attach a Subnet to a VPN Connection +// Deprecated Attach a Subnet to a VPN Connection func (f *IBMPIVpnConnectionClient) AddSubnet(id, subnet string) (*models.PeerSubnets, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) @@ -194,7 +194,7 @@ func (f *IBMPIVpnConnectionClient) AddSubnet(id, subnet string) (*models.PeerSub return resp.Payload, nil } -// Detach a Subnet from a VPN Connection +// Deprecated Detach a Subnet from a VPN Connection func (f *IBMPIVpnConnectionClient) DeleteSubnet(id, subnet string) (*models.PeerSubnets, error) { if f.session.IsOnPrem() { return nil, fmt.Errorf(helpers.NotOnPremSupported) diff --git a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-workspaces.go b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-workspaces.go index 4db8206dee22..137911c23ba2 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-workspaces.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/clients/instance/ibm-pi-workspaces.go @@ -92,7 +92,7 @@ func (f *IBMPIWorkspacesClient) Create(name, location, groupID, plan string) (*r return workspace, response, nil } -// Create a workspace wiht parmas +// Create a workspace with parameters func (f *IBMPIWorkspacesClient) CreateV2(name, location, groupID, plan string, parameters map[string]interface{}) (*resourcecontrollerv2.ResourceInstance, *core.DetailedResponse, error) { resourceController, err := ibmpisession.CreateResourceControllerV2(f.session.Options.URL, f.session.Options.Authenticator) if err != nil { diff --git a/vendor/github.com/IBM-Cloud/power-go-client/errors/errors.go b/vendor/github.com/IBM-Cloud/power-go-client/errors/errors.go index 6c9fcbfec3d7..815685256486 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/errors/errors.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/errors/errors.go @@ -99,6 +99,13 @@ const GetPIKeyOperationFailed = "failed to Get PI Key %s with error %w" const CreatePIKeyOperationFailed = "failed to Create PI Key with error %w" const DeletePIKeyOperationFailed = "failed to Delete PI Key %s with error %w" +// start of PI ssh Key Messages +const GetAllPISSHKeyOperationFailed = "failed to Get PI SSH Keys with error %w" +const GetPISSHKeyOperationFailed = "failed to Get PI SSH Key %s with error %w" +const CreatePISSHKeyOperationFailed = "failed to Create PI SSH Key with error %w" +const DeletePISSHKeyOperationFailed = "failed to Delete PI SSH Key %s with error %w" +const UpdatePISSHKeyOperationFailed = "failed to Update PI SSH Key %s with error %w" + // start of Volume Groups const GetVolumeGroupOperationFailed = "failed to Get volume-group %s for the cloud instance %s with error %w" const GetVolumeGroupDetailsOperationFailed = "failed to Get volume-group %s details for the cloud instance %s with error %w" diff --git a/vendor/github.com/IBM-Cloud/power-go-client/helpers/constants.go b/vendor/github.com/IBM-Cloud/power-go-client/helpers/constants.go index c0fd80027369..cd242fd8e6ca 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/helpers/constants.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/helpers/constants.go @@ -76,9 +76,11 @@ const ( PISAPProfile = "pi_sap_profile" PISAPProfileMemory = "pi_sap_profile_memory" //#nosec G101 - PISAPProfileCertified = "pi_sap_profile_certified" - PISAPProfileType = "pi_sap_profile_type" - PISAPProfileCores = "pi_sap_profile_cores" + PISAPProfileCertified = "pi_sap_profile_certified" + PISAPProfileType = "pi_sap_profile_type" + PISAPProfileCores = "pi_sap_profile_cores" + PISAPProfileFamilyFilterMapKey = "pi_family_filter" + PISAPProfilePrefixFilterMapKey = "pi_prefix_filter" // IBM PI Clone Volume PIVolumeCloneStatus = "pi_volume_clone_status" diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_s_a_p/pcloud_sap_getall_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_s_a_p/pcloud_sap_getall_parameters.go index 108da8cd62a1..473e62687ea0 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_s_a_p/pcloud_sap_getall_parameters.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_s_a_p/pcloud_sap_getall_parameters.go @@ -67,6 +67,18 @@ type PcloudSapGetallParams struct { */ CloudInstanceID string + /* ProfileFamily. + + SAP profile family to filter by + */ + ProfileFamily *string + + /* ProfilePrefix. + + SAP profile prefix to filter by + */ + ProfilePrefix *string + timeout time.Duration Context context.Context HTTPClient *http.Client @@ -131,6 +143,28 @@ func (o *PcloudSapGetallParams) SetCloudInstanceID(cloudInstanceID string) { o.CloudInstanceID = cloudInstanceID } +// WithProfileFamily adds the profileFamily to the pcloud sap getall params +func (o *PcloudSapGetallParams) WithProfileFamily(profileFamily *string) *PcloudSapGetallParams { + o.SetProfileFamily(profileFamily) + return o +} + +// SetProfileFamily adds the profileFamily to the pcloud sap getall params +func (o *PcloudSapGetallParams) SetProfileFamily(profileFamily *string) { + o.ProfileFamily = profileFamily +} + +// WithProfilePrefix adds the profilePrefix to the pcloud sap getall params +func (o *PcloudSapGetallParams) WithProfilePrefix(profilePrefix *string) *PcloudSapGetallParams { + o.SetProfilePrefix(profilePrefix) + return o +} + +// SetProfilePrefix adds the profilePrefix to the pcloud sap getall params +func (o *PcloudSapGetallParams) SetProfilePrefix(profilePrefix *string) { + o.ProfilePrefix = profilePrefix +} + // WriteToRequest writes these params to a swagger request func (o *PcloudSapGetallParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { @@ -144,6 +178,40 @@ func (o *PcloudSapGetallParams) WriteToRequest(r runtime.ClientRequest, reg strf return err } + if o.ProfileFamily != nil { + + // query param profile_family + var qrProfileFamily string + + if o.ProfileFamily != nil { + qrProfileFamily = *o.ProfileFamily + } + qProfileFamily := qrProfileFamily + if qProfileFamily != "" { + + if err := r.SetQueryParam("profile_family", qProfileFamily); err != nil { + return err + } + } + } + + if o.ProfilePrefix != nil { + + // query param profile_prefix + var qrProfilePrefix string + + if o.ProfilePrefix != nil { + qrProfilePrefix = *o.ProfilePrefix + } + qProfilePrefix := qrProfilePrefix + if qProfilePrefix != "" { + + if err := r.SetQueryParam("profile_prefix", qProfilePrefix); err != nil { + return err + } + } + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/p_cloud_virtual_serial_number_client.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/p_cloud_virtual_serial_number_client.go index 709da60fe9ff..95dc5cfec524 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/p_cloud_virtual_serial_number_client.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/p_cloud_virtual_serial_number_client.go @@ -62,7 +62,7 @@ type ClientService interface { PcloudPvminstancesVirtualserialnumberPost(params *PcloudPvminstancesVirtualserialnumberPostParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudPvminstancesVirtualserialnumberPostAccepted, error) - PcloudPvminstancesVirtualserialnumberPut(params *PcloudPvminstancesVirtualserialnumberPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudPvminstancesVirtualserialnumberPutOK, error) + PcloudPvminstancesVirtualserialnumberPut(params *PcloudPvminstancesVirtualserialnumberPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudPvminstancesVirtualserialnumberPutOK, *PcloudPvminstancesVirtualserialnumberPutAccepted, error) PcloudVirtualserialnumberDelete(params *PcloudVirtualserialnumberDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudVirtualserialnumberDeleteOK, error) @@ -72,6 +72,8 @@ type ClientService interface { PcloudVirtualserialnumberPut(params *PcloudVirtualserialnumberPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudVirtualserialnumberPutOK, error) + PcloudVirtualserialnumberSoftwaretiersGetall(params *PcloudVirtualserialnumberSoftwaretiersGetallParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudVirtualserialnumberSoftwaretiersGetallOK, error) + SetTransport(transport runtime.ClientTransport) } @@ -193,9 +195,9 @@ func (a *Client) PcloudPvminstancesVirtualserialnumberPost(params *PcloudPvminst } /* -PcloudPvminstancesVirtualserialnumberPut updates description of a virtual serial number +PcloudPvminstancesVirtualserialnumberPut updates a virtual serial number */ -func (a *Client) PcloudPvminstancesVirtualserialnumberPut(params *PcloudPvminstancesVirtualserialnumberPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudPvminstancesVirtualserialnumberPutOK, error) { +func (a *Client) PcloudPvminstancesVirtualserialnumberPut(params *PcloudPvminstancesVirtualserialnumberPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudPvminstancesVirtualserialnumberPutOK, *PcloudPvminstancesVirtualserialnumberPutAccepted, error) { // TODO: Validate the params before sending if params == nil { params = NewPcloudPvminstancesVirtualserialnumberPutParams() @@ -219,15 +221,16 @@ func (a *Client) PcloudPvminstancesVirtualserialnumberPut(params *PcloudPvminsta result, err := a.transport.Submit(op) if err != nil { - return nil, err + return nil, nil, err } - success, ok := result.(*PcloudPvminstancesVirtualserialnumberPutOK) - if ok { - return success, nil + switch value := result.(type) { + case *PcloudPvminstancesVirtualserialnumberPutOK: + return value, nil, nil + case *PcloudPvminstancesVirtualserialnumberPutAccepted: + return nil, value, nil } - // unexpected success response // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue - msg := fmt.Sprintf("unexpected success response for pcloud.pvminstances.virtualserialnumber.put: API contract not enforced by server. Client expected to get an error, but got: %T", result) + msg := fmt.Sprintf("unexpected success response for p_cloud_virtual_serial_number: API contract not enforced by server. Client expected to get an error, but got: %T", result) panic(msg) } @@ -387,6 +390,45 @@ func (a *Client) PcloudVirtualserialnumberPut(params *PcloudVirtualserialnumberP panic(msg) } +/* +PcloudVirtualserialnumberSoftwaretiersGetall lists supported software tiers i b mi licensing +*/ +func (a *Client) PcloudVirtualserialnumberSoftwaretiersGetall(params *PcloudVirtualserialnumberSoftwaretiersGetallParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PcloudVirtualserialnumberSoftwaretiersGetallOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPcloudVirtualserialnumberSoftwaretiersGetallParams() + } + op := &runtime.ClientOperation{ + ID: "pcloud.virtualserialnumber.softwaretiers.getall", + Method: "GET", + PathPattern: "/v1/virtual-serial-number/software-tiers", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &PcloudVirtualserialnumberSoftwaretiersGetallReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PcloudVirtualserialnumberSoftwaretiersGetallOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for pcloud.virtualserialnumber.softwaretiers.getall: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + // SetTransport changes the transport on the client func (a *Client) SetTransport(transport runtime.ClientTransport) { a.transport = transport diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_pvminstances_virtualserialnumber_put_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_pvminstances_virtualserialnumber_put_responses.go index 669d081d48ba..e351a1b06f6b 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_pvminstances_virtualserialnumber_put_responses.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_pvminstances_virtualserialnumber_put_responses.go @@ -30,6 +30,12 @@ func (o *PcloudPvminstancesVirtualserialnumberPutReader) ReadResponse(response r return nil, err } return result, nil + case 202: + result := NewPcloudPvminstancesVirtualserialnumberPutAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil case 400: result := NewPcloudPvminstancesVirtualserialnumberPutBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { @@ -141,6 +147,76 @@ func (o *PcloudPvminstancesVirtualserialnumberPutOK) readResponse(response runti return nil } +// NewPcloudPvminstancesVirtualserialnumberPutAccepted creates a PcloudPvminstancesVirtualserialnumberPutAccepted with default headers values +func NewPcloudPvminstancesVirtualserialnumberPutAccepted() *PcloudPvminstancesVirtualserialnumberPutAccepted { + return &PcloudPvminstancesVirtualserialnumberPutAccepted{} +} + +/* +PcloudPvminstancesVirtualserialnumberPutAccepted describes a response with status code 202, with default header values. + +Accepted +*/ +type PcloudPvminstancesVirtualserialnumberPutAccepted struct { + Payload *models.VirtualSerialNumber +} + +// IsSuccess returns true when this pcloud pvminstances virtualserialnumber put accepted response has a 2xx status code +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this pcloud pvminstances virtualserialnumber put accepted response has a 3xx status code +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) IsRedirect() bool { + return false +} + +// IsClientError returns true when this pcloud pvminstances virtualserialnumber put accepted response has a 4xx status code +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) IsClientError() bool { + return false +} + +// IsServerError returns true when this pcloud pvminstances virtualserialnumber put accepted response has a 5xx status code +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) IsServerError() bool { + return false +} + +// IsCode returns true when this pcloud pvminstances virtualserialnumber put accepted response a status code equal to that given +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) IsCode(code int) bool { + return code == 202 +} + +// Code gets the status code for the pcloud pvminstances virtualserialnumber put accepted response +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) Code() int { + return 202 +} + +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /pcloud/v1/cloud-instances/{cloud_instance_id}/pvm-instances/{pvm_instance_id}/virtual-serial-number][%d] pcloudPvminstancesVirtualserialnumberPutAccepted %s", 202, payload) +} + +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /pcloud/v1/cloud-instances/{cloud_instance_id}/pvm-instances/{pvm_instance_id}/virtual-serial-number][%d] pcloudPvminstancesVirtualserialnumberPutAccepted %s", 202, payload) +} + +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) GetPayload() *models.VirtualSerialNumber { + return o.Payload +} + +func (o *PcloudPvminstancesVirtualserialnumberPutAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.VirtualSerialNumber) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + // NewPcloudPvminstancesVirtualserialnumberPutBadRequest creates a PcloudPvminstancesVirtualserialnumberPutBadRequest with default headers values func NewPcloudPvminstancesVirtualserialnumberPutBadRequest() *PcloudPvminstancesVirtualserialnumberPutBadRequest { return &PcloudPvminstancesVirtualserialnumberPutBadRequest{} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_virtualserialnumber_softwaretiers_getall_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_virtualserialnumber_softwaretiers_getall_parameters.go new file mode 100644 index 000000000000..f90bfac6d3c2 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_virtualserialnumber_softwaretiers_getall_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package p_cloud_virtual_serial_number + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPcloudVirtualserialnumberSoftwaretiersGetallParams creates a new PcloudVirtualserialnumberSoftwaretiersGetallParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPcloudVirtualserialnumberSoftwaretiersGetallParams() *PcloudVirtualserialnumberSoftwaretiersGetallParams { + return &PcloudVirtualserialnumberSoftwaretiersGetallParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPcloudVirtualserialnumberSoftwaretiersGetallParamsWithTimeout creates a new PcloudVirtualserialnumberSoftwaretiersGetallParams object +// with the ability to set a timeout on a request. +func NewPcloudVirtualserialnumberSoftwaretiersGetallParamsWithTimeout(timeout time.Duration) *PcloudVirtualserialnumberSoftwaretiersGetallParams { + return &PcloudVirtualserialnumberSoftwaretiersGetallParams{ + timeout: timeout, + } +} + +// NewPcloudVirtualserialnumberSoftwaretiersGetallParamsWithContext creates a new PcloudVirtualserialnumberSoftwaretiersGetallParams object +// with the ability to set a context for a request. +func NewPcloudVirtualserialnumberSoftwaretiersGetallParamsWithContext(ctx context.Context) *PcloudVirtualserialnumberSoftwaretiersGetallParams { + return &PcloudVirtualserialnumberSoftwaretiersGetallParams{ + Context: ctx, + } +} + +// NewPcloudVirtualserialnumberSoftwaretiersGetallParamsWithHTTPClient creates a new PcloudVirtualserialnumberSoftwaretiersGetallParams object +// with the ability to set a custom HTTPClient for a request. +func NewPcloudVirtualserialnumberSoftwaretiersGetallParamsWithHTTPClient(client *http.Client) *PcloudVirtualserialnumberSoftwaretiersGetallParams { + return &PcloudVirtualserialnumberSoftwaretiersGetallParams{ + HTTPClient: client, + } +} + +/* +PcloudVirtualserialnumberSoftwaretiersGetallParams contains all the parameters to send to the API endpoint + + for the pcloud virtualserialnumber softwaretiers getall operation. + + Typically these are written to a http.Request. +*/ +type PcloudVirtualserialnumberSoftwaretiersGetallParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the pcloud virtualserialnumber softwaretiers getall params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) WithDefaults() *PcloudVirtualserialnumberSoftwaretiersGetallParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the pcloud virtualserialnumber softwaretiers getall params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the pcloud virtualserialnumber softwaretiers getall params +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) WithTimeout(timeout time.Duration) *PcloudVirtualserialnumberSoftwaretiersGetallParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the pcloud virtualserialnumber softwaretiers getall params +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the pcloud virtualserialnumber softwaretiers getall params +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) WithContext(ctx context.Context) *PcloudVirtualserialnumberSoftwaretiersGetallParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the pcloud virtualserialnumber softwaretiers getall params +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the pcloud virtualserialnumber softwaretiers getall params +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) WithHTTPClient(client *http.Client) *PcloudVirtualserialnumberSoftwaretiersGetallParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the pcloud virtualserialnumber softwaretiers getall params +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *PcloudVirtualserialnumberSoftwaretiersGetallParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_virtualserialnumber_softwaretiers_getall_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_virtualserialnumber_softwaretiers_getall_responses.go new file mode 100644 index 000000000000..53d0a5b9cc87 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/p_cloud_virtual_serial_number/pcloud_virtualserialnumber_softwaretiers_getall_responses.go @@ -0,0 +1,408 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package p_cloud_virtual_serial_number + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// PcloudVirtualserialnumberSoftwaretiersGetallReader is a Reader for the PcloudVirtualserialnumberSoftwaretiersGetall structure. +type PcloudVirtualserialnumberSoftwaretiersGetallReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PcloudVirtualserialnumberSoftwaretiersGetallReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPcloudVirtualserialnumberSoftwaretiersGetallOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPcloudVirtualserialnumberSoftwaretiersGetallBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPcloudVirtualserialnumberSoftwaretiersGetallUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewPcloudVirtualserialnumberSoftwaretiersGetallForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewPcloudVirtualserialnumberSoftwaretiersGetallInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/virtual-serial-number/software-tiers] pcloud.virtualserialnumber.softwaretiers.getall", response, response.Code()) + } +} + +// NewPcloudVirtualserialnumberSoftwaretiersGetallOK creates a PcloudVirtualserialnumberSoftwaretiersGetallOK with default headers values +func NewPcloudVirtualserialnumberSoftwaretiersGetallOK() *PcloudVirtualserialnumberSoftwaretiersGetallOK { + return &PcloudVirtualserialnumberSoftwaretiersGetallOK{} +} + +/* +PcloudVirtualserialnumberSoftwaretiersGetallOK describes a response with status code 200, with default header values. + +OK +*/ +type PcloudVirtualserialnumberSoftwaretiersGetallOK struct { + Payload models.SupportedSoftwareTierList +} + +// IsSuccess returns true when this pcloud virtualserialnumber softwaretiers getall o k response has a 2xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this pcloud virtualserialnumber softwaretiers getall o k response has a 3xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this pcloud virtualserialnumber softwaretiers getall o k response has a 4xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this pcloud virtualserialnumber softwaretiers getall o k response has a 5xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) IsServerError() bool { + return false +} + +// IsCode returns true when this pcloud virtualserialnumber softwaretiers getall o k response a status code equal to that given +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the pcloud virtualserialnumber softwaretiers getall o k response +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) Code() int { + return 200 +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallOK %s", 200, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallOK %s", 200, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) GetPayload() models.SupportedSoftwareTierList { + return o.Payload +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPcloudVirtualserialnumberSoftwaretiersGetallBadRequest creates a PcloudVirtualserialnumberSoftwaretiersGetallBadRequest with default headers values +func NewPcloudVirtualserialnumberSoftwaretiersGetallBadRequest() *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest { + return &PcloudVirtualserialnumberSoftwaretiersGetallBadRequest{} +} + +/* +PcloudVirtualserialnumberSoftwaretiersGetallBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type PcloudVirtualserialnumberSoftwaretiersGetallBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this pcloud virtualserialnumber softwaretiers getall bad request response has a 2xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this pcloud virtualserialnumber softwaretiers getall bad request response has a 3xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this pcloud virtualserialnumber softwaretiers getall bad request response has a 4xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this pcloud virtualserialnumber softwaretiers getall bad request response has a 5xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this pcloud virtualserialnumber softwaretiers getall bad request response a status code equal to that given +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the pcloud virtualserialnumber softwaretiers getall bad request response +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) Code() int { + return 400 +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallBadRequest %s", 400, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallBadRequest %s", 400, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPcloudVirtualserialnumberSoftwaretiersGetallUnauthorized creates a PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized with default headers values +func NewPcloudVirtualserialnumberSoftwaretiersGetallUnauthorized() *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized { + return &PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized{} +} + +/* +PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this pcloud virtualserialnumber softwaretiers getall unauthorized response has a 2xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this pcloud virtualserialnumber softwaretiers getall unauthorized response has a 3xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this pcloud virtualserialnumber softwaretiers getall unauthorized response has a 4xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this pcloud virtualserialnumber softwaretiers getall unauthorized response has a 5xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this pcloud virtualserialnumber softwaretiers getall unauthorized response a status code equal to that given +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the pcloud virtualserialnumber softwaretiers getall unauthorized response +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) Code() int { + return 401 +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallUnauthorized %s", 401, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallUnauthorized %s", 401, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPcloudVirtualserialnumberSoftwaretiersGetallForbidden creates a PcloudVirtualserialnumberSoftwaretiersGetallForbidden with default headers values +func NewPcloudVirtualserialnumberSoftwaretiersGetallForbidden() *PcloudVirtualserialnumberSoftwaretiersGetallForbidden { + return &PcloudVirtualserialnumberSoftwaretiersGetallForbidden{} +} + +/* +PcloudVirtualserialnumberSoftwaretiersGetallForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type PcloudVirtualserialnumberSoftwaretiersGetallForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this pcloud virtualserialnumber softwaretiers getall forbidden response has a 2xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this pcloud virtualserialnumber softwaretiers getall forbidden response has a 3xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this pcloud virtualserialnumber softwaretiers getall forbidden response has a 4xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this pcloud virtualserialnumber softwaretiers getall forbidden response has a 5xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this pcloud virtualserialnumber softwaretiers getall forbidden response a status code equal to that given +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the pcloud virtualserialnumber softwaretiers getall forbidden response +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) Code() int { + return 403 +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallForbidden %s", 403, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallForbidden %s", 403, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPcloudVirtualserialnumberSoftwaretiersGetallInternalServerError creates a PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError with default headers values +func NewPcloudVirtualserialnumberSoftwaretiersGetallInternalServerError() *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError { + return &PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError{} +} + +/* +PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this pcloud virtualserialnumber softwaretiers getall internal server error response has a 2xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this pcloud virtualserialnumber softwaretiers getall internal server error response has a 3xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this pcloud virtualserialnumber softwaretiers getall internal server error response has a 4xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this pcloud virtualserialnumber softwaretiers getall internal server error response has a 5xx status code +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this pcloud virtualserialnumber softwaretiers getall internal server error response a status code equal to that given +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the pcloud virtualserialnumber softwaretiers getall internal server error response +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) Code() int { + return 500 +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallInternalServerError %s", 500, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/virtual-serial-number/software-tiers][%d] pcloudVirtualserialnumberSoftwaretiersGetallInternalServerError %s", 500, payload) +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *PcloudVirtualserialnumberSoftwaretiersGetallInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/power_iaas_api_client.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/power_iaas_api_client.go index eee389dd1115..a637694abf96 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/client/power_iaas_api_client.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/power_iaas_api_client.go @@ -64,9 +64,11 @@ import ( "github.com/IBM-Cloud/power-go-client/power/client/p_cloud_volume_onboarding" "github.com/IBM-Cloud/power-go-client/power/client/p_cloud_volumes" "github.com/IBM-Cloud/power-go-client/power/client/power_edge_router" + "github.com/IBM-Cloud/power-go-client/power/client/routes" "github.com/IBM-Cloud/power-go-client/power/client/service_bindings" "github.com/IBM-Cloud/power-go-client/power/client/service_instances" "github.com/IBM-Cloud/power-go-client/power/client/snapshots" + "github.com/IBM-Cloud/power-go-client/power/client/ssh_keys" "github.com/IBM-Cloud/power-go-client/power/client/storage_types" "github.com/IBM-Cloud/power-go-client/power/client/swagger_spec" "github.com/IBM-Cloud/power-go-client/power/client/workspaces" @@ -168,9 +170,11 @@ func New(transport runtime.ClientTransport, formats strfmt.Registry) *PowerIaasA cli.PCloudVolumeOnboarding = p_cloud_volume_onboarding.New(transport, formats) cli.PCloudVolumes = p_cloud_volumes.New(transport, formats) cli.PowerEdgeRouter = power_edge_router.New(transport, formats) + cli.Routes = routes.New(transport, formats) cli.ServiceBindings = service_bindings.New(transport, formats) cli.ServiceInstances = service_instances.New(transport, formats) cli.Snapshots = snapshots.New(transport, formats) + cli.SSHKeys = ssh_keys.New(transport, formats) cli.StorageTypes = storage_types.New(transport, formats) cli.SwaggerSpec = swagger_spec.New(transport, formats) cli.Workspaces = workspaces.New(transport, formats) @@ -326,12 +330,16 @@ type PowerIaasAPI struct { PowerEdgeRouter power_edge_router.ClientService + Routes routes.ClientService + ServiceBindings service_bindings.ClientService ServiceInstances service_instances.ClientService Snapshots snapshots.ClientService + SSHKeys ssh_keys.ClientService + StorageTypes storage_types.ClientService SwaggerSpec swagger_spec.ClientService @@ -398,9 +406,11 @@ func (c *PowerIaasAPI) SetTransport(transport runtime.ClientTransport) { c.PCloudVolumeOnboarding.SetTransport(transport) c.PCloudVolumes.SetTransport(transport) c.PowerEdgeRouter.SetTransport(transport) + c.Routes.SetTransport(transport) c.ServiceBindings.SetTransport(transport) c.ServiceInstances.SetTransport(transport) c.Snapshots.SetTransport(transport) + c.SSHKeys.SetTransport(transport) c.StorageTypes.SetTransport(transport) c.SwaggerSpec.SetTransport(transport) c.Workspaces.SetTransport(transport) diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/routes_client.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/routes_client.go new file mode 100644 index 000000000000..946f16df4667 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/routes_client.go @@ -0,0 +1,311 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new routes API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new routes API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new routes API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for routes API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1RoutesDelete(params *V1RoutesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesDeleteOK, error) + + V1RoutesGet(params *V1RoutesGetParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesGetOK, error) + + V1RoutesGetall(params *V1RoutesGetallParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesGetallOK, error) + + V1RoutesPost(params *V1RoutesPostParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesPostCreated, error) + + V1RoutesPut(params *V1RoutesPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesPutOK, error) + + V1RoutesReportGet(params *V1RoutesReportGetParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesReportGetOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1RoutesDelete deletes a route +*/ +func (a *Client) V1RoutesDelete(params *V1RoutesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesDeleteOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1RoutesDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "v1.routes.delete", + Method: "DELETE", + PathPattern: "/v1/routes/{route_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1RoutesDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1RoutesDeleteOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.routes.delete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1RoutesGet gets a route s information +*/ +func (a *Client) V1RoutesGet(params *V1RoutesGetParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesGetOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1RoutesGetParams() + } + op := &runtime.ClientOperation{ + ID: "v1.routes.get", + Method: "GET", + PathPattern: "/v1/routes/{route_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1RoutesGetReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1RoutesGetOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.routes.get: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1RoutesGetall gets all routes in the workspace +*/ +func (a *Client) V1RoutesGetall(params *V1RoutesGetallParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesGetallOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1RoutesGetallParams() + } + op := &runtime.ClientOperation{ + ID: "v1.routes.getall", + Method: "GET", + PathPattern: "/v1/routes", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1RoutesGetallReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1RoutesGetallOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.routes.getall: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1RoutesPost performs a route creation +*/ +func (a *Client) V1RoutesPost(params *V1RoutesPostParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesPostCreated, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1RoutesPostParams() + } + op := &runtime.ClientOperation{ + ID: "v1.routes.post", + Method: "POST", + PathPattern: "/v1/routes", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1RoutesPostReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1RoutesPostCreated) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.routes.post: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1RoutesPut updates a route s information +*/ +func (a *Client) V1RoutesPut(params *V1RoutesPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesPutOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1RoutesPutParams() + } + op := &runtime.ClientOperation{ + ID: "v1.routes.put", + Method: "PUT", + PathPattern: "/v1/routes/{route_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1RoutesPutReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1RoutesPutOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.routes.put: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1RoutesReportGet gets the route report for a workspace +*/ +func (a *Client) V1RoutesReportGet(params *V1RoutesReportGetParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1RoutesReportGetOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1RoutesReportGetParams() + } + op := &runtime.ClientOperation{ + ID: "v1.routes.report.get", + Method: "GET", + PathPattern: "/v1/routes/report", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1RoutesReportGetReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1RoutesReportGetOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.routes.report.get: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_delete_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_delete_parameters.go new file mode 100644 index 000000000000..621cef0edc82 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_delete_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1RoutesDeleteParams creates a new V1RoutesDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1RoutesDeleteParams() *V1RoutesDeleteParams { + return &V1RoutesDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1RoutesDeleteParamsWithTimeout creates a new V1RoutesDeleteParams object +// with the ability to set a timeout on a request. +func NewV1RoutesDeleteParamsWithTimeout(timeout time.Duration) *V1RoutesDeleteParams { + return &V1RoutesDeleteParams{ + timeout: timeout, + } +} + +// NewV1RoutesDeleteParamsWithContext creates a new V1RoutesDeleteParams object +// with the ability to set a context for a request. +func NewV1RoutesDeleteParamsWithContext(ctx context.Context) *V1RoutesDeleteParams { + return &V1RoutesDeleteParams{ + Context: ctx, + } +} + +// NewV1RoutesDeleteParamsWithHTTPClient creates a new V1RoutesDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1RoutesDeleteParamsWithHTTPClient(client *http.Client) *V1RoutesDeleteParams { + return &V1RoutesDeleteParams{ + HTTPClient: client, + } +} + +/* +V1RoutesDeleteParams contains all the parameters to send to the API endpoint + + for the v1 routes delete operation. + + Typically these are written to a http.Request. +*/ +type V1RoutesDeleteParams struct { + + /* RouteID. + + Route ID + */ + RouteID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 routes delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesDeleteParams) WithDefaults() *V1RoutesDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 routes delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 routes delete params +func (o *V1RoutesDeleteParams) WithTimeout(timeout time.Duration) *V1RoutesDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 routes delete params +func (o *V1RoutesDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 routes delete params +func (o *V1RoutesDeleteParams) WithContext(ctx context.Context) *V1RoutesDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 routes delete params +func (o *V1RoutesDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 routes delete params +func (o *V1RoutesDeleteParams) WithHTTPClient(client *http.Client) *V1RoutesDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 routes delete params +func (o *V1RoutesDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithRouteID adds the routeID to the v1 routes delete params +func (o *V1RoutesDeleteParams) WithRouteID(routeID string) *V1RoutesDeleteParams { + o.SetRouteID(routeID) + return o +} + +// SetRouteID adds the routeId to the v1 routes delete params +func (o *V1RoutesDeleteParams) SetRouteID(routeID string) { + o.RouteID = routeID +} + +// WriteToRequest writes these params to a swagger request +func (o *V1RoutesDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param route_id + if err := r.SetPathParam("route_id", o.RouteID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_delete_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_delete_responses.go new file mode 100644 index 000000000000..6244d6c08e2d --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_delete_responses.go @@ -0,0 +1,560 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1RoutesDeleteReader is a Reader for the V1RoutesDelete structure. +type V1RoutesDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1RoutesDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1RoutesDeleteOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1RoutesDeleteBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1RoutesDeleteUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1RoutesDeleteForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1RoutesDeleteNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 410: + result := NewV1RoutesDeleteGone() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1RoutesDeleteInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /v1/routes/{route_id}] v1.routes.delete", response, response.Code()) + } +} + +// NewV1RoutesDeleteOK creates a V1RoutesDeleteOK with default headers values +func NewV1RoutesDeleteOK() *V1RoutesDeleteOK { + return &V1RoutesDeleteOK{} +} + +/* +V1RoutesDeleteOK describes a response with status code 200, with default header values. + +OK +*/ +type V1RoutesDeleteOK struct { + Payload models.Object +} + +// IsSuccess returns true when this v1 routes delete o k response has a 2xx status code +func (o *V1RoutesDeleteOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 routes delete o k response has a 3xx status code +func (o *V1RoutesDeleteOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes delete o k response has a 4xx status code +func (o *V1RoutesDeleteOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes delete o k response has a 5xx status code +func (o *V1RoutesDeleteOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes delete o k response a status code equal to that given +func (o *V1RoutesDeleteOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 routes delete o k response +func (o *V1RoutesDeleteOK) Code() int { + return 200 +} + +func (o *V1RoutesDeleteOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteOK %s", 200, payload) +} + +func (o *V1RoutesDeleteOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteOK %s", 200, payload) +} + +func (o *V1RoutesDeleteOK) GetPayload() models.Object { + return o.Payload +} + +func (o *V1RoutesDeleteOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesDeleteBadRequest creates a V1RoutesDeleteBadRequest with default headers values +func NewV1RoutesDeleteBadRequest() *V1RoutesDeleteBadRequest { + return &V1RoutesDeleteBadRequest{} +} + +/* +V1RoutesDeleteBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1RoutesDeleteBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes delete bad request response has a 2xx status code +func (o *V1RoutesDeleteBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes delete bad request response has a 3xx status code +func (o *V1RoutesDeleteBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes delete bad request response has a 4xx status code +func (o *V1RoutesDeleteBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes delete bad request response has a 5xx status code +func (o *V1RoutesDeleteBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes delete bad request response a status code equal to that given +func (o *V1RoutesDeleteBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 routes delete bad request response +func (o *V1RoutesDeleteBadRequest) Code() int { + return 400 +} + +func (o *V1RoutesDeleteBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteBadRequest %s", 400, payload) +} + +func (o *V1RoutesDeleteBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteBadRequest %s", 400, payload) +} + +func (o *V1RoutesDeleteBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesDeleteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesDeleteUnauthorized creates a V1RoutesDeleteUnauthorized with default headers values +func NewV1RoutesDeleteUnauthorized() *V1RoutesDeleteUnauthorized { + return &V1RoutesDeleteUnauthorized{} +} + +/* +V1RoutesDeleteUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1RoutesDeleteUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes delete unauthorized response has a 2xx status code +func (o *V1RoutesDeleteUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes delete unauthorized response has a 3xx status code +func (o *V1RoutesDeleteUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes delete unauthorized response has a 4xx status code +func (o *V1RoutesDeleteUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes delete unauthorized response has a 5xx status code +func (o *V1RoutesDeleteUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes delete unauthorized response a status code equal to that given +func (o *V1RoutesDeleteUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 routes delete unauthorized response +func (o *V1RoutesDeleteUnauthorized) Code() int { + return 401 +} + +func (o *V1RoutesDeleteUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteUnauthorized %s", 401, payload) +} + +func (o *V1RoutesDeleteUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteUnauthorized %s", 401, payload) +} + +func (o *V1RoutesDeleteUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesDeleteUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesDeleteForbidden creates a V1RoutesDeleteForbidden with default headers values +func NewV1RoutesDeleteForbidden() *V1RoutesDeleteForbidden { + return &V1RoutesDeleteForbidden{} +} + +/* +V1RoutesDeleteForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1RoutesDeleteForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes delete forbidden response has a 2xx status code +func (o *V1RoutesDeleteForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes delete forbidden response has a 3xx status code +func (o *V1RoutesDeleteForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes delete forbidden response has a 4xx status code +func (o *V1RoutesDeleteForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes delete forbidden response has a 5xx status code +func (o *V1RoutesDeleteForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes delete forbidden response a status code equal to that given +func (o *V1RoutesDeleteForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 routes delete forbidden response +func (o *V1RoutesDeleteForbidden) Code() int { + return 403 +} + +func (o *V1RoutesDeleteForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteForbidden %s", 403, payload) +} + +func (o *V1RoutesDeleteForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteForbidden %s", 403, payload) +} + +func (o *V1RoutesDeleteForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesDeleteForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesDeleteNotFound creates a V1RoutesDeleteNotFound with default headers values +func NewV1RoutesDeleteNotFound() *V1RoutesDeleteNotFound { + return &V1RoutesDeleteNotFound{} +} + +/* +V1RoutesDeleteNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1RoutesDeleteNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes delete not found response has a 2xx status code +func (o *V1RoutesDeleteNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes delete not found response has a 3xx status code +func (o *V1RoutesDeleteNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes delete not found response has a 4xx status code +func (o *V1RoutesDeleteNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes delete not found response has a 5xx status code +func (o *V1RoutesDeleteNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes delete not found response a status code equal to that given +func (o *V1RoutesDeleteNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 routes delete not found response +func (o *V1RoutesDeleteNotFound) Code() int { + return 404 +} + +func (o *V1RoutesDeleteNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteNotFound %s", 404, payload) +} + +func (o *V1RoutesDeleteNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteNotFound %s", 404, payload) +} + +func (o *V1RoutesDeleteNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesDeleteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesDeleteGone creates a V1RoutesDeleteGone with default headers values +func NewV1RoutesDeleteGone() *V1RoutesDeleteGone { + return &V1RoutesDeleteGone{} +} + +/* +V1RoutesDeleteGone describes a response with status code 410, with default header values. + +Gone +*/ +type V1RoutesDeleteGone struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes delete gone response has a 2xx status code +func (o *V1RoutesDeleteGone) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes delete gone response has a 3xx status code +func (o *V1RoutesDeleteGone) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes delete gone response has a 4xx status code +func (o *V1RoutesDeleteGone) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes delete gone response has a 5xx status code +func (o *V1RoutesDeleteGone) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes delete gone response a status code equal to that given +func (o *V1RoutesDeleteGone) IsCode(code int) bool { + return code == 410 +} + +// Code gets the status code for the v1 routes delete gone response +func (o *V1RoutesDeleteGone) Code() int { + return 410 +} + +func (o *V1RoutesDeleteGone) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteGone %s", 410, payload) +} + +func (o *V1RoutesDeleteGone) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteGone %s", 410, payload) +} + +func (o *V1RoutesDeleteGone) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesDeleteGone) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesDeleteInternalServerError creates a V1RoutesDeleteInternalServerError with default headers values +func NewV1RoutesDeleteInternalServerError() *V1RoutesDeleteInternalServerError { + return &V1RoutesDeleteInternalServerError{} +} + +/* +V1RoutesDeleteInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1RoutesDeleteInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes delete internal server error response has a 2xx status code +func (o *V1RoutesDeleteInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes delete internal server error response has a 3xx status code +func (o *V1RoutesDeleteInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes delete internal server error response has a 4xx status code +func (o *V1RoutesDeleteInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes delete internal server error response has a 5xx status code +func (o *V1RoutesDeleteInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 routes delete internal server error response a status code equal to that given +func (o *V1RoutesDeleteInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 routes delete internal server error response +func (o *V1RoutesDeleteInternalServerError) Code() int { + return 500 +} + +func (o *V1RoutesDeleteInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteInternalServerError %s", 500, payload) +} + +func (o *V1RoutesDeleteInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/routes/{route_id}][%d] v1RoutesDeleteInternalServerError %s", 500, payload) +} + +func (o *V1RoutesDeleteInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesDeleteInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_get_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_get_parameters.go new file mode 100644 index 000000000000..2fda24e29545 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_get_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1RoutesGetParams creates a new V1RoutesGetParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1RoutesGetParams() *V1RoutesGetParams { + return &V1RoutesGetParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1RoutesGetParamsWithTimeout creates a new V1RoutesGetParams object +// with the ability to set a timeout on a request. +func NewV1RoutesGetParamsWithTimeout(timeout time.Duration) *V1RoutesGetParams { + return &V1RoutesGetParams{ + timeout: timeout, + } +} + +// NewV1RoutesGetParamsWithContext creates a new V1RoutesGetParams object +// with the ability to set a context for a request. +func NewV1RoutesGetParamsWithContext(ctx context.Context) *V1RoutesGetParams { + return &V1RoutesGetParams{ + Context: ctx, + } +} + +// NewV1RoutesGetParamsWithHTTPClient creates a new V1RoutesGetParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1RoutesGetParamsWithHTTPClient(client *http.Client) *V1RoutesGetParams { + return &V1RoutesGetParams{ + HTTPClient: client, + } +} + +/* +V1RoutesGetParams contains all the parameters to send to the API endpoint + + for the v1 routes get operation. + + Typically these are written to a http.Request. +*/ +type V1RoutesGetParams struct { + + /* RouteID. + + Route ID + */ + RouteID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 routes get params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesGetParams) WithDefaults() *V1RoutesGetParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 routes get params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesGetParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 routes get params +func (o *V1RoutesGetParams) WithTimeout(timeout time.Duration) *V1RoutesGetParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 routes get params +func (o *V1RoutesGetParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 routes get params +func (o *V1RoutesGetParams) WithContext(ctx context.Context) *V1RoutesGetParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 routes get params +func (o *V1RoutesGetParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 routes get params +func (o *V1RoutesGetParams) WithHTTPClient(client *http.Client) *V1RoutesGetParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 routes get params +func (o *V1RoutesGetParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithRouteID adds the routeID to the v1 routes get params +func (o *V1RoutesGetParams) WithRouteID(routeID string) *V1RoutesGetParams { + o.SetRouteID(routeID) + return o +} + +// SetRouteID adds the routeId to the v1 routes get params +func (o *V1RoutesGetParams) SetRouteID(routeID string) { + o.RouteID = routeID +} + +// WriteToRequest writes these params to a swagger request +func (o *V1RoutesGetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param route_id + if err := r.SetPathParam("route_id", o.RouteID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_get_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_get_responses.go new file mode 100644 index 000000000000..e09afbbdb013 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_get_responses.go @@ -0,0 +1,486 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1RoutesGetReader is a Reader for the V1RoutesGet structure. +type V1RoutesGetReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1RoutesGetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1RoutesGetOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1RoutesGetBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1RoutesGetUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1RoutesGetForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1RoutesGetNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1RoutesGetInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/routes/{route_id}] v1.routes.get", response, response.Code()) + } +} + +// NewV1RoutesGetOK creates a V1RoutesGetOK with default headers values +func NewV1RoutesGetOK() *V1RoutesGetOK { + return &V1RoutesGetOK{} +} + +/* +V1RoutesGetOK describes a response with status code 200, with default header values. + +OK +*/ +type V1RoutesGetOK struct { + Payload *models.Route +} + +// IsSuccess returns true when this v1 routes get o k response has a 2xx status code +func (o *V1RoutesGetOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 routes get o k response has a 3xx status code +func (o *V1RoutesGetOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes get o k response has a 4xx status code +func (o *V1RoutesGetOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes get o k response has a 5xx status code +func (o *V1RoutesGetOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes get o k response a status code equal to that given +func (o *V1RoutesGetOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 routes get o k response +func (o *V1RoutesGetOK) Code() int { + return 200 +} + +func (o *V1RoutesGetOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetOK %s", 200, payload) +} + +func (o *V1RoutesGetOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetOK %s", 200, payload) +} + +func (o *V1RoutesGetOK) GetPayload() *models.Route { + return o.Payload +} + +func (o *V1RoutesGetOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Route) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetBadRequest creates a V1RoutesGetBadRequest with default headers values +func NewV1RoutesGetBadRequest() *V1RoutesGetBadRequest { + return &V1RoutesGetBadRequest{} +} + +/* +V1RoutesGetBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1RoutesGetBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes get bad request response has a 2xx status code +func (o *V1RoutesGetBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes get bad request response has a 3xx status code +func (o *V1RoutesGetBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes get bad request response has a 4xx status code +func (o *V1RoutesGetBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes get bad request response has a 5xx status code +func (o *V1RoutesGetBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes get bad request response a status code equal to that given +func (o *V1RoutesGetBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 routes get bad request response +func (o *V1RoutesGetBadRequest) Code() int { + return 400 +} + +func (o *V1RoutesGetBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetBadRequest %s", 400, payload) +} + +func (o *V1RoutesGetBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetBadRequest %s", 400, payload) +} + +func (o *V1RoutesGetBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetUnauthorized creates a V1RoutesGetUnauthorized with default headers values +func NewV1RoutesGetUnauthorized() *V1RoutesGetUnauthorized { + return &V1RoutesGetUnauthorized{} +} + +/* +V1RoutesGetUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1RoutesGetUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes get unauthorized response has a 2xx status code +func (o *V1RoutesGetUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes get unauthorized response has a 3xx status code +func (o *V1RoutesGetUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes get unauthorized response has a 4xx status code +func (o *V1RoutesGetUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes get unauthorized response has a 5xx status code +func (o *V1RoutesGetUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes get unauthorized response a status code equal to that given +func (o *V1RoutesGetUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 routes get unauthorized response +func (o *V1RoutesGetUnauthorized) Code() int { + return 401 +} + +func (o *V1RoutesGetUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetUnauthorized %s", 401, payload) +} + +func (o *V1RoutesGetUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetUnauthorized %s", 401, payload) +} + +func (o *V1RoutesGetUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetForbidden creates a V1RoutesGetForbidden with default headers values +func NewV1RoutesGetForbidden() *V1RoutesGetForbidden { + return &V1RoutesGetForbidden{} +} + +/* +V1RoutesGetForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1RoutesGetForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes get forbidden response has a 2xx status code +func (o *V1RoutesGetForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes get forbidden response has a 3xx status code +func (o *V1RoutesGetForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes get forbidden response has a 4xx status code +func (o *V1RoutesGetForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes get forbidden response has a 5xx status code +func (o *V1RoutesGetForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes get forbidden response a status code equal to that given +func (o *V1RoutesGetForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 routes get forbidden response +func (o *V1RoutesGetForbidden) Code() int { + return 403 +} + +func (o *V1RoutesGetForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetForbidden %s", 403, payload) +} + +func (o *V1RoutesGetForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetForbidden %s", 403, payload) +} + +func (o *V1RoutesGetForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetNotFound creates a V1RoutesGetNotFound with default headers values +func NewV1RoutesGetNotFound() *V1RoutesGetNotFound { + return &V1RoutesGetNotFound{} +} + +/* +V1RoutesGetNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1RoutesGetNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes get not found response has a 2xx status code +func (o *V1RoutesGetNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes get not found response has a 3xx status code +func (o *V1RoutesGetNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes get not found response has a 4xx status code +func (o *V1RoutesGetNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes get not found response has a 5xx status code +func (o *V1RoutesGetNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes get not found response a status code equal to that given +func (o *V1RoutesGetNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 routes get not found response +func (o *V1RoutesGetNotFound) Code() int { + return 404 +} + +func (o *V1RoutesGetNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetNotFound %s", 404, payload) +} + +func (o *V1RoutesGetNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetNotFound %s", 404, payload) +} + +func (o *V1RoutesGetNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetInternalServerError creates a V1RoutesGetInternalServerError with default headers values +func NewV1RoutesGetInternalServerError() *V1RoutesGetInternalServerError { + return &V1RoutesGetInternalServerError{} +} + +/* +V1RoutesGetInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1RoutesGetInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes get internal server error response has a 2xx status code +func (o *V1RoutesGetInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes get internal server error response has a 3xx status code +func (o *V1RoutesGetInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes get internal server error response has a 4xx status code +func (o *V1RoutesGetInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes get internal server error response has a 5xx status code +func (o *V1RoutesGetInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 routes get internal server error response a status code equal to that given +func (o *V1RoutesGetInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 routes get internal server error response +func (o *V1RoutesGetInternalServerError) Code() int { + return 500 +} + +func (o *V1RoutesGetInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetInternalServerError %s", 500, payload) +} + +func (o *V1RoutesGetInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/{route_id}][%d] v1RoutesGetInternalServerError %s", 500, payload) +} + +func (o *V1RoutesGetInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_getall_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_getall_parameters.go new file mode 100644 index 000000000000..e5073afc77cf --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_getall_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1RoutesGetallParams creates a new V1RoutesGetallParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1RoutesGetallParams() *V1RoutesGetallParams { + return &V1RoutesGetallParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1RoutesGetallParamsWithTimeout creates a new V1RoutesGetallParams object +// with the ability to set a timeout on a request. +func NewV1RoutesGetallParamsWithTimeout(timeout time.Duration) *V1RoutesGetallParams { + return &V1RoutesGetallParams{ + timeout: timeout, + } +} + +// NewV1RoutesGetallParamsWithContext creates a new V1RoutesGetallParams object +// with the ability to set a context for a request. +func NewV1RoutesGetallParamsWithContext(ctx context.Context) *V1RoutesGetallParams { + return &V1RoutesGetallParams{ + Context: ctx, + } +} + +// NewV1RoutesGetallParamsWithHTTPClient creates a new V1RoutesGetallParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1RoutesGetallParamsWithHTTPClient(client *http.Client) *V1RoutesGetallParams { + return &V1RoutesGetallParams{ + HTTPClient: client, + } +} + +/* +V1RoutesGetallParams contains all the parameters to send to the API endpoint + + for the v1 routes getall operation. + + Typically these are written to a http.Request. +*/ +type V1RoutesGetallParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 routes getall params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesGetallParams) WithDefaults() *V1RoutesGetallParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 routes getall params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesGetallParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 routes getall params +func (o *V1RoutesGetallParams) WithTimeout(timeout time.Duration) *V1RoutesGetallParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 routes getall params +func (o *V1RoutesGetallParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 routes getall params +func (o *V1RoutesGetallParams) WithContext(ctx context.Context) *V1RoutesGetallParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 routes getall params +func (o *V1RoutesGetallParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 routes getall params +func (o *V1RoutesGetallParams) WithHTTPClient(client *http.Client) *V1RoutesGetallParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 routes getall params +func (o *V1RoutesGetallParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *V1RoutesGetallParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_getall_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_getall_responses.go new file mode 100644 index 000000000000..cf9001c74ea1 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_getall_responses.go @@ -0,0 +1,486 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1RoutesGetallReader is a Reader for the V1RoutesGetall structure. +type V1RoutesGetallReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1RoutesGetallReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1RoutesGetallOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1RoutesGetallBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1RoutesGetallUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1RoutesGetallForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1RoutesGetallNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1RoutesGetallInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/routes] v1.routes.getall", response, response.Code()) + } +} + +// NewV1RoutesGetallOK creates a V1RoutesGetallOK with default headers values +func NewV1RoutesGetallOK() *V1RoutesGetallOK { + return &V1RoutesGetallOK{} +} + +/* +V1RoutesGetallOK describes a response with status code 200, with default header values. + +OK +*/ +type V1RoutesGetallOK struct { + Payload *models.Routes +} + +// IsSuccess returns true when this v1 routes getall o k response has a 2xx status code +func (o *V1RoutesGetallOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 routes getall o k response has a 3xx status code +func (o *V1RoutesGetallOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes getall o k response has a 4xx status code +func (o *V1RoutesGetallOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes getall o k response has a 5xx status code +func (o *V1RoutesGetallOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes getall o k response a status code equal to that given +func (o *V1RoutesGetallOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 routes getall o k response +func (o *V1RoutesGetallOK) Code() int { + return 200 +} + +func (o *V1RoutesGetallOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallOK %s", 200, payload) +} + +func (o *V1RoutesGetallOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallOK %s", 200, payload) +} + +func (o *V1RoutesGetallOK) GetPayload() *models.Routes { + return o.Payload +} + +func (o *V1RoutesGetallOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Routes) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetallBadRequest creates a V1RoutesGetallBadRequest with default headers values +func NewV1RoutesGetallBadRequest() *V1RoutesGetallBadRequest { + return &V1RoutesGetallBadRequest{} +} + +/* +V1RoutesGetallBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1RoutesGetallBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes getall bad request response has a 2xx status code +func (o *V1RoutesGetallBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes getall bad request response has a 3xx status code +func (o *V1RoutesGetallBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes getall bad request response has a 4xx status code +func (o *V1RoutesGetallBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes getall bad request response has a 5xx status code +func (o *V1RoutesGetallBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes getall bad request response a status code equal to that given +func (o *V1RoutesGetallBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 routes getall bad request response +func (o *V1RoutesGetallBadRequest) Code() int { + return 400 +} + +func (o *V1RoutesGetallBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallBadRequest %s", 400, payload) +} + +func (o *V1RoutesGetallBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallBadRequest %s", 400, payload) +} + +func (o *V1RoutesGetallBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetallBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetallUnauthorized creates a V1RoutesGetallUnauthorized with default headers values +func NewV1RoutesGetallUnauthorized() *V1RoutesGetallUnauthorized { + return &V1RoutesGetallUnauthorized{} +} + +/* +V1RoutesGetallUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1RoutesGetallUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes getall unauthorized response has a 2xx status code +func (o *V1RoutesGetallUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes getall unauthorized response has a 3xx status code +func (o *V1RoutesGetallUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes getall unauthorized response has a 4xx status code +func (o *V1RoutesGetallUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes getall unauthorized response has a 5xx status code +func (o *V1RoutesGetallUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes getall unauthorized response a status code equal to that given +func (o *V1RoutesGetallUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 routes getall unauthorized response +func (o *V1RoutesGetallUnauthorized) Code() int { + return 401 +} + +func (o *V1RoutesGetallUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallUnauthorized %s", 401, payload) +} + +func (o *V1RoutesGetallUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallUnauthorized %s", 401, payload) +} + +func (o *V1RoutesGetallUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetallUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetallForbidden creates a V1RoutesGetallForbidden with default headers values +func NewV1RoutesGetallForbidden() *V1RoutesGetallForbidden { + return &V1RoutesGetallForbidden{} +} + +/* +V1RoutesGetallForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1RoutesGetallForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes getall forbidden response has a 2xx status code +func (o *V1RoutesGetallForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes getall forbidden response has a 3xx status code +func (o *V1RoutesGetallForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes getall forbidden response has a 4xx status code +func (o *V1RoutesGetallForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes getall forbidden response has a 5xx status code +func (o *V1RoutesGetallForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes getall forbidden response a status code equal to that given +func (o *V1RoutesGetallForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 routes getall forbidden response +func (o *V1RoutesGetallForbidden) Code() int { + return 403 +} + +func (o *V1RoutesGetallForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallForbidden %s", 403, payload) +} + +func (o *V1RoutesGetallForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallForbidden %s", 403, payload) +} + +func (o *V1RoutesGetallForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetallForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetallNotFound creates a V1RoutesGetallNotFound with default headers values +func NewV1RoutesGetallNotFound() *V1RoutesGetallNotFound { + return &V1RoutesGetallNotFound{} +} + +/* +V1RoutesGetallNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1RoutesGetallNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes getall not found response has a 2xx status code +func (o *V1RoutesGetallNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes getall not found response has a 3xx status code +func (o *V1RoutesGetallNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes getall not found response has a 4xx status code +func (o *V1RoutesGetallNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes getall not found response has a 5xx status code +func (o *V1RoutesGetallNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes getall not found response a status code equal to that given +func (o *V1RoutesGetallNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 routes getall not found response +func (o *V1RoutesGetallNotFound) Code() int { + return 404 +} + +func (o *V1RoutesGetallNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallNotFound %s", 404, payload) +} + +func (o *V1RoutesGetallNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallNotFound %s", 404, payload) +} + +func (o *V1RoutesGetallNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetallNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesGetallInternalServerError creates a V1RoutesGetallInternalServerError with default headers values +func NewV1RoutesGetallInternalServerError() *V1RoutesGetallInternalServerError { + return &V1RoutesGetallInternalServerError{} +} + +/* +V1RoutesGetallInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1RoutesGetallInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes getall internal server error response has a 2xx status code +func (o *V1RoutesGetallInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes getall internal server error response has a 3xx status code +func (o *V1RoutesGetallInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes getall internal server error response has a 4xx status code +func (o *V1RoutesGetallInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes getall internal server error response has a 5xx status code +func (o *V1RoutesGetallInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 routes getall internal server error response a status code equal to that given +func (o *V1RoutesGetallInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 routes getall internal server error response +func (o *V1RoutesGetallInternalServerError) Code() int { + return 500 +} + +func (o *V1RoutesGetallInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallInternalServerError %s", 500, payload) +} + +func (o *V1RoutesGetallInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes][%d] v1RoutesGetallInternalServerError %s", 500, payload) +} + +func (o *V1RoutesGetallInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesGetallInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_post_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_post_parameters.go new file mode 100644 index 000000000000..076ab41b2217 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_post_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// NewV1RoutesPostParams creates a new V1RoutesPostParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1RoutesPostParams() *V1RoutesPostParams { + return &V1RoutesPostParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1RoutesPostParamsWithTimeout creates a new V1RoutesPostParams object +// with the ability to set a timeout on a request. +func NewV1RoutesPostParamsWithTimeout(timeout time.Duration) *V1RoutesPostParams { + return &V1RoutesPostParams{ + timeout: timeout, + } +} + +// NewV1RoutesPostParamsWithContext creates a new V1RoutesPostParams object +// with the ability to set a context for a request. +func NewV1RoutesPostParamsWithContext(ctx context.Context) *V1RoutesPostParams { + return &V1RoutesPostParams{ + Context: ctx, + } +} + +// NewV1RoutesPostParamsWithHTTPClient creates a new V1RoutesPostParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1RoutesPostParamsWithHTTPClient(client *http.Client) *V1RoutesPostParams { + return &V1RoutesPostParams{ + HTTPClient: client, + } +} + +/* +V1RoutesPostParams contains all the parameters to send to the API endpoint + + for the v1 routes post operation. + + Typically these are written to a http.Request. +*/ +type V1RoutesPostParams struct { + + /* Body. + + Create a route based on the inputs + */ + Body *models.RouteCreate + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 routes post params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesPostParams) WithDefaults() *V1RoutesPostParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 routes post params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesPostParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 routes post params +func (o *V1RoutesPostParams) WithTimeout(timeout time.Duration) *V1RoutesPostParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 routes post params +func (o *V1RoutesPostParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 routes post params +func (o *V1RoutesPostParams) WithContext(ctx context.Context) *V1RoutesPostParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 routes post params +func (o *V1RoutesPostParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 routes post params +func (o *V1RoutesPostParams) WithHTTPClient(client *http.Client) *V1RoutesPostParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 routes post params +func (o *V1RoutesPostParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the v1 routes post params +func (o *V1RoutesPostParams) WithBody(body *models.RouteCreate) *V1RoutesPostParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the v1 routes post params +func (o *V1RoutesPostParams) SetBody(body *models.RouteCreate) { + o.Body = body +} + +// WriteToRequest writes these params to a swagger request +func (o *V1RoutesPostParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_post_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_post_responses.go new file mode 100644 index 000000000000..91acfe074f80 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_post_responses.go @@ -0,0 +1,638 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1RoutesPostReader is a Reader for the V1RoutesPost structure. +type V1RoutesPostReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1RoutesPostReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewV1RoutesPostCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1RoutesPostBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1RoutesPostUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1RoutesPostForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1RoutesPostNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewV1RoutesPostConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1RoutesPostUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1RoutesPostInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /v1/routes] v1.routes.post", response, response.Code()) + } +} + +// NewV1RoutesPostCreated creates a V1RoutesPostCreated with default headers values +func NewV1RoutesPostCreated() *V1RoutesPostCreated { + return &V1RoutesPostCreated{} +} + +/* +V1RoutesPostCreated describes a response with status code 201, with default header values. + +Created +*/ +type V1RoutesPostCreated struct { + Payload *models.Route +} + +// IsSuccess returns true when this v1 routes post created response has a 2xx status code +func (o *V1RoutesPostCreated) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 routes post created response has a 3xx status code +func (o *V1RoutesPostCreated) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes post created response has a 4xx status code +func (o *V1RoutesPostCreated) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes post created response has a 5xx status code +func (o *V1RoutesPostCreated) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes post created response a status code equal to that given +func (o *V1RoutesPostCreated) IsCode(code int) bool { + return code == 201 +} + +// Code gets the status code for the v1 routes post created response +func (o *V1RoutesPostCreated) Code() int { + return 201 +} + +func (o *V1RoutesPostCreated) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostCreated %s", 201, payload) +} + +func (o *V1RoutesPostCreated) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostCreated %s", 201, payload) +} + +func (o *V1RoutesPostCreated) GetPayload() *models.Route { + return o.Payload +} + +func (o *V1RoutesPostCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Route) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPostBadRequest creates a V1RoutesPostBadRequest with default headers values +func NewV1RoutesPostBadRequest() *V1RoutesPostBadRequest { + return &V1RoutesPostBadRequest{} +} + +/* +V1RoutesPostBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1RoutesPostBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes post bad request response has a 2xx status code +func (o *V1RoutesPostBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes post bad request response has a 3xx status code +func (o *V1RoutesPostBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes post bad request response has a 4xx status code +func (o *V1RoutesPostBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes post bad request response has a 5xx status code +func (o *V1RoutesPostBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes post bad request response a status code equal to that given +func (o *V1RoutesPostBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 routes post bad request response +func (o *V1RoutesPostBadRequest) Code() int { + return 400 +} + +func (o *V1RoutesPostBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostBadRequest %s", 400, payload) +} + +func (o *V1RoutesPostBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostBadRequest %s", 400, payload) +} + +func (o *V1RoutesPostBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPostBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPostUnauthorized creates a V1RoutesPostUnauthorized with default headers values +func NewV1RoutesPostUnauthorized() *V1RoutesPostUnauthorized { + return &V1RoutesPostUnauthorized{} +} + +/* +V1RoutesPostUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1RoutesPostUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes post unauthorized response has a 2xx status code +func (o *V1RoutesPostUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes post unauthorized response has a 3xx status code +func (o *V1RoutesPostUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes post unauthorized response has a 4xx status code +func (o *V1RoutesPostUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes post unauthorized response has a 5xx status code +func (o *V1RoutesPostUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes post unauthorized response a status code equal to that given +func (o *V1RoutesPostUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 routes post unauthorized response +func (o *V1RoutesPostUnauthorized) Code() int { + return 401 +} + +func (o *V1RoutesPostUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostUnauthorized %s", 401, payload) +} + +func (o *V1RoutesPostUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostUnauthorized %s", 401, payload) +} + +func (o *V1RoutesPostUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPostUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPostForbidden creates a V1RoutesPostForbidden with default headers values +func NewV1RoutesPostForbidden() *V1RoutesPostForbidden { + return &V1RoutesPostForbidden{} +} + +/* +V1RoutesPostForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1RoutesPostForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes post forbidden response has a 2xx status code +func (o *V1RoutesPostForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes post forbidden response has a 3xx status code +func (o *V1RoutesPostForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes post forbidden response has a 4xx status code +func (o *V1RoutesPostForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes post forbidden response has a 5xx status code +func (o *V1RoutesPostForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes post forbidden response a status code equal to that given +func (o *V1RoutesPostForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 routes post forbidden response +func (o *V1RoutesPostForbidden) Code() int { + return 403 +} + +func (o *V1RoutesPostForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostForbidden %s", 403, payload) +} + +func (o *V1RoutesPostForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostForbidden %s", 403, payload) +} + +func (o *V1RoutesPostForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPostForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPostNotFound creates a V1RoutesPostNotFound with default headers values +func NewV1RoutesPostNotFound() *V1RoutesPostNotFound { + return &V1RoutesPostNotFound{} +} + +/* +V1RoutesPostNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1RoutesPostNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes post not found response has a 2xx status code +func (o *V1RoutesPostNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes post not found response has a 3xx status code +func (o *V1RoutesPostNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes post not found response has a 4xx status code +func (o *V1RoutesPostNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes post not found response has a 5xx status code +func (o *V1RoutesPostNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes post not found response a status code equal to that given +func (o *V1RoutesPostNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 routes post not found response +func (o *V1RoutesPostNotFound) Code() int { + return 404 +} + +func (o *V1RoutesPostNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostNotFound %s", 404, payload) +} + +func (o *V1RoutesPostNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostNotFound %s", 404, payload) +} + +func (o *V1RoutesPostNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPostNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPostConflict creates a V1RoutesPostConflict with default headers values +func NewV1RoutesPostConflict() *V1RoutesPostConflict { + return &V1RoutesPostConflict{} +} + +/* +V1RoutesPostConflict describes a response with status code 409, with default header values. + +Conflict +*/ +type V1RoutesPostConflict struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes post conflict response has a 2xx status code +func (o *V1RoutesPostConflict) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes post conflict response has a 3xx status code +func (o *V1RoutesPostConflict) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes post conflict response has a 4xx status code +func (o *V1RoutesPostConflict) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes post conflict response has a 5xx status code +func (o *V1RoutesPostConflict) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes post conflict response a status code equal to that given +func (o *V1RoutesPostConflict) IsCode(code int) bool { + return code == 409 +} + +// Code gets the status code for the v1 routes post conflict response +func (o *V1RoutesPostConflict) Code() int { + return 409 +} + +func (o *V1RoutesPostConflict) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostConflict %s", 409, payload) +} + +func (o *V1RoutesPostConflict) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostConflict %s", 409, payload) +} + +func (o *V1RoutesPostConflict) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPostConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPostUnprocessableEntity creates a V1RoutesPostUnprocessableEntity with default headers values +func NewV1RoutesPostUnprocessableEntity() *V1RoutesPostUnprocessableEntity { + return &V1RoutesPostUnprocessableEntity{} +} + +/* +V1RoutesPostUnprocessableEntity describes a response with status code 422, with default header values. + +Unprocessable Entity +*/ +type V1RoutesPostUnprocessableEntity struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes post unprocessable entity response has a 2xx status code +func (o *V1RoutesPostUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes post unprocessable entity response has a 3xx status code +func (o *V1RoutesPostUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes post unprocessable entity response has a 4xx status code +func (o *V1RoutesPostUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes post unprocessable entity response has a 5xx status code +func (o *V1RoutesPostUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes post unprocessable entity response a status code equal to that given +func (o *V1RoutesPostUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 routes post unprocessable entity response +func (o *V1RoutesPostUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1RoutesPostUnprocessableEntity) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostUnprocessableEntity %s", 422, payload) +} + +func (o *V1RoutesPostUnprocessableEntity) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostUnprocessableEntity %s", 422, payload) +} + +func (o *V1RoutesPostUnprocessableEntity) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPostUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPostInternalServerError creates a V1RoutesPostInternalServerError with default headers values +func NewV1RoutesPostInternalServerError() *V1RoutesPostInternalServerError { + return &V1RoutesPostInternalServerError{} +} + +/* +V1RoutesPostInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1RoutesPostInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes post internal server error response has a 2xx status code +func (o *V1RoutesPostInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes post internal server error response has a 3xx status code +func (o *V1RoutesPostInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes post internal server error response has a 4xx status code +func (o *V1RoutesPostInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes post internal server error response has a 5xx status code +func (o *V1RoutesPostInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 routes post internal server error response a status code equal to that given +func (o *V1RoutesPostInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 routes post internal server error response +func (o *V1RoutesPostInternalServerError) Code() int { + return 500 +} + +func (o *V1RoutesPostInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostInternalServerError %s", 500, payload) +} + +func (o *V1RoutesPostInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/routes][%d] v1RoutesPostInternalServerError %s", 500, payload) +} + +func (o *V1RoutesPostInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPostInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_put_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_put_parameters.go new file mode 100644 index 000000000000..34b98ba1e040 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_put_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// NewV1RoutesPutParams creates a new V1RoutesPutParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1RoutesPutParams() *V1RoutesPutParams { + return &V1RoutesPutParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1RoutesPutParamsWithTimeout creates a new V1RoutesPutParams object +// with the ability to set a timeout on a request. +func NewV1RoutesPutParamsWithTimeout(timeout time.Duration) *V1RoutesPutParams { + return &V1RoutesPutParams{ + timeout: timeout, + } +} + +// NewV1RoutesPutParamsWithContext creates a new V1RoutesPutParams object +// with the ability to set a context for a request. +func NewV1RoutesPutParamsWithContext(ctx context.Context) *V1RoutesPutParams { + return &V1RoutesPutParams{ + Context: ctx, + } +} + +// NewV1RoutesPutParamsWithHTTPClient creates a new V1RoutesPutParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1RoutesPutParamsWithHTTPClient(client *http.Client) *V1RoutesPutParams { + return &V1RoutesPutParams{ + HTTPClient: client, + } +} + +/* +V1RoutesPutParams contains all the parameters to send to the API endpoint + + for the v1 routes put operation. + + Typically these are written to a http.Request. +*/ +type V1RoutesPutParams struct { + + /* Body. + + Parameters for updating a route + */ + Body *models.RouteUpdate + + /* RouteID. + + Route ID + */ + RouteID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 routes put params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesPutParams) WithDefaults() *V1RoutesPutParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 routes put params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesPutParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 routes put params +func (o *V1RoutesPutParams) WithTimeout(timeout time.Duration) *V1RoutesPutParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 routes put params +func (o *V1RoutesPutParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 routes put params +func (o *V1RoutesPutParams) WithContext(ctx context.Context) *V1RoutesPutParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 routes put params +func (o *V1RoutesPutParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 routes put params +func (o *V1RoutesPutParams) WithHTTPClient(client *http.Client) *V1RoutesPutParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 routes put params +func (o *V1RoutesPutParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the v1 routes put params +func (o *V1RoutesPutParams) WithBody(body *models.RouteUpdate) *V1RoutesPutParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the v1 routes put params +func (o *V1RoutesPutParams) SetBody(body *models.RouteUpdate) { + o.Body = body +} + +// WithRouteID adds the routeID to the v1 routes put params +func (o *V1RoutesPutParams) WithRouteID(routeID string) *V1RoutesPutParams { + o.SetRouteID(routeID) + return o +} + +// SetRouteID adds the routeId to the v1 routes put params +func (o *V1RoutesPutParams) SetRouteID(routeID string) { + o.RouteID = routeID +} + +// WriteToRequest writes these params to a swagger request +func (o *V1RoutesPutParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // path param route_id + if err := r.SetPathParam("route_id", o.RouteID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_put_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_put_responses.go new file mode 100644 index 000000000000..6d1f58a349a4 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_put_responses.go @@ -0,0 +1,562 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1RoutesPutReader is a Reader for the V1RoutesPut structure. +type V1RoutesPutReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1RoutesPutReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1RoutesPutOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1RoutesPutBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1RoutesPutUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1RoutesPutForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1RoutesPutNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1RoutesPutUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1RoutesPutInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /v1/routes/{route_id}] v1.routes.put", response, response.Code()) + } +} + +// NewV1RoutesPutOK creates a V1RoutesPutOK with default headers values +func NewV1RoutesPutOK() *V1RoutesPutOK { + return &V1RoutesPutOK{} +} + +/* +V1RoutesPutOK describes a response with status code 200, with default header values. + +OK +*/ +type V1RoutesPutOK struct { + Payload *models.Route +} + +// IsSuccess returns true when this v1 routes put o k response has a 2xx status code +func (o *V1RoutesPutOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 routes put o k response has a 3xx status code +func (o *V1RoutesPutOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes put o k response has a 4xx status code +func (o *V1RoutesPutOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes put o k response has a 5xx status code +func (o *V1RoutesPutOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes put o k response a status code equal to that given +func (o *V1RoutesPutOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 routes put o k response +func (o *V1RoutesPutOK) Code() int { + return 200 +} + +func (o *V1RoutesPutOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutOK %s", 200, payload) +} + +func (o *V1RoutesPutOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutOK %s", 200, payload) +} + +func (o *V1RoutesPutOK) GetPayload() *models.Route { + return o.Payload +} + +func (o *V1RoutesPutOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Route) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPutBadRequest creates a V1RoutesPutBadRequest with default headers values +func NewV1RoutesPutBadRequest() *V1RoutesPutBadRequest { + return &V1RoutesPutBadRequest{} +} + +/* +V1RoutesPutBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1RoutesPutBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes put bad request response has a 2xx status code +func (o *V1RoutesPutBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes put bad request response has a 3xx status code +func (o *V1RoutesPutBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes put bad request response has a 4xx status code +func (o *V1RoutesPutBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes put bad request response has a 5xx status code +func (o *V1RoutesPutBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes put bad request response a status code equal to that given +func (o *V1RoutesPutBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 routes put bad request response +func (o *V1RoutesPutBadRequest) Code() int { + return 400 +} + +func (o *V1RoutesPutBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutBadRequest %s", 400, payload) +} + +func (o *V1RoutesPutBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutBadRequest %s", 400, payload) +} + +func (o *V1RoutesPutBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPutBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPutUnauthorized creates a V1RoutesPutUnauthorized with default headers values +func NewV1RoutesPutUnauthorized() *V1RoutesPutUnauthorized { + return &V1RoutesPutUnauthorized{} +} + +/* +V1RoutesPutUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1RoutesPutUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes put unauthorized response has a 2xx status code +func (o *V1RoutesPutUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes put unauthorized response has a 3xx status code +func (o *V1RoutesPutUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes put unauthorized response has a 4xx status code +func (o *V1RoutesPutUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes put unauthorized response has a 5xx status code +func (o *V1RoutesPutUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes put unauthorized response a status code equal to that given +func (o *V1RoutesPutUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 routes put unauthorized response +func (o *V1RoutesPutUnauthorized) Code() int { + return 401 +} + +func (o *V1RoutesPutUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutUnauthorized %s", 401, payload) +} + +func (o *V1RoutesPutUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutUnauthorized %s", 401, payload) +} + +func (o *V1RoutesPutUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPutUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPutForbidden creates a V1RoutesPutForbidden with default headers values +func NewV1RoutesPutForbidden() *V1RoutesPutForbidden { + return &V1RoutesPutForbidden{} +} + +/* +V1RoutesPutForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1RoutesPutForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes put forbidden response has a 2xx status code +func (o *V1RoutesPutForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes put forbidden response has a 3xx status code +func (o *V1RoutesPutForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes put forbidden response has a 4xx status code +func (o *V1RoutesPutForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes put forbidden response has a 5xx status code +func (o *V1RoutesPutForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes put forbidden response a status code equal to that given +func (o *V1RoutesPutForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 routes put forbidden response +func (o *V1RoutesPutForbidden) Code() int { + return 403 +} + +func (o *V1RoutesPutForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutForbidden %s", 403, payload) +} + +func (o *V1RoutesPutForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutForbidden %s", 403, payload) +} + +func (o *V1RoutesPutForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPutForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPutNotFound creates a V1RoutesPutNotFound with default headers values +func NewV1RoutesPutNotFound() *V1RoutesPutNotFound { + return &V1RoutesPutNotFound{} +} + +/* +V1RoutesPutNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1RoutesPutNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes put not found response has a 2xx status code +func (o *V1RoutesPutNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes put not found response has a 3xx status code +func (o *V1RoutesPutNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes put not found response has a 4xx status code +func (o *V1RoutesPutNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes put not found response has a 5xx status code +func (o *V1RoutesPutNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes put not found response a status code equal to that given +func (o *V1RoutesPutNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 routes put not found response +func (o *V1RoutesPutNotFound) Code() int { + return 404 +} + +func (o *V1RoutesPutNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutNotFound %s", 404, payload) +} + +func (o *V1RoutesPutNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutNotFound %s", 404, payload) +} + +func (o *V1RoutesPutNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPutNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPutUnprocessableEntity creates a V1RoutesPutUnprocessableEntity with default headers values +func NewV1RoutesPutUnprocessableEntity() *V1RoutesPutUnprocessableEntity { + return &V1RoutesPutUnprocessableEntity{} +} + +/* +V1RoutesPutUnprocessableEntity describes a response with status code 422, with default header values. + +Unprocessable Entity +*/ +type V1RoutesPutUnprocessableEntity struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes put unprocessable entity response has a 2xx status code +func (o *V1RoutesPutUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes put unprocessable entity response has a 3xx status code +func (o *V1RoutesPutUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes put unprocessable entity response has a 4xx status code +func (o *V1RoutesPutUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes put unprocessable entity response has a 5xx status code +func (o *V1RoutesPutUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes put unprocessable entity response a status code equal to that given +func (o *V1RoutesPutUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 routes put unprocessable entity response +func (o *V1RoutesPutUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1RoutesPutUnprocessableEntity) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutUnprocessableEntity %s", 422, payload) +} + +func (o *V1RoutesPutUnprocessableEntity) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutUnprocessableEntity %s", 422, payload) +} + +func (o *V1RoutesPutUnprocessableEntity) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPutUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesPutInternalServerError creates a V1RoutesPutInternalServerError with default headers values +func NewV1RoutesPutInternalServerError() *V1RoutesPutInternalServerError { + return &V1RoutesPutInternalServerError{} +} + +/* +V1RoutesPutInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1RoutesPutInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes put internal server error response has a 2xx status code +func (o *V1RoutesPutInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes put internal server error response has a 3xx status code +func (o *V1RoutesPutInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes put internal server error response has a 4xx status code +func (o *V1RoutesPutInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes put internal server error response has a 5xx status code +func (o *V1RoutesPutInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 routes put internal server error response a status code equal to that given +func (o *V1RoutesPutInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 routes put internal server error response +func (o *V1RoutesPutInternalServerError) Code() int { + return 500 +} + +func (o *V1RoutesPutInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutInternalServerError %s", 500, payload) +} + +func (o *V1RoutesPutInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/routes/{route_id}][%d] v1RoutesPutInternalServerError %s", 500, payload) +} + +func (o *V1RoutesPutInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesPutInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_report_get_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_report_get_parameters.go new file mode 100644 index 000000000000..cab7a51b31b3 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_report_get_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1RoutesReportGetParams creates a new V1RoutesReportGetParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1RoutesReportGetParams() *V1RoutesReportGetParams { + return &V1RoutesReportGetParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1RoutesReportGetParamsWithTimeout creates a new V1RoutesReportGetParams object +// with the ability to set a timeout on a request. +func NewV1RoutesReportGetParamsWithTimeout(timeout time.Duration) *V1RoutesReportGetParams { + return &V1RoutesReportGetParams{ + timeout: timeout, + } +} + +// NewV1RoutesReportGetParamsWithContext creates a new V1RoutesReportGetParams object +// with the ability to set a context for a request. +func NewV1RoutesReportGetParamsWithContext(ctx context.Context) *V1RoutesReportGetParams { + return &V1RoutesReportGetParams{ + Context: ctx, + } +} + +// NewV1RoutesReportGetParamsWithHTTPClient creates a new V1RoutesReportGetParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1RoutesReportGetParamsWithHTTPClient(client *http.Client) *V1RoutesReportGetParams { + return &V1RoutesReportGetParams{ + HTTPClient: client, + } +} + +/* +V1RoutesReportGetParams contains all the parameters to send to the API endpoint + + for the v1 routes report get operation. + + Typically these are written to a http.Request. +*/ +type V1RoutesReportGetParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 routes report get params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesReportGetParams) WithDefaults() *V1RoutesReportGetParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 routes report get params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1RoutesReportGetParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 routes report get params +func (o *V1RoutesReportGetParams) WithTimeout(timeout time.Duration) *V1RoutesReportGetParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 routes report get params +func (o *V1RoutesReportGetParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 routes report get params +func (o *V1RoutesReportGetParams) WithContext(ctx context.Context) *V1RoutesReportGetParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 routes report get params +func (o *V1RoutesReportGetParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 routes report get params +func (o *V1RoutesReportGetParams) WithHTTPClient(client *http.Client) *V1RoutesReportGetParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 routes report get params +func (o *V1RoutesReportGetParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *V1RoutesReportGetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_report_get_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_report_get_responses.go new file mode 100644 index 000000000000..7081aec1c94f --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/routes/v1_routes_report_get_responses.go @@ -0,0 +1,486 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package routes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1RoutesReportGetReader is a Reader for the V1RoutesReportGet structure. +type V1RoutesReportGetReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1RoutesReportGetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1RoutesReportGetOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1RoutesReportGetBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1RoutesReportGetUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1RoutesReportGetForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1RoutesReportGetNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1RoutesReportGetInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/routes/report] v1.routes.report.get", response, response.Code()) + } +} + +// NewV1RoutesReportGetOK creates a V1RoutesReportGetOK with default headers values +func NewV1RoutesReportGetOK() *V1RoutesReportGetOK { + return &V1RoutesReportGetOK{} +} + +/* +V1RoutesReportGetOK describes a response with status code 200, with default header values. + +OK +*/ +type V1RoutesReportGetOK struct { + Payload *models.RouteReport +} + +// IsSuccess returns true when this v1 routes report get o k response has a 2xx status code +func (o *V1RoutesReportGetOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 routes report get o k response has a 3xx status code +func (o *V1RoutesReportGetOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes report get o k response has a 4xx status code +func (o *V1RoutesReportGetOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes report get o k response has a 5xx status code +func (o *V1RoutesReportGetOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes report get o k response a status code equal to that given +func (o *V1RoutesReportGetOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 routes report get o k response +func (o *V1RoutesReportGetOK) Code() int { + return 200 +} + +func (o *V1RoutesReportGetOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetOK %s", 200, payload) +} + +func (o *V1RoutesReportGetOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetOK %s", 200, payload) +} + +func (o *V1RoutesReportGetOK) GetPayload() *models.RouteReport { + return o.Payload +} + +func (o *V1RoutesReportGetOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.RouteReport) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesReportGetBadRequest creates a V1RoutesReportGetBadRequest with default headers values +func NewV1RoutesReportGetBadRequest() *V1RoutesReportGetBadRequest { + return &V1RoutesReportGetBadRequest{} +} + +/* +V1RoutesReportGetBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1RoutesReportGetBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes report get bad request response has a 2xx status code +func (o *V1RoutesReportGetBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes report get bad request response has a 3xx status code +func (o *V1RoutesReportGetBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes report get bad request response has a 4xx status code +func (o *V1RoutesReportGetBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes report get bad request response has a 5xx status code +func (o *V1RoutesReportGetBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes report get bad request response a status code equal to that given +func (o *V1RoutesReportGetBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 routes report get bad request response +func (o *V1RoutesReportGetBadRequest) Code() int { + return 400 +} + +func (o *V1RoutesReportGetBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetBadRequest %s", 400, payload) +} + +func (o *V1RoutesReportGetBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetBadRequest %s", 400, payload) +} + +func (o *V1RoutesReportGetBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesReportGetBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesReportGetUnauthorized creates a V1RoutesReportGetUnauthorized with default headers values +func NewV1RoutesReportGetUnauthorized() *V1RoutesReportGetUnauthorized { + return &V1RoutesReportGetUnauthorized{} +} + +/* +V1RoutesReportGetUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1RoutesReportGetUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes report get unauthorized response has a 2xx status code +func (o *V1RoutesReportGetUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes report get unauthorized response has a 3xx status code +func (o *V1RoutesReportGetUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes report get unauthorized response has a 4xx status code +func (o *V1RoutesReportGetUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes report get unauthorized response has a 5xx status code +func (o *V1RoutesReportGetUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes report get unauthorized response a status code equal to that given +func (o *V1RoutesReportGetUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 routes report get unauthorized response +func (o *V1RoutesReportGetUnauthorized) Code() int { + return 401 +} + +func (o *V1RoutesReportGetUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetUnauthorized %s", 401, payload) +} + +func (o *V1RoutesReportGetUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetUnauthorized %s", 401, payload) +} + +func (o *V1RoutesReportGetUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesReportGetUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesReportGetForbidden creates a V1RoutesReportGetForbidden with default headers values +func NewV1RoutesReportGetForbidden() *V1RoutesReportGetForbidden { + return &V1RoutesReportGetForbidden{} +} + +/* +V1RoutesReportGetForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1RoutesReportGetForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes report get forbidden response has a 2xx status code +func (o *V1RoutesReportGetForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes report get forbidden response has a 3xx status code +func (o *V1RoutesReportGetForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes report get forbidden response has a 4xx status code +func (o *V1RoutesReportGetForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes report get forbidden response has a 5xx status code +func (o *V1RoutesReportGetForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes report get forbidden response a status code equal to that given +func (o *V1RoutesReportGetForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 routes report get forbidden response +func (o *V1RoutesReportGetForbidden) Code() int { + return 403 +} + +func (o *V1RoutesReportGetForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetForbidden %s", 403, payload) +} + +func (o *V1RoutesReportGetForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetForbidden %s", 403, payload) +} + +func (o *V1RoutesReportGetForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesReportGetForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesReportGetNotFound creates a V1RoutesReportGetNotFound with default headers values +func NewV1RoutesReportGetNotFound() *V1RoutesReportGetNotFound { + return &V1RoutesReportGetNotFound{} +} + +/* +V1RoutesReportGetNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1RoutesReportGetNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes report get not found response has a 2xx status code +func (o *V1RoutesReportGetNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes report get not found response has a 3xx status code +func (o *V1RoutesReportGetNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes report get not found response has a 4xx status code +func (o *V1RoutesReportGetNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 routes report get not found response has a 5xx status code +func (o *V1RoutesReportGetNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 routes report get not found response a status code equal to that given +func (o *V1RoutesReportGetNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 routes report get not found response +func (o *V1RoutesReportGetNotFound) Code() int { + return 404 +} + +func (o *V1RoutesReportGetNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetNotFound %s", 404, payload) +} + +func (o *V1RoutesReportGetNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetNotFound %s", 404, payload) +} + +func (o *V1RoutesReportGetNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesReportGetNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1RoutesReportGetInternalServerError creates a V1RoutesReportGetInternalServerError with default headers values +func NewV1RoutesReportGetInternalServerError() *V1RoutesReportGetInternalServerError { + return &V1RoutesReportGetInternalServerError{} +} + +/* +V1RoutesReportGetInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1RoutesReportGetInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 routes report get internal server error response has a 2xx status code +func (o *V1RoutesReportGetInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 routes report get internal server error response has a 3xx status code +func (o *V1RoutesReportGetInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 routes report get internal server error response has a 4xx status code +func (o *V1RoutesReportGetInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 routes report get internal server error response has a 5xx status code +func (o *V1RoutesReportGetInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 routes report get internal server error response a status code equal to that given +func (o *V1RoutesReportGetInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 routes report get internal server error response +func (o *V1RoutesReportGetInternalServerError) Code() int { + return 500 +} + +func (o *V1RoutesReportGetInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetInternalServerError %s", 500, payload) +} + +func (o *V1RoutesReportGetInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/routes/report][%d] v1RoutesReportGetInternalServerError %s", 500, payload) +} + +func (o *V1RoutesReportGetInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1RoutesReportGetInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/ssh_keys_client.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/ssh_keys_client.go new file mode 100644 index 000000000000..66ac214626f3 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/ssh_keys_client.go @@ -0,0 +1,270 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new ssh keys API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new ssh keys API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new ssh keys API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for ssh keys API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1SshkeysDelete(params *V1SshkeysDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysDeleteOK, error) + + V1SshkeysGet(params *V1SshkeysGetParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysGetOK, error) + + V1SshkeysGetall(params *V1SshkeysGetallParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysGetallOK, error) + + V1SshkeysPost(params *V1SshkeysPostParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysPostCreated, error) + + V1SshkeysPut(params *V1SshkeysPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysPutOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1SshkeysDelete deletes ssh key +*/ +func (a *Client) V1SshkeysDelete(params *V1SshkeysDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysDeleteOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SshkeysDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "v1.sshkeys.delete", + Method: "DELETE", + PathPattern: "/v1/ssh-keys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1SshkeysDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SshkeysDeleteOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.sshkeys.delete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SshkeysGet gets ssh key information +*/ +func (a *Client) V1SshkeysGet(params *V1SshkeysGetParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysGetOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SshkeysGetParams() + } + op := &runtime.ClientOperation{ + ID: "v1.sshkeys.get", + Method: "GET", + PathPattern: "/v1/ssh-keys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1SshkeysGetReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SshkeysGetOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.sshkeys.get: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SshkeysGetall lists SSH keys +*/ +func (a *Client) V1SshkeysGetall(params *V1SshkeysGetallParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysGetallOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SshkeysGetallParams() + } + op := &runtime.ClientOperation{ + ID: "v1.sshkeys.getall", + Method: "GET", + PathPattern: "/v1/ssh-keys", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1SshkeysGetallReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SshkeysGetallOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.sshkeys.getall: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SshkeysPost adds a new SSH key +*/ +func (a *Client) V1SshkeysPost(params *V1SshkeysPostParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysPostCreated, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SshkeysPostParams() + } + op := &runtime.ClientOperation{ + ID: "v1.sshkeys.post", + Method: "POST", + PathPattern: "/v1/ssh-keys", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1SshkeysPostReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SshkeysPostCreated) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.sshkeys.post: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SshkeysPut updates the ssh key +*/ +func (a *Client) V1SshkeysPut(params *V1SshkeysPutParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SshkeysPutOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SshkeysPutParams() + } + op := &runtime.ClientOperation{ + ID: "v1.sshkeys.put", + Method: "PUT", + PathPattern: "/v1/ssh-keys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &V1SshkeysPutReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SshkeysPutOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1.sshkeys.put: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_delete_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_delete_parameters.go new file mode 100644 index 000000000000..67dc611134f1 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_delete_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1SshkeysDeleteParams creates a new V1SshkeysDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SshkeysDeleteParams() *V1SshkeysDeleteParams { + return &V1SshkeysDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SshkeysDeleteParamsWithTimeout creates a new V1SshkeysDeleteParams object +// with the ability to set a timeout on a request. +func NewV1SshkeysDeleteParamsWithTimeout(timeout time.Duration) *V1SshkeysDeleteParams { + return &V1SshkeysDeleteParams{ + timeout: timeout, + } +} + +// NewV1SshkeysDeleteParamsWithContext creates a new V1SshkeysDeleteParams object +// with the ability to set a context for a request. +func NewV1SshkeysDeleteParamsWithContext(ctx context.Context) *V1SshkeysDeleteParams { + return &V1SshkeysDeleteParams{ + Context: ctx, + } +} + +// NewV1SshkeysDeleteParamsWithHTTPClient creates a new V1SshkeysDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SshkeysDeleteParamsWithHTTPClient(client *http.Client) *V1SshkeysDeleteParams { + return &V1SshkeysDeleteParams{ + HTTPClient: client, + } +} + +/* +V1SshkeysDeleteParams contains all the parameters to send to the API endpoint + + for the v1 sshkeys delete operation. + + Typically these are written to a http.Request. +*/ +type V1SshkeysDeleteParams struct { + + /* SshkeyID. + + SSH Key ID + */ + SshkeyID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 sshkeys delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysDeleteParams) WithDefaults() *V1SshkeysDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 sshkeys delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 sshkeys delete params +func (o *V1SshkeysDeleteParams) WithTimeout(timeout time.Duration) *V1SshkeysDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 sshkeys delete params +func (o *V1SshkeysDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 sshkeys delete params +func (o *V1SshkeysDeleteParams) WithContext(ctx context.Context) *V1SshkeysDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 sshkeys delete params +func (o *V1SshkeysDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 sshkeys delete params +func (o *V1SshkeysDeleteParams) WithHTTPClient(client *http.Client) *V1SshkeysDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 sshkeys delete params +func (o *V1SshkeysDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSshkeyID adds the sshkeyID to the v1 sshkeys delete params +func (o *V1SshkeysDeleteParams) WithSshkeyID(sshkeyID string) *V1SshkeysDeleteParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the v1 sshkeys delete params +func (o *V1SshkeysDeleteParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SshkeysDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_delete_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_delete_responses.go new file mode 100644 index 000000000000..6832171fe245 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_delete_responses.go @@ -0,0 +1,560 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1SshkeysDeleteReader is a Reader for the V1SshkeysDelete structure. +type V1SshkeysDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SshkeysDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SshkeysDeleteOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SshkeysDeleteBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1SshkeysDeleteUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1SshkeysDeleteForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1SshkeysDeleteNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 410: + result := NewV1SshkeysDeleteGone() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1SshkeysDeleteInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /v1/ssh-keys/{sshkey_id}] v1.sshkeys.delete", response, response.Code()) + } +} + +// NewV1SshkeysDeleteOK creates a V1SshkeysDeleteOK with default headers values +func NewV1SshkeysDeleteOK() *V1SshkeysDeleteOK { + return &V1SshkeysDeleteOK{} +} + +/* +V1SshkeysDeleteOK describes a response with status code 200, with default header values. + +OK +*/ +type V1SshkeysDeleteOK struct { + Payload models.Object +} + +// IsSuccess returns true when this v1 sshkeys delete o k response has a 2xx status code +func (o *V1SshkeysDeleteOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 sshkeys delete o k response has a 3xx status code +func (o *V1SshkeysDeleteOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys delete o k response has a 4xx status code +func (o *V1SshkeysDeleteOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys delete o k response has a 5xx status code +func (o *V1SshkeysDeleteOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys delete o k response a status code equal to that given +func (o *V1SshkeysDeleteOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 sshkeys delete o k response +func (o *V1SshkeysDeleteOK) Code() int { + return 200 +} + +func (o *V1SshkeysDeleteOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteOK %s", 200, payload) +} + +func (o *V1SshkeysDeleteOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteOK %s", 200, payload) +} + +func (o *V1SshkeysDeleteOK) GetPayload() models.Object { + return o.Payload +} + +func (o *V1SshkeysDeleteOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysDeleteBadRequest creates a V1SshkeysDeleteBadRequest with default headers values +func NewV1SshkeysDeleteBadRequest() *V1SshkeysDeleteBadRequest { + return &V1SshkeysDeleteBadRequest{} +} + +/* +V1SshkeysDeleteBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1SshkeysDeleteBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys delete bad request response has a 2xx status code +func (o *V1SshkeysDeleteBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys delete bad request response has a 3xx status code +func (o *V1SshkeysDeleteBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys delete bad request response has a 4xx status code +func (o *V1SshkeysDeleteBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys delete bad request response has a 5xx status code +func (o *V1SshkeysDeleteBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys delete bad request response a status code equal to that given +func (o *V1SshkeysDeleteBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 sshkeys delete bad request response +func (o *V1SshkeysDeleteBadRequest) Code() int { + return 400 +} + +func (o *V1SshkeysDeleteBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteBadRequest %s", 400, payload) +} + +func (o *V1SshkeysDeleteBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteBadRequest %s", 400, payload) +} + +func (o *V1SshkeysDeleteBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysDeleteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysDeleteUnauthorized creates a V1SshkeysDeleteUnauthorized with default headers values +func NewV1SshkeysDeleteUnauthorized() *V1SshkeysDeleteUnauthorized { + return &V1SshkeysDeleteUnauthorized{} +} + +/* +V1SshkeysDeleteUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1SshkeysDeleteUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys delete unauthorized response has a 2xx status code +func (o *V1SshkeysDeleteUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys delete unauthorized response has a 3xx status code +func (o *V1SshkeysDeleteUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys delete unauthorized response has a 4xx status code +func (o *V1SshkeysDeleteUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys delete unauthorized response has a 5xx status code +func (o *V1SshkeysDeleteUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys delete unauthorized response a status code equal to that given +func (o *V1SshkeysDeleteUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 sshkeys delete unauthorized response +func (o *V1SshkeysDeleteUnauthorized) Code() int { + return 401 +} + +func (o *V1SshkeysDeleteUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysDeleteUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysDeleteUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysDeleteUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysDeleteForbidden creates a V1SshkeysDeleteForbidden with default headers values +func NewV1SshkeysDeleteForbidden() *V1SshkeysDeleteForbidden { + return &V1SshkeysDeleteForbidden{} +} + +/* +V1SshkeysDeleteForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1SshkeysDeleteForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys delete forbidden response has a 2xx status code +func (o *V1SshkeysDeleteForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys delete forbidden response has a 3xx status code +func (o *V1SshkeysDeleteForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys delete forbidden response has a 4xx status code +func (o *V1SshkeysDeleteForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys delete forbidden response has a 5xx status code +func (o *V1SshkeysDeleteForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys delete forbidden response a status code equal to that given +func (o *V1SshkeysDeleteForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 sshkeys delete forbidden response +func (o *V1SshkeysDeleteForbidden) Code() int { + return 403 +} + +func (o *V1SshkeysDeleteForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteForbidden %s", 403, payload) +} + +func (o *V1SshkeysDeleteForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteForbidden %s", 403, payload) +} + +func (o *V1SshkeysDeleteForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysDeleteForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysDeleteNotFound creates a V1SshkeysDeleteNotFound with default headers values +func NewV1SshkeysDeleteNotFound() *V1SshkeysDeleteNotFound { + return &V1SshkeysDeleteNotFound{} +} + +/* +V1SshkeysDeleteNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1SshkeysDeleteNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys delete not found response has a 2xx status code +func (o *V1SshkeysDeleteNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys delete not found response has a 3xx status code +func (o *V1SshkeysDeleteNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys delete not found response has a 4xx status code +func (o *V1SshkeysDeleteNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys delete not found response has a 5xx status code +func (o *V1SshkeysDeleteNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys delete not found response a status code equal to that given +func (o *V1SshkeysDeleteNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 sshkeys delete not found response +func (o *V1SshkeysDeleteNotFound) Code() int { + return 404 +} + +func (o *V1SshkeysDeleteNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteNotFound %s", 404, payload) +} + +func (o *V1SshkeysDeleteNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteNotFound %s", 404, payload) +} + +func (o *V1SshkeysDeleteNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysDeleteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysDeleteGone creates a V1SshkeysDeleteGone with default headers values +func NewV1SshkeysDeleteGone() *V1SshkeysDeleteGone { + return &V1SshkeysDeleteGone{} +} + +/* +V1SshkeysDeleteGone describes a response with status code 410, with default header values. + +Gone +*/ +type V1SshkeysDeleteGone struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys delete gone response has a 2xx status code +func (o *V1SshkeysDeleteGone) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys delete gone response has a 3xx status code +func (o *V1SshkeysDeleteGone) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys delete gone response has a 4xx status code +func (o *V1SshkeysDeleteGone) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys delete gone response has a 5xx status code +func (o *V1SshkeysDeleteGone) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys delete gone response a status code equal to that given +func (o *V1SshkeysDeleteGone) IsCode(code int) bool { + return code == 410 +} + +// Code gets the status code for the v1 sshkeys delete gone response +func (o *V1SshkeysDeleteGone) Code() int { + return 410 +} + +func (o *V1SshkeysDeleteGone) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteGone %s", 410, payload) +} + +func (o *V1SshkeysDeleteGone) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteGone %s", 410, payload) +} + +func (o *V1SshkeysDeleteGone) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysDeleteGone) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysDeleteInternalServerError creates a V1SshkeysDeleteInternalServerError with default headers values +func NewV1SshkeysDeleteInternalServerError() *V1SshkeysDeleteInternalServerError { + return &V1SshkeysDeleteInternalServerError{} +} + +/* +V1SshkeysDeleteInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1SshkeysDeleteInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys delete internal server error response has a 2xx status code +func (o *V1SshkeysDeleteInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys delete internal server error response has a 3xx status code +func (o *V1SshkeysDeleteInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys delete internal server error response has a 4xx status code +func (o *V1SshkeysDeleteInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys delete internal server error response has a 5xx status code +func (o *V1SshkeysDeleteInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 sshkeys delete internal server error response a status code equal to that given +func (o *V1SshkeysDeleteInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 sshkeys delete internal server error response +func (o *V1SshkeysDeleteInternalServerError) Code() int { + return 500 +} + +func (o *V1SshkeysDeleteInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysDeleteInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysDeleteInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysDeleteInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysDeleteInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_get_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_get_parameters.go new file mode 100644 index 000000000000..fe512ee23375 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_get_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1SshkeysGetParams creates a new V1SshkeysGetParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SshkeysGetParams() *V1SshkeysGetParams { + return &V1SshkeysGetParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SshkeysGetParamsWithTimeout creates a new V1SshkeysGetParams object +// with the ability to set a timeout on a request. +func NewV1SshkeysGetParamsWithTimeout(timeout time.Duration) *V1SshkeysGetParams { + return &V1SshkeysGetParams{ + timeout: timeout, + } +} + +// NewV1SshkeysGetParamsWithContext creates a new V1SshkeysGetParams object +// with the ability to set a context for a request. +func NewV1SshkeysGetParamsWithContext(ctx context.Context) *V1SshkeysGetParams { + return &V1SshkeysGetParams{ + Context: ctx, + } +} + +// NewV1SshkeysGetParamsWithHTTPClient creates a new V1SshkeysGetParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SshkeysGetParamsWithHTTPClient(client *http.Client) *V1SshkeysGetParams { + return &V1SshkeysGetParams{ + HTTPClient: client, + } +} + +/* +V1SshkeysGetParams contains all the parameters to send to the API endpoint + + for the v1 sshkeys get operation. + + Typically these are written to a http.Request. +*/ +type V1SshkeysGetParams struct { + + /* SshkeyID. + + SSH Key ID + */ + SshkeyID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 sshkeys get params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysGetParams) WithDefaults() *V1SshkeysGetParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 sshkeys get params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysGetParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 sshkeys get params +func (o *V1SshkeysGetParams) WithTimeout(timeout time.Duration) *V1SshkeysGetParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 sshkeys get params +func (o *V1SshkeysGetParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 sshkeys get params +func (o *V1SshkeysGetParams) WithContext(ctx context.Context) *V1SshkeysGetParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 sshkeys get params +func (o *V1SshkeysGetParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 sshkeys get params +func (o *V1SshkeysGetParams) WithHTTPClient(client *http.Client) *V1SshkeysGetParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 sshkeys get params +func (o *V1SshkeysGetParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSshkeyID adds the sshkeyID to the v1 sshkeys get params +func (o *V1SshkeysGetParams) WithSshkeyID(sshkeyID string) *V1SshkeysGetParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the v1 sshkeys get params +func (o *V1SshkeysGetParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SshkeysGetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_get_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_get_responses.go new file mode 100644 index 000000000000..ffa2ff52ee23 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_get_responses.go @@ -0,0 +1,486 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1SshkeysGetReader is a Reader for the V1SshkeysGet structure. +type V1SshkeysGetReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SshkeysGetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SshkeysGetOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SshkeysGetBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1SshkeysGetUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1SshkeysGetForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1SshkeysGetNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1SshkeysGetInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/ssh-keys/{sshkey_id}] v1.sshkeys.get", response, response.Code()) + } +} + +// NewV1SshkeysGetOK creates a V1SshkeysGetOK with default headers values +func NewV1SshkeysGetOK() *V1SshkeysGetOK { + return &V1SshkeysGetOK{} +} + +/* +V1SshkeysGetOK describes a response with status code 200, with default header values. + +OK +*/ +type V1SshkeysGetOK struct { + Payload *models.WorkspaceSSHKey +} + +// IsSuccess returns true when this v1 sshkeys get o k response has a 2xx status code +func (o *V1SshkeysGetOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 sshkeys get o k response has a 3xx status code +func (o *V1SshkeysGetOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys get o k response has a 4xx status code +func (o *V1SshkeysGetOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys get o k response has a 5xx status code +func (o *V1SshkeysGetOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys get o k response a status code equal to that given +func (o *V1SshkeysGetOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 sshkeys get o k response +func (o *V1SshkeysGetOK) Code() int { + return 200 +} + +func (o *V1SshkeysGetOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetOK %s", 200, payload) +} + +func (o *V1SshkeysGetOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetOK %s", 200, payload) +} + +func (o *V1SshkeysGetOK) GetPayload() *models.WorkspaceSSHKey { + return o.Payload +} + +func (o *V1SshkeysGetOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.WorkspaceSSHKey) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetBadRequest creates a V1SshkeysGetBadRequest with default headers values +func NewV1SshkeysGetBadRequest() *V1SshkeysGetBadRequest { + return &V1SshkeysGetBadRequest{} +} + +/* +V1SshkeysGetBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1SshkeysGetBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys get bad request response has a 2xx status code +func (o *V1SshkeysGetBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys get bad request response has a 3xx status code +func (o *V1SshkeysGetBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys get bad request response has a 4xx status code +func (o *V1SshkeysGetBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys get bad request response has a 5xx status code +func (o *V1SshkeysGetBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys get bad request response a status code equal to that given +func (o *V1SshkeysGetBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 sshkeys get bad request response +func (o *V1SshkeysGetBadRequest) Code() int { + return 400 +} + +func (o *V1SshkeysGetBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetBadRequest %s", 400, payload) +} + +func (o *V1SshkeysGetBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetBadRequest %s", 400, payload) +} + +func (o *V1SshkeysGetBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetUnauthorized creates a V1SshkeysGetUnauthorized with default headers values +func NewV1SshkeysGetUnauthorized() *V1SshkeysGetUnauthorized { + return &V1SshkeysGetUnauthorized{} +} + +/* +V1SshkeysGetUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1SshkeysGetUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys get unauthorized response has a 2xx status code +func (o *V1SshkeysGetUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys get unauthorized response has a 3xx status code +func (o *V1SshkeysGetUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys get unauthorized response has a 4xx status code +func (o *V1SshkeysGetUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys get unauthorized response has a 5xx status code +func (o *V1SshkeysGetUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys get unauthorized response a status code equal to that given +func (o *V1SshkeysGetUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 sshkeys get unauthorized response +func (o *V1SshkeysGetUnauthorized) Code() int { + return 401 +} + +func (o *V1SshkeysGetUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysGetUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysGetUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetForbidden creates a V1SshkeysGetForbidden with default headers values +func NewV1SshkeysGetForbidden() *V1SshkeysGetForbidden { + return &V1SshkeysGetForbidden{} +} + +/* +V1SshkeysGetForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1SshkeysGetForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys get forbidden response has a 2xx status code +func (o *V1SshkeysGetForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys get forbidden response has a 3xx status code +func (o *V1SshkeysGetForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys get forbidden response has a 4xx status code +func (o *V1SshkeysGetForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys get forbidden response has a 5xx status code +func (o *V1SshkeysGetForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys get forbidden response a status code equal to that given +func (o *V1SshkeysGetForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 sshkeys get forbidden response +func (o *V1SshkeysGetForbidden) Code() int { + return 403 +} + +func (o *V1SshkeysGetForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetForbidden %s", 403, payload) +} + +func (o *V1SshkeysGetForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetForbidden %s", 403, payload) +} + +func (o *V1SshkeysGetForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetNotFound creates a V1SshkeysGetNotFound with default headers values +func NewV1SshkeysGetNotFound() *V1SshkeysGetNotFound { + return &V1SshkeysGetNotFound{} +} + +/* +V1SshkeysGetNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1SshkeysGetNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys get not found response has a 2xx status code +func (o *V1SshkeysGetNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys get not found response has a 3xx status code +func (o *V1SshkeysGetNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys get not found response has a 4xx status code +func (o *V1SshkeysGetNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys get not found response has a 5xx status code +func (o *V1SshkeysGetNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys get not found response a status code equal to that given +func (o *V1SshkeysGetNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 sshkeys get not found response +func (o *V1SshkeysGetNotFound) Code() int { + return 404 +} + +func (o *V1SshkeysGetNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetNotFound %s", 404, payload) +} + +func (o *V1SshkeysGetNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetNotFound %s", 404, payload) +} + +func (o *V1SshkeysGetNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetInternalServerError creates a V1SshkeysGetInternalServerError with default headers values +func NewV1SshkeysGetInternalServerError() *V1SshkeysGetInternalServerError { + return &V1SshkeysGetInternalServerError{} +} + +/* +V1SshkeysGetInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1SshkeysGetInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys get internal server error response has a 2xx status code +func (o *V1SshkeysGetInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys get internal server error response has a 3xx status code +func (o *V1SshkeysGetInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys get internal server error response has a 4xx status code +func (o *V1SshkeysGetInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys get internal server error response has a 5xx status code +func (o *V1SshkeysGetInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 sshkeys get internal server error response a status code equal to that given +func (o *V1SshkeysGetInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 sshkeys get internal server error response +func (o *V1SshkeysGetInternalServerError) Code() int { + return 500 +} + +func (o *V1SshkeysGetInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysGetInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysGetInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysGetInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_getall_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_getall_parameters.go new file mode 100644 index 000000000000..2962350c17e6 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_getall_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1SshkeysGetallParams creates a new V1SshkeysGetallParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SshkeysGetallParams() *V1SshkeysGetallParams { + return &V1SshkeysGetallParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SshkeysGetallParamsWithTimeout creates a new V1SshkeysGetallParams object +// with the ability to set a timeout on a request. +func NewV1SshkeysGetallParamsWithTimeout(timeout time.Duration) *V1SshkeysGetallParams { + return &V1SshkeysGetallParams{ + timeout: timeout, + } +} + +// NewV1SshkeysGetallParamsWithContext creates a new V1SshkeysGetallParams object +// with the ability to set a context for a request. +func NewV1SshkeysGetallParamsWithContext(ctx context.Context) *V1SshkeysGetallParams { + return &V1SshkeysGetallParams{ + Context: ctx, + } +} + +// NewV1SshkeysGetallParamsWithHTTPClient creates a new V1SshkeysGetallParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SshkeysGetallParamsWithHTTPClient(client *http.Client) *V1SshkeysGetallParams { + return &V1SshkeysGetallParams{ + HTTPClient: client, + } +} + +/* +V1SshkeysGetallParams contains all the parameters to send to the API endpoint + + for the v1 sshkeys getall operation. + + Typically these are written to a http.Request. +*/ +type V1SshkeysGetallParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 sshkeys getall params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysGetallParams) WithDefaults() *V1SshkeysGetallParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 sshkeys getall params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysGetallParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 sshkeys getall params +func (o *V1SshkeysGetallParams) WithTimeout(timeout time.Duration) *V1SshkeysGetallParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 sshkeys getall params +func (o *V1SshkeysGetallParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 sshkeys getall params +func (o *V1SshkeysGetallParams) WithContext(ctx context.Context) *V1SshkeysGetallParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 sshkeys getall params +func (o *V1SshkeysGetallParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 sshkeys getall params +func (o *V1SshkeysGetallParams) WithHTTPClient(client *http.Client) *V1SshkeysGetallParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 sshkeys getall params +func (o *V1SshkeysGetallParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SshkeysGetallParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_getall_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_getall_responses.go new file mode 100644 index 000000000000..17c0243a360f --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_getall_responses.go @@ -0,0 +1,486 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1SshkeysGetallReader is a Reader for the V1SshkeysGetall structure. +type V1SshkeysGetallReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SshkeysGetallReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SshkeysGetallOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SshkeysGetallBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1SshkeysGetallUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1SshkeysGetallForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1SshkeysGetallNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1SshkeysGetallInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/ssh-keys] v1.sshkeys.getall", response, response.Code()) + } +} + +// NewV1SshkeysGetallOK creates a V1SshkeysGetallOK with default headers values +func NewV1SshkeysGetallOK() *V1SshkeysGetallOK { + return &V1SshkeysGetallOK{} +} + +/* +V1SshkeysGetallOK describes a response with status code 200, with default header values. + +OK +*/ +type V1SshkeysGetallOK struct { + Payload *models.WorkspaceSSHKeys +} + +// IsSuccess returns true when this v1 sshkeys getall o k response has a 2xx status code +func (o *V1SshkeysGetallOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 sshkeys getall o k response has a 3xx status code +func (o *V1SshkeysGetallOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys getall o k response has a 4xx status code +func (o *V1SshkeysGetallOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys getall o k response has a 5xx status code +func (o *V1SshkeysGetallOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys getall o k response a status code equal to that given +func (o *V1SshkeysGetallOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 sshkeys getall o k response +func (o *V1SshkeysGetallOK) Code() int { + return 200 +} + +func (o *V1SshkeysGetallOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallOK %s", 200, payload) +} + +func (o *V1SshkeysGetallOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallOK %s", 200, payload) +} + +func (o *V1SshkeysGetallOK) GetPayload() *models.WorkspaceSSHKeys { + return o.Payload +} + +func (o *V1SshkeysGetallOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.WorkspaceSSHKeys) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetallBadRequest creates a V1SshkeysGetallBadRequest with default headers values +func NewV1SshkeysGetallBadRequest() *V1SshkeysGetallBadRequest { + return &V1SshkeysGetallBadRequest{} +} + +/* +V1SshkeysGetallBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1SshkeysGetallBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys getall bad request response has a 2xx status code +func (o *V1SshkeysGetallBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys getall bad request response has a 3xx status code +func (o *V1SshkeysGetallBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys getall bad request response has a 4xx status code +func (o *V1SshkeysGetallBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys getall bad request response has a 5xx status code +func (o *V1SshkeysGetallBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys getall bad request response a status code equal to that given +func (o *V1SshkeysGetallBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 sshkeys getall bad request response +func (o *V1SshkeysGetallBadRequest) Code() int { + return 400 +} + +func (o *V1SshkeysGetallBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallBadRequest %s", 400, payload) +} + +func (o *V1SshkeysGetallBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallBadRequest %s", 400, payload) +} + +func (o *V1SshkeysGetallBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetallBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetallUnauthorized creates a V1SshkeysGetallUnauthorized with default headers values +func NewV1SshkeysGetallUnauthorized() *V1SshkeysGetallUnauthorized { + return &V1SshkeysGetallUnauthorized{} +} + +/* +V1SshkeysGetallUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1SshkeysGetallUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys getall unauthorized response has a 2xx status code +func (o *V1SshkeysGetallUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys getall unauthorized response has a 3xx status code +func (o *V1SshkeysGetallUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys getall unauthorized response has a 4xx status code +func (o *V1SshkeysGetallUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys getall unauthorized response has a 5xx status code +func (o *V1SshkeysGetallUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys getall unauthorized response a status code equal to that given +func (o *V1SshkeysGetallUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 sshkeys getall unauthorized response +func (o *V1SshkeysGetallUnauthorized) Code() int { + return 401 +} + +func (o *V1SshkeysGetallUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysGetallUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysGetallUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetallUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetallForbidden creates a V1SshkeysGetallForbidden with default headers values +func NewV1SshkeysGetallForbidden() *V1SshkeysGetallForbidden { + return &V1SshkeysGetallForbidden{} +} + +/* +V1SshkeysGetallForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1SshkeysGetallForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys getall forbidden response has a 2xx status code +func (o *V1SshkeysGetallForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys getall forbidden response has a 3xx status code +func (o *V1SshkeysGetallForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys getall forbidden response has a 4xx status code +func (o *V1SshkeysGetallForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys getall forbidden response has a 5xx status code +func (o *V1SshkeysGetallForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys getall forbidden response a status code equal to that given +func (o *V1SshkeysGetallForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 sshkeys getall forbidden response +func (o *V1SshkeysGetallForbidden) Code() int { + return 403 +} + +func (o *V1SshkeysGetallForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallForbidden %s", 403, payload) +} + +func (o *V1SshkeysGetallForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallForbidden %s", 403, payload) +} + +func (o *V1SshkeysGetallForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetallForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetallNotFound creates a V1SshkeysGetallNotFound with default headers values +func NewV1SshkeysGetallNotFound() *V1SshkeysGetallNotFound { + return &V1SshkeysGetallNotFound{} +} + +/* +V1SshkeysGetallNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1SshkeysGetallNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys getall not found response has a 2xx status code +func (o *V1SshkeysGetallNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys getall not found response has a 3xx status code +func (o *V1SshkeysGetallNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys getall not found response has a 4xx status code +func (o *V1SshkeysGetallNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys getall not found response has a 5xx status code +func (o *V1SshkeysGetallNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys getall not found response a status code equal to that given +func (o *V1SshkeysGetallNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 sshkeys getall not found response +func (o *V1SshkeysGetallNotFound) Code() int { + return 404 +} + +func (o *V1SshkeysGetallNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallNotFound %s", 404, payload) +} + +func (o *V1SshkeysGetallNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallNotFound %s", 404, payload) +} + +func (o *V1SshkeysGetallNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetallNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysGetallInternalServerError creates a V1SshkeysGetallInternalServerError with default headers values +func NewV1SshkeysGetallInternalServerError() *V1SshkeysGetallInternalServerError { + return &V1SshkeysGetallInternalServerError{} +} + +/* +V1SshkeysGetallInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1SshkeysGetallInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys getall internal server error response has a 2xx status code +func (o *V1SshkeysGetallInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys getall internal server error response has a 3xx status code +func (o *V1SshkeysGetallInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys getall internal server error response has a 4xx status code +func (o *V1SshkeysGetallInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys getall internal server error response has a 5xx status code +func (o *V1SshkeysGetallInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 sshkeys getall internal server error response a status code equal to that given +func (o *V1SshkeysGetallInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 sshkeys getall internal server error response +func (o *V1SshkeysGetallInternalServerError) Code() int { + return 500 +} + +func (o *V1SshkeysGetallInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysGetallInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/ssh-keys][%d] v1SshkeysGetallInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysGetallInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysGetallInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_post_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_post_parameters.go new file mode 100644 index 000000000000..73dc1eaf5ea9 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_post_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// NewV1SshkeysPostParams creates a new V1SshkeysPostParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SshkeysPostParams() *V1SshkeysPostParams { + return &V1SshkeysPostParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SshkeysPostParamsWithTimeout creates a new V1SshkeysPostParams object +// with the ability to set a timeout on a request. +func NewV1SshkeysPostParamsWithTimeout(timeout time.Duration) *V1SshkeysPostParams { + return &V1SshkeysPostParams{ + timeout: timeout, + } +} + +// NewV1SshkeysPostParamsWithContext creates a new V1SshkeysPostParams object +// with the ability to set a context for a request. +func NewV1SshkeysPostParamsWithContext(ctx context.Context) *V1SshkeysPostParams { + return &V1SshkeysPostParams{ + Context: ctx, + } +} + +// NewV1SshkeysPostParamsWithHTTPClient creates a new V1SshkeysPostParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SshkeysPostParamsWithHTTPClient(client *http.Client) *V1SshkeysPostParams { + return &V1SshkeysPostParams{ + HTTPClient: client, + } +} + +/* +V1SshkeysPostParams contains all the parameters to send to the API endpoint + + for the v1 sshkeys post operation. + + Typically these are written to a http.Request. +*/ +type V1SshkeysPostParams struct { + + /* Body. + + Parameters for the creation of a new SSH key + */ + Body *models.CreateWorkspaceSSHKey + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 sshkeys post params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysPostParams) WithDefaults() *V1SshkeysPostParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 sshkeys post params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysPostParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 sshkeys post params +func (o *V1SshkeysPostParams) WithTimeout(timeout time.Duration) *V1SshkeysPostParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 sshkeys post params +func (o *V1SshkeysPostParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 sshkeys post params +func (o *V1SshkeysPostParams) WithContext(ctx context.Context) *V1SshkeysPostParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 sshkeys post params +func (o *V1SshkeysPostParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 sshkeys post params +func (o *V1SshkeysPostParams) WithHTTPClient(client *http.Client) *V1SshkeysPostParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 sshkeys post params +func (o *V1SshkeysPostParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the v1 sshkeys post params +func (o *V1SshkeysPostParams) WithBody(body *models.CreateWorkspaceSSHKey) *V1SshkeysPostParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the v1 sshkeys post params +func (o *V1SshkeysPostParams) SetBody(body *models.CreateWorkspaceSSHKey) { + o.Body = body +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SshkeysPostParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_post_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_post_responses.go new file mode 100644 index 000000000000..bb0ee9574577 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_post_responses.go @@ -0,0 +1,638 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1SshkeysPostReader is a Reader for the V1SshkeysPost structure. +type V1SshkeysPostReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SshkeysPostReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewV1SshkeysPostCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SshkeysPostBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1SshkeysPostUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1SshkeysPostForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1SshkeysPostNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewV1SshkeysPostConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1SshkeysPostUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1SshkeysPostInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /v1/ssh-keys] v1.sshkeys.post", response, response.Code()) + } +} + +// NewV1SshkeysPostCreated creates a V1SshkeysPostCreated with default headers values +func NewV1SshkeysPostCreated() *V1SshkeysPostCreated { + return &V1SshkeysPostCreated{} +} + +/* +V1SshkeysPostCreated describes a response with status code 201, with default header values. + +Created +*/ +type V1SshkeysPostCreated struct { + Payload *models.WorkspaceSSHKey +} + +// IsSuccess returns true when this v1 sshkeys post created response has a 2xx status code +func (o *V1SshkeysPostCreated) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 sshkeys post created response has a 3xx status code +func (o *V1SshkeysPostCreated) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys post created response has a 4xx status code +func (o *V1SshkeysPostCreated) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys post created response has a 5xx status code +func (o *V1SshkeysPostCreated) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys post created response a status code equal to that given +func (o *V1SshkeysPostCreated) IsCode(code int) bool { + return code == 201 +} + +// Code gets the status code for the v1 sshkeys post created response +func (o *V1SshkeysPostCreated) Code() int { + return 201 +} + +func (o *V1SshkeysPostCreated) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostCreated %s", 201, payload) +} + +func (o *V1SshkeysPostCreated) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostCreated %s", 201, payload) +} + +func (o *V1SshkeysPostCreated) GetPayload() *models.WorkspaceSSHKey { + return o.Payload +} + +func (o *V1SshkeysPostCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.WorkspaceSSHKey) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPostBadRequest creates a V1SshkeysPostBadRequest with default headers values +func NewV1SshkeysPostBadRequest() *V1SshkeysPostBadRequest { + return &V1SshkeysPostBadRequest{} +} + +/* +V1SshkeysPostBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1SshkeysPostBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys post bad request response has a 2xx status code +func (o *V1SshkeysPostBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys post bad request response has a 3xx status code +func (o *V1SshkeysPostBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys post bad request response has a 4xx status code +func (o *V1SshkeysPostBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys post bad request response has a 5xx status code +func (o *V1SshkeysPostBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys post bad request response a status code equal to that given +func (o *V1SshkeysPostBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 sshkeys post bad request response +func (o *V1SshkeysPostBadRequest) Code() int { + return 400 +} + +func (o *V1SshkeysPostBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostBadRequest %s", 400, payload) +} + +func (o *V1SshkeysPostBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostBadRequest %s", 400, payload) +} + +func (o *V1SshkeysPostBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPostBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPostUnauthorized creates a V1SshkeysPostUnauthorized with default headers values +func NewV1SshkeysPostUnauthorized() *V1SshkeysPostUnauthorized { + return &V1SshkeysPostUnauthorized{} +} + +/* +V1SshkeysPostUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1SshkeysPostUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys post unauthorized response has a 2xx status code +func (o *V1SshkeysPostUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys post unauthorized response has a 3xx status code +func (o *V1SshkeysPostUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys post unauthorized response has a 4xx status code +func (o *V1SshkeysPostUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys post unauthorized response has a 5xx status code +func (o *V1SshkeysPostUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys post unauthorized response a status code equal to that given +func (o *V1SshkeysPostUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 sshkeys post unauthorized response +func (o *V1SshkeysPostUnauthorized) Code() int { + return 401 +} + +func (o *V1SshkeysPostUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysPostUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysPostUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPostUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPostForbidden creates a V1SshkeysPostForbidden with default headers values +func NewV1SshkeysPostForbidden() *V1SshkeysPostForbidden { + return &V1SshkeysPostForbidden{} +} + +/* +V1SshkeysPostForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1SshkeysPostForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys post forbidden response has a 2xx status code +func (o *V1SshkeysPostForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys post forbidden response has a 3xx status code +func (o *V1SshkeysPostForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys post forbidden response has a 4xx status code +func (o *V1SshkeysPostForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys post forbidden response has a 5xx status code +func (o *V1SshkeysPostForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys post forbidden response a status code equal to that given +func (o *V1SshkeysPostForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 sshkeys post forbidden response +func (o *V1SshkeysPostForbidden) Code() int { + return 403 +} + +func (o *V1SshkeysPostForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostForbidden %s", 403, payload) +} + +func (o *V1SshkeysPostForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostForbidden %s", 403, payload) +} + +func (o *V1SshkeysPostForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPostForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPostNotFound creates a V1SshkeysPostNotFound with default headers values +func NewV1SshkeysPostNotFound() *V1SshkeysPostNotFound { + return &V1SshkeysPostNotFound{} +} + +/* +V1SshkeysPostNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1SshkeysPostNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys post not found response has a 2xx status code +func (o *V1SshkeysPostNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys post not found response has a 3xx status code +func (o *V1SshkeysPostNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys post not found response has a 4xx status code +func (o *V1SshkeysPostNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys post not found response has a 5xx status code +func (o *V1SshkeysPostNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys post not found response a status code equal to that given +func (o *V1SshkeysPostNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 sshkeys post not found response +func (o *V1SshkeysPostNotFound) Code() int { + return 404 +} + +func (o *V1SshkeysPostNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostNotFound %s", 404, payload) +} + +func (o *V1SshkeysPostNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostNotFound %s", 404, payload) +} + +func (o *V1SshkeysPostNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPostNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPostConflict creates a V1SshkeysPostConflict with default headers values +func NewV1SshkeysPostConflict() *V1SshkeysPostConflict { + return &V1SshkeysPostConflict{} +} + +/* +V1SshkeysPostConflict describes a response with status code 409, with default header values. + +Conflict +*/ +type V1SshkeysPostConflict struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys post conflict response has a 2xx status code +func (o *V1SshkeysPostConflict) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys post conflict response has a 3xx status code +func (o *V1SshkeysPostConflict) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys post conflict response has a 4xx status code +func (o *V1SshkeysPostConflict) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys post conflict response has a 5xx status code +func (o *V1SshkeysPostConflict) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys post conflict response a status code equal to that given +func (o *V1SshkeysPostConflict) IsCode(code int) bool { + return code == 409 +} + +// Code gets the status code for the v1 sshkeys post conflict response +func (o *V1SshkeysPostConflict) Code() int { + return 409 +} + +func (o *V1SshkeysPostConflict) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostConflict %s", 409, payload) +} + +func (o *V1SshkeysPostConflict) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostConflict %s", 409, payload) +} + +func (o *V1SshkeysPostConflict) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPostConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPostUnprocessableEntity creates a V1SshkeysPostUnprocessableEntity with default headers values +func NewV1SshkeysPostUnprocessableEntity() *V1SshkeysPostUnprocessableEntity { + return &V1SshkeysPostUnprocessableEntity{} +} + +/* +V1SshkeysPostUnprocessableEntity describes a response with status code 422, with default header values. + +Unprocessable Entity +*/ +type V1SshkeysPostUnprocessableEntity struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys post unprocessable entity response has a 2xx status code +func (o *V1SshkeysPostUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys post unprocessable entity response has a 3xx status code +func (o *V1SshkeysPostUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys post unprocessable entity response has a 4xx status code +func (o *V1SshkeysPostUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys post unprocessable entity response has a 5xx status code +func (o *V1SshkeysPostUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys post unprocessable entity response a status code equal to that given +func (o *V1SshkeysPostUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 sshkeys post unprocessable entity response +func (o *V1SshkeysPostUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SshkeysPostUnprocessableEntity) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostUnprocessableEntity %s", 422, payload) +} + +func (o *V1SshkeysPostUnprocessableEntity) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostUnprocessableEntity %s", 422, payload) +} + +func (o *V1SshkeysPostUnprocessableEntity) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPostUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPostInternalServerError creates a V1SshkeysPostInternalServerError with default headers values +func NewV1SshkeysPostInternalServerError() *V1SshkeysPostInternalServerError { + return &V1SshkeysPostInternalServerError{} +} + +/* +V1SshkeysPostInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1SshkeysPostInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys post internal server error response has a 2xx status code +func (o *V1SshkeysPostInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys post internal server error response has a 3xx status code +func (o *V1SshkeysPostInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys post internal server error response has a 4xx status code +func (o *V1SshkeysPostInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys post internal server error response has a 5xx status code +func (o *V1SshkeysPostInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 sshkeys post internal server error response a status code equal to that given +func (o *V1SshkeysPostInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 sshkeys post internal server error response +func (o *V1SshkeysPostInternalServerError) Code() int { + return 500 +} + +func (o *V1SshkeysPostInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysPostInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/ssh-keys][%d] v1SshkeysPostInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysPostInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPostInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_put_parameters.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_put_parameters.go new file mode 100644 index 000000000000..7384b6911fa8 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_put_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// NewV1SshkeysPutParams creates a new V1SshkeysPutParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SshkeysPutParams() *V1SshkeysPutParams { + return &V1SshkeysPutParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SshkeysPutParamsWithTimeout creates a new V1SshkeysPutParams object +// with the ability to set a timeout on a request. +func NewV1SshkeysPutParamsWithTimeout(timeout time.Duration) *V1SshkeysPutParams { + return &V1SshkeysPutParams{ + timeout: timeout, + } +} + +// NewV1SshkeysPutParamsWithContext creates a new V1SshkeysPutParams object +// with the ability to set a context for a request. +func NewV1SshkeysPutParamsWithContext(ctx context.Context) *V1SshkeysPutParams { + return &V1SshkeysPutParams{ + Context: ctx, + } +} + +// NewV1SshkeysPutParamsWithHTTPClient creates a new V1SshkeysPutParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SshkeysPutParamsWithHTTPClient(client *http.Client) *V1SshkeysPutParams { + return &V1SshkeysPutParams{ + HTTPClient: client, + } +} + +/* +V1SshkeysPutParams contains all the parameters to send to the API endpoint + + for the v1 sshkeys put operation. + + Typically these are written to a http.Request. +*/ +type V1SshkeysPutParams struct { + + /* Body. + + Parameter for updating SSH key + */ + Body *models.UpdateWorkspaceSSHKey + + /* SshkeyID. + + SSH Key ID + */ + SshkeyID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 sshkeys put params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysPutParams) WithDefaults() *V1SshkeysPutParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 sshkeys put params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SshkeysPutParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 sshkeys put params +func (o *V1SshkeysPutParams) WithTimeout(timeout time.Duration) *V1SshkeysPutParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 sshkeys put params +func (o *V1SshkeysPutParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 sshkeys put params +func (o *V1SshkeysPutParams) WithContext(ctx context.Context) *V1SshkeysPutParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 sshkeys put params +func (o *V1SshkeysPutParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 sshkeys put params +func (o *V1SshkeysPutParams) WithHTTPClient(client *http.Client) *V1SshkeysPutParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 sshkeys put params +func (o *V1SshkeysPutParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the v1 sshkeys put params +func (o *V1SshkeysPutParams) WithBody(body *models.UpdateWorkspaceSSHKey) *V1SshkeysPutParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the v1 sshkeys put params +func (o *V1SshkeysPutParams) SetBody(body *models.UpdateWorkspaceSSHKey) { + o.Body = body +} + +// WithSshkeyID adds the sshkeyID to the v1 sshkeys put params +func (o *V1SshkeysPutParams) WithSshkeyID(sshkeyID string) *V1SshkeysPutParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the v1 sshkeys put params +func (o *V1SshkeysPutParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SshkeysPutParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_put_responses.go b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_put_responses.go new file mode 100644 index 000000000000..10a4c21c4a3b --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/client/ssh_keys/v1_sshkeys_put_responses.go @@ -0,0 +1,638 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package ssh_keys + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/power/models" +) + +// V1SshkeysPutReader is a Reader for the V1SshkeysPut structure. +type V1SshkeysPutReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SshkeysPutReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SshkeysPutOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SshkeysPutBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewV1SshkeysPutUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 403: + result := NewV1SshkeysPutForbidden() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1SshkeysPutNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewV1SshkeysPutConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 410: + result := NewV1SshkeysPutGone() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewV1SshkeysPutInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /v1/ssh-keys/{sshkey_id}] v1.sshkeys.put", response, response.Code()) + } +} + +// NewV1SshkeysPutOK creates a V1SshkeysPutOK with default headers values +func NewV1SshkeysPutOK() *V1SshkeysPutOK { + return &V1SshkeysPutOK{} +} + +/* +V1SshkeysPutOK describes a response with status code 200, with default header values. + +OK +*/ +type V1SshkeysPutOK struct { + Payload *models.WorkspaceSSHKey +} + +// IsSuccess returns true when this v1 sshkeys put o k response has a 2xx status code +func (o *V1SshkeysPutOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 sshkeys put o k response has a 3xx status code +func (o *V1SshkeysPutOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys put o k response has a 4xx status code +func (o *V1SshkeysPutOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys put o k response has a 5xx status code +func (o *V1SshkeysPutOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys put o k response a status code equal to that given +func (o *V1SshkeysPutOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 sshkeys put o k response +func (o *V1SshkeysPutOK) Code() int { + return 200 +} + +func (o *V1SshkeysPutOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutOK %s", 200, payload) +} + +func (o *V1SshkeysPutOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutOK %s", 200, payload) +} + +func (o *V1SshkeysPutOK) GetPayload() *models.WorkspaceSSHKey { + return o.Payload +} + +func (o *V1SshkeysPutOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.WorkspaceSSHKey) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPutBadRequest creates a V1SshkeysPutBadRequest with default headers values +func NewV1SshkeysPutBadRequest() *V1SshkeysPutBadRequest { + return &V1SshkeysPutBadRequest{} +} + +/* +V1SshkeysPutBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type V1SshkeysPutBadRequest struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys put bad request response has a 2xx status code +func (o *V1SshkeysPutBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys put bad request response has a 3xx status code +func (o *V1SshkeysPutBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys put bad request response has a 4xx status code +func (o *V1SshkeysPutBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys put bad request response has a 5xx status code +func (o *V1SshkeysPutBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys put bad request response a status code equal to that given +func (o *V1SshkeysPutBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 sshkeys put bad request response +func (o *V1SshkeysPutBadRequest) Code() int { + return 400 +} + +func (o *V1SshkeysPutBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutBadRequest %s", 400, payload) +} + +func (o *V1SshkeysPutBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutBadRequest %s", 400, payload) +} + +func (o *V1SshkeysPutBadRequest) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPutBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPutUnauthorized creates a V1SshkeysPutUnauthorized with default headers values +func NewV1SshkeysPutUnauthorized() *V1SshkeysPutUnauthorized { + return &V1SshkeysPutUnauthorized{} +} + +/* +V1SshkeysPutUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type V1SshkeysPutUnauthorized struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys put unauthorized response has a 2xx status code +func (o *V1SshkeysPutUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys put unauthorized response has a 3xx status code +func (o *V1SshkeysPutUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys put unauthorized response has a 4xx status code +func (o *V1SshkeysPutUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys put unauthorized response has a 5xx status code +func (o *V1SshkeysPutUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys put unauthorized response a status code equal to that given +func (o *V1SshkeysPutUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the v1 sshkeys put unauthorized response +func (o *V1SshkeysPutUnauthorized) Code() int { + return 401 +} + +func (o *V1SshkeysPutUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysPutUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutUnauthorized %s", 401, payload) +} + +func (o *V1SshkeysPutUnauthorized) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPutUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPutForbidden creates a V1SshkeysPutForbidden with default headers values +func NewV1SshkeysPutForbidden() *V1SshkeysPutForbidden { + return &V1SshkeysPutForbidden{} +} + +/* +V1SshkeysPutForbidden describes a response with status code 403, with default header values. + +Forbidden +*/ +type V1SshkeysPutForbidden struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys put forbidden response has a 2xx status code +func (o *V1SshkeysPutForbidden) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys put forbidden response has a 3xx status code +func (o *V1SshkeysPutForbidden) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys put forbidden response has a 4xx status code +func (o *V1SshkeysPutForbidden) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys put forbidden response has a 5xx status code +func (o *V1SshkeysPutForbidden) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys put forbidden response a status code equal to that given +func (o *V1SshkeysPutForbidden) IsCode(code int) bool { + return code == 403 +} + +// Code gets the status code for the v1 sshkeys put forbidden response +func (o *V1SshkeysPutForbidden) Code() int { + return 403 +} + +func (o *V1SshkeysPutForbidden) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutForbidden %s", 403, payload) +} + +func (o *V1SshkeysPutForbidden) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutForbidden %s", 403, payload) +} + +func (o *V1SshkeysPutForbidden) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPutForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPutNotFound creates a V1SshkeysPutNotFound with default headers values +func NewV1SshkeysPutNotFound() *V1SshkeysPutNotFound { + return &V1SshkeysPutNotFound{} +} + +/* +V1SshkeysPutNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type V1SshkeysPutNotFound struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys put not found response has a 2xx status code +func (o *V1SshkeysPutNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys put not found response has a 3xx status code +func (o *V1SshkeysPutNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys put not found response has a 4xx status code +func (o *V1SshkeysPutNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys put not found response has a 5xx status code +func (o *V1SshkeysPutNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys put not found response a status code equal to that given +func (o *V1SshkeysPutNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 sshkeys put not found response +func (o *V1SshkeysPutNotFound) Code() int { + return 404 +} + +func (o *V1SshkeysPutNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutNotFound %s", 404, payload) +} + +func (o *V1SshkeysPutNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutNotFound %s", 404, payload) +} + +func (o *V1SshkeysPutNotFound) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPutNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPutConflict creates a V1SshkeysPutConflict with default headers values +func NewV1SshkeysPutConflict() *V1SshkeysPutConflict { + return &V1SshkeysPutConflict{} +} + +/* +V1SshkeysPutConflict describes a response with status code 409, with default header values. + +Conflict +*/ +type V1SshkeysPutConflict struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys put conflict response has a 2xx status code +func (o *V1SshkeysPutConflict) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys put conflict response has a 3xx status code +func (o *V1SshkeysPutConflict) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys put conflict response has a 4xx status code +func (o *V1SshkeysPutConflict) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys put conflict response has a 5xx status code +func (o *V1SshkeysPutConflict) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys put conflict response a status code equal to that given +func (o *V1SshkeysPutConflict) IsCode(code int) bool { + return code == 409 +} + +// Code gets the status code for the v1 sshkeys put conflict response +func (o *V1SshkeysPutConflict) Code() int { + return 409 +} + +func (o *V1SshkeysPutConflict) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutConflict %s", 409, payload) +} + +func (o *V1SshkeysPutConflict) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutConflict %s", 409, payload) +} + +func (o *V1SshkeysPutConflict) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPutConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPutGone creates a V1SshkeysPutGone with default headers values +func NewV1SshkeysPutGone() *V1SshkeysPutGone { + return &V1SshkeysPutGone{} +} + +/* +V1SshkeysPutGone describes a response with status code 410, with default header values. + +Gone +*/ +type V1SshkeysPutGone struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys put gone response has a 2xx status code +func (o *V1SshkeysPutGone) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys put gone response has a 3xx status code +func (o *V1SshkeysPutGone) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys put gone response has a 4xx status code +func (o *V1SshkeysPutGone) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 sshkeys put gone response has a 5xx status code +func (o *V1SshkeysPutGone) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 sshkeys put gone response a status code equal to that given +func (o *V1SshkeysPutGone) IsCode(code int) bool { + return code == 410 +} + +// Code gets the status code for the v1 sshkeys put gone response +func (o *V1SshkeysPutGone) Code() int { + return 410 +} + +func (o *V1SshkeysPutGone) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutGone %s", 410, payload) +} + +func (o *V1SshkeysPutGone) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutGone %s", 410, payload) +} + +func (o *V1SshkeysPutGone) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPutGone) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SshkeysPutInternalServerError creates a V1SshkeysPutInternalServerError with default headers values +func NewV1SshkeysPutInternalServerError() *V1SshkeysPutInternalServerError { + return &V1SshkeysPutInternalServerError{} +} + +/* +V1SshkeysPutInternalServerError describes a response with status code 500, with default header values. + +Internal Server Error +*/ +type V1SshkeysPutInternalServerError struct { + Payload *models.Error +} + +// IsSuccess returns true when this v1 sshkeys put internal server error response has a 2xx status code +func (o *V1SshkeysPutInternalServerError) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 sshkeys put internal server error response has a 3xx status code +func (o *V1SshkeysPutInternalServerError) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 sshkeys put internal server error response has a 4xx status code +func (o *V1SshkeysPutInternalServerError) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 sshkeys put internal server error response has a 5xx status code +func (o *V1SshkeysPutInternalServerError) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 sshkeys put internal server error response a status code equal to that given +func (o *V1SshkeysPutInternalServerError) IsCode(code int) bool { + return code == 500 +} + +// Code gets the status code for the v1 sshkeys put internal server error response +func (o *V1SshkeysPutInternalServerError) Code() int { + return 500 +} + +func (o *V1SshkeysPutInternalServerError) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysPutInternalServerError) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /v1/ssh-keys/{sshkey_id}][%d] v1SshkeysPutInternalServerError %s", 500, payload) +} + +func (o *V1SshkeysPutInternalServerError) GetPayload() *models.Error { + return o.Payload +} + +func (o *V1SshkeysPutInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Error) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/create_server_virtual_serial_number.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/create_server_virtual_serial_number.go index d01b210d13e9..a69712d6909c 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/create_server_virtual_serial_number.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/create_server_virtual_serial_number.go @@ -25,6 +25,9 @@ type CreateServerVirtualSerialNumber struct { // Provide an existing reserved Virtual Serial Number or specify 'auto-assign' for auto generated Virtual Serial Number. // Required: true Serial *string `json:"serial"` + + // software tier + SoftwareTier SoftwareTier `json:"softwareTier,omitempty"` } // Validate validates this create server virtual serial number @@ -35,6 +38,10 @@ func (m *CreateServerVirtualSerialNumber) Validate(formats strfmt.Registry) erro res = append(res, err) } + if err := m.validateSoftwareTier(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -50,8 +57,52 @@ func (m *CreateServerVirtualSerialNumber) validateSerial(formats strfmt.Registry return nil } -// ContextValidate validates this create server virtual serial number based on context it is used +func (m *CreateServerVirtualSerialNumber) validateSoftwareTier(formats strfmt.Registry) error { + if swag.IsZero(m.SoftwareTier) { // not required + return nil + } + + if err := m.SoftwareTier.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("softwareTier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("softwareTier") + } + return err + } + + return nil +} + +// ContextValidate validate this create server virtual serial number based on the context it is used func (m *CreateServerVirtualSerialNumber) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSoftwareTier(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateServerVirtualSerialNumber) contextValidateSoftwareTier(ctx context.Context, formats strfmt.Registry) error { + + if swag.IsZero(m.SoftwareTier) { // not required + return nil + } + + if err := m.SoftwareTier.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("softwareTier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("softwareTier") + } + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/create_workspace_ssh_key.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/create_workspace_ssh_key.go new file mode 100644 index 000000000000..c717df6dbed8 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/create_workspace_ssh_key.go @@ -0,0 +1,152 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateWorkspaceSSHKey create workspace SSH key +// +// swagger:model CreateWorkspaceSSHKey +type CreateWorkspaceSSHKey struct { + + // Description of the sshkey + Description string `json:"description,omitempty" datastore:"description"` + + // User defined name for the SSH key + // Required: true + // Max Length: 128 + // Pattern: ^[A-Za-z0-9-_]+(?: +[A-Za-z0-9-_]+)*$ + Name *string `json:"name" datastore:"name"` + + // SSH RSA key + // Required: true + SSHKey *string `json:"sshKey" datastore:"sshKey"` + + // Visibility of the sshkey; workspace suggests ssh-key is only accessible in a workspace, account suggests ssh-key is accessible throughout an account + // Enum: ["account","workspace"] + Visibility *string `json:"visibility,omitempty" datastore:"visibility"` +} + +// Validate validates this create workspace SSH key +func (m *CreateWorkspaceSSHKey) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSSHKey(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVisibility(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateWorkspaceSSHKey) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 128); err != nil { + return err + } + + if err := validate.Pattern("name", "body", *m.Name, `^[A-Za-z0-9-_]+(?: +[A-Za-z0-9-_]+)*$`); err != nil { + return err + } + + return nil +} + +func (m *CreateWorkspaceSSHKey) validateSSHKey(formats strfmt.Registry) error { + + if err := validate.Required("sshKey", "body", m.SSHKey); err != nil { + return err + } + + return nil +} + +var createWorkspaceSshKeyTypeVisibilityPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["account","workspace"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + createWorkspaceSshKeyTypeVisibilityPropEnum = append(createWorkspaceSshKeyTypeVisibilityPropEnum, v) + } +} + +const ( + + // CreateWorkspaceSSHKeyVisibilityAccount captures enum value "account" + CreateWorkspaceSSHKeyVisibilityAccount string = "account" + + // CreateWorkspaceSSHKeyVisibilityWorkspace captures enum value "workspace" + CreateWorkspaceSSHKeyVisibilityWorkspace string = "workspace" +) + +// prop value enum +func (m *CreateWorkspaceSSHKey) validateVisibilityEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, createWorkspaceSshKeyTypeVisibilityPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *CreateWorkspaceSSHKey) validateVisibility(formats strfmt.Registry) error { + if swag.IsZero(m.Visibility) { // not required + return nil + } + + // value enum + if err := m.validateVisibilityEnum("visibility", "body", *m.Visibility); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create workspace SSH key based on context it is used +func (m *CreateWorkspaceSSHKey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateWorkspaceSSHKey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateWorkspaceSSHKey) UnmarshalBinary(b []byte) error { + var res CreateWorkspaceSSHKey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/get_server_virtual_serial_number.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/get_server_virtual_serial_number.go index e3148136053a..116a64543a26 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/get_server_virtual_serial_number.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/get_server_virtual_serial_number.go @@ -26,6 +26,9 @@ type GetServerVirtualSerialNumber struct { // Virtual Serial Number // Required: true Serial *string `json:"serial"` + + // software tier + SoftwareTier SoftwareTier `json:"softwareTier,omitempty"` } // Validate validates this get server virtual serial number @@ -40,6 +43,10 @@ func (m *GetServerVirtualSerialNumber) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateSoftwareTier(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -64,8 +71,52 @@ func (m *GetServerVirtualSerialNumber) validateSerial(formats strfmt.Registry) e return nil } -// ContextValidate validates this get server virtual serial number based on context it is used +func (m *GetServerVirtualSerialNumber) validateSoftwareTier(formats strfmt.Registry) error { + if swag.IsZero(m.SoftwareTier) { // not required + return nil + } + + if err := m.SoftwareTier.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("softwareTier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("softwareTier") + } + return err + } + + return nil +} + +// ContextValidate validate this get server virtual serial number based on the context it is used func (m *GetServerVirtualSerialNumber) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSoftwareTier(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *GetServerVirtualSerialNumber) contextValidateSoftwareTier(ctx context.Context, formats strfmt.Registry) error { + + if swag.IsZero(m.SoftwareTier) { // not required + return nil + } + + if err := m.SoftwareTier.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("softwareTier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("softwareTier") + } + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/network.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/network.go index d6a16ba15019..788d9681e4a5 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/network.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/network.go @@ -24,6 +24,14 @@ type Network struct { // access config AccessConfig AccessConfig `json:"accessConfig,omitempty"` + // Indicates if the network is advertised externally of the workspace to PER and\or peer networks. + // Enum: ["enable","disable"] + Advertise string `json:"advertise,omitempty"` + + // Indicates if the ARP broadcast is enabled + // Enum: ["enable","disable"] + ArpBroadcast string `json:"arpBroadcast,omitempty"` + // Network in CIDR notation (192.168.0.0/24) // Required: true Cidr *string `json:"cidr"` @@ -98,6 +106,14 @@ func (m *Network) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateAdvertise(formats); err != nil { + res = append(res, err) + } + + if err := m.validateArpBroadcast(formats); err != nil { + res = append(res, err) + } + if err := m.validateCidr(formats); err != nil { res = append(res, err) } @@ -169,6 +185,90 @@ func (m *Network) validateAccessConfig(formats strfmt.Registry) error { return nil } +var networkTypeAdvertisePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + networkTypeAdvertisePropEnum = append(networkTypeAdvertisePropEnum, v) + } +} + +const ( + + // NetworkAdvertiseEnable captures enum value "enable" + NetworkAdvertiseEnable string = "enable" + + // NetworkAdvertiseDisable captures enum value "disable" + NetworkAdvertiseDisable string = "disable" +) + +// prop value enum +func (m *Network) validateAdvertiseEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, networkTypeAdvertisePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Network) validateAdvertise(formats strfmt.Registry) error { + if swag.IsZero(m.Advertise) { // not required + return nil + } + + // value enum + if err := m.validateAdvertiseEnum("advertise", "body", m.Advertise); err != nil { + return err + } + + return nil +} + +var networkTypeArpBroadcastPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + networkTypeArpBroadcastPropEnum = append(networkTypeArpBroadcastPropEnum, v) + } +} + +const ( + + // NetworkArpBroadcastEnable captures enum value "enable" + NetworkArpBroadcastEnable string = "enable" + + // NetworkArpBroadcastDisable captures enum value "disable" + NetworkArpBroadcastDisable string = "disable" +) + +// prop value enum +func (m *Network) validateArpBroadcastEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, networkTypeArpBroadcastPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Network) validateArpBroadcast(formats strfmt.Registry) error { + if swag.IsZero(m.ArpBroadcast) { // not required + return nil + } + + // value enum + if err := m.validateArpBroadcastEnum("arpBroadcast", "body", m.ArpBroadcast); err != nil { + return err + } + + return nil +} + func (m *Network) validateCidr(formats strfmt.Registry) error { if err := validate.Required("cidr", "body", m.Cidr); err != nil { diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_create.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_create.go index 3aaa8c1b5eb4..cbc689d5d4bb 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_create.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_create.go @@ -25,6 +25,14 @@ type NetworkCreate struct { // access config AccessConfig AccessConfig `json:"accessConfig,omitempty"` + // Indicates if the network is advertised externally of the workspace to PER and\or peer networks + // Enum: ["enable","disable"] + Advertise *string `json:"advertise,omitempty"` + + // Indicates if ARP broadcast is enabled + // Enum: ["enable","disable"] + ArpBroadcast *string `json:"arpBroadcast,omitempty"` + // Network in CIDR notation (192.168.0.0/24) Cidr string `json:"cidr,omitempty"` @@ -46,6 +54,8 @@ type NetworkCreate struct { Mtu *int64 `json:"mtu,omitempty"` // Network Name + // Max Length: 128 + // Pattern: ^[a-zA-Z0-9-_][a-zA-Z0-9-_]*$ Name string `json:"name,omitempty"` // Network Peer information @@ -68,6 +78,14 @@ func (m *NetworkCreate) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateAdvertise(formats); err != nil { + res = append(res, err) + } + + if err := m.validateArpBroadcast(formats); err != nil { + res = append(res, err) + } + if err := m.validateIPAddressRanges(formats); err != nil { res = append(res, err) } @@ -76,6 +94,10 @@ func (m *NetworkCreate) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + if err := m.validatePeer(formats); err != nil { res = append(res, err) } @@ -111,6 +133,90 @@ func (m *NetworkCreate) validateAccessConfig(formats strfmt.Registry) error { return nil } +var networkCreateTypeAdvertisePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + networkCreateTypeAdvertisePropEnum = append(networkCreateTypeAdvertisePropEnum, v) + } +} + +const ( + + // NetworkCreateAdvertiseEnable captures enum value "enable" + NetworkCreateAdvertiseEnable string = "enable" + + // NetworkCreateAdvertiseDisable captures enum value "disable" + NetworkCreateAdvertiseDisable string = "disable" +) + +// prop value enum +func (m *NetworkCreate) validateAdvertiseEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, networkCreateTypeAdvertisePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *NetworkCreate) validateAdvertise(formats strfmt.Registry) error { + if swag.IsZero(m.Advertise) { // not required + return nil + } + + // value enum + if err := m.validateAdvertiseEnum("advertise", "body", *m.Advertise); err != nil { + return err + } + + return nil +} + +var networkCreateTypeArpBroadcastPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + networkCreateTypeArpBroadcastPropEnum = append(networkCreateTypeArpBroadcastPropEnum, v) + } +} + +const ( + + // NetworkCreateArpBroadcastEnable captures enum value "enable" + NetworkCreateArpBroadcastEnable string = "enable" + + // NetworkCreateArpBroadcastDisable captures enum value "disable" + NetworkCreateArpBroadcastDisable string = "disable" +) + +// prop value enum +func (m *NetworkCreate) validateArpBroadcastEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, networkCreateTypeArpBroadcastPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *NetworkCreate) validateArpBroadcast(formats strfmt.Registry) error { + if swag.IsZero(m.ArpBroadcast) { // not required + return nil + } + + // value enum + if err := m.validateArpBroadcastEnum("arpBroadcast", "body", *m.ArpBroadcast); err != nil { + return err + } + + return nil +} + func (m *NetworkCreate) validateIPAddressRanges(formats strfmt.Registry) error { if swag.IsZero(m.IPAddressRanges) { // not required return nil @@ -153,6 +259,22 @@ func (m *NetworkCreate) validateMtu(formats strfmt.Registry) error { return nil } +func (m *NetworkCreate) validateName(formats strfmt.Registry) error { + if swag.IsZero(m.Name) { // not required + return nil + } + + if err := validate.MaxLength("name", "body", m.Name, 128); err != nil { + return err + } + + if err := validate.Pattern("name", "body", m.Name, `^[a-zA-Z0-9-_][a-zA-Z0-9-_]*$`); err != nil { + return err + } + + return nil +} + func (m *NetworkCreate) validatePeer(formats strfmt.Registry) error { if swag.IsZero(m.Peer) { // not required return nil diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_reference.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_reference.go index 85784eb42060..9b2482b61ccd 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_reference.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_reference.go @@ -23,6 +23,14 @@ type NetworkReference struct { // access config AccessConfig AccessConfig `json:"accessConfig,omitempty"` + // Indicates if the network is advertised externally of the workspace to PER and\or peer networks + // Enum: ["enable","disable"] + Advertise string `json:"advertise,omitempty"` + + // Indicates if the ARP broadcast is enabled + // Enum: ["enable","disable"] + ArpBroadcast string `json:"arpBroadcast,omitempty"` + // crn Crn CRN `json:"crn,omitempty"` @@ -70,6 +78,14 @@ func (m *NetworkReference) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateAdvertise(formats); err != nil { + res = append(res, err) + } + + if err := m.validateArpBroadcast(formats); err != nil { + res = append(res, err) + } + if err := m.validateCrn(formats); err != nil { res = append(res, err) } @@ -121,6 +137,90 @@ func (m *NetworkReference) validateAccessConfig(formats strfmt.Registry) error { return nil } +var networkReferenceTypeAdvertisePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + networkReferenceTypeAdvertisePropEnum = append(networkReferenceTypeAdvertisePropEnum, v) + } +} + +const ( + + // NetworkReferenceAdvertiseEnable captures enum value "enable" + NetworkReferenceAdvertiseEnable string = "enable" + + // NetworkReferenceAdvertiseDisable captures enum value "disable" + NetworkReferenceAdvertiseDisable string = "disable" +) + +// prop value enum +func (m *NetworkReference) validateAdvertiseEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, networkReferenceTypeAdvertisePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *NetworkReference) validateAdvertise(formats strfmt.Registry) error { + if swag.IsZero(m.Advertise) { // not required + return nil + } + + // value enum + if err := m.validateAdvertiseEnum("advertise", "body", m.Advertise); err != nil { + return err + } + + return nil +} + +var networkReferenceTypeArpBroadcastPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + networkReferenceTypeArpBroadcastPropEnum = append(networkReferenceTypeArpBroadcastPropEnum, v) + } +} + +const ( + + // NetworkReferenceArpBroadcastEnable captures enum value "enable" + NetworkReferenceArpBroadcastEnable string = "enable" + + // NetworkReferenceArpBroadcastDisable captures enum value "disable" + NetworkReferenceArpBroadcastDisable string = "disable" +) + +// prop value enum +func (m *NetworkReference) validateArpBroadcastEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, networkReferenceTypeArpBroadcastPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *NetworkReference) validateArpBroadcast(formats strfmt.Registry) error { + if swag.IsZero(m.ArpBroadcast) { // not required + return nil + } + + // value enum + if err := m.validateArpBroadcastEnum("arpBroadcast", "body", m.ArpBroadcast); err != nil { + return err + } + + return nil +} + func (m *NetworkReference) validateCrn(formats strfmt.Registry) error { if swag.IsZero(m.Crn) { // not required return nil diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_update.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_update.go index b8924c7f25e2..adfb8bea9706 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_update.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/network_update.go @@ -7,11 +7,13 @@ package models import ( "context" + "encoding/json" "strconv" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" + "github.com/go-openapi/validate" ) // NetworkUpdate network update @@ -19,6 +21,14 @@ import ( // swagger:model NetworkUpdate type NetworkUpdate struct { + // Indicates if the network is advertised externally of the workspace to PER and\or peer networks + // Enum: ["enable","disable"] + Advertise string `json:"advertise,omitempty"` + + // Indicates if the ARP broadcast is enabled + // Enum: ["enable","disable"] + ArpBroadcast string `json:"arpBroadcast,omitempty"` + // Replaces the current DNS Servers DNSServers []string `json:"dnsServers"` @@ -36,6 +46,14 @@ type NetworkUpdate struct { func (m *NetworkUpdate) Validate(formats strfmt.Registry) error { var res []error + if err := m.validateAdvertise(formats); err != nil { + res = append(res, err) + } + + if err := m.validateArpBroadcast(formats); err != nil { + res = append(res, err) + } + if err := m.validateIPAddressRanges(formats); err != nil { res = append(res, err) } @@ -46,6 +64,90 @@ func (m *NetworkUpdate) Validate(formats strfmt.Registry) error { return nil } +var networkUpdateTypeAdvertisePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + networkUpdateTypeAdvertisePropEnum = append(networkUpdateTypeAdvertisePropEnum, v) + } +} + +const ( + + // NetworkUpdateAdvertiseEnable captures enum value "enable" + NetworkUpdateAdvertiseEnable string = "enable" + + // NetworkUpdateAdvertiseDisable captures enum value "disable" + NetworkUpdateAdvertiseDisable string = "disable" +) + +// prop value enum +func (m *NetworkUpdate) validateAdvertiseEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, networkUpdateTypeAdvertisePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *NetworkUpdate) validateAdvertise(formats strfmt.Registry) error { + if swag.IsZero(m.Advertise) { // not required + return nil + } + + // value enum + if err := m.validateAdvertiseEnum("advertise", "body", m.Advertise); err != nil { + return err + } + + return nil +} + +var networkUpdateTypeArpBroadcastPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + networkUpdateTypeArpBroadcastPropEnum = append(networkUpdateTypeArpBroadcastPropEnum, v) + } +} + +const ( + + // NetworkUpdateArpBroadcastEnable captures enum value "enable" + NetworkUpdateArpBroadcastEnable string = "enable" + + // NetworkUpdateArpBroadcastDisable captures enum value "disable" + NetworkUpdateArpBroadcastDisable string = "disable" +) + +// prop value enum +func (m *NetworkUpdate) validateArpBroadcastEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, networkUpdateTypeArpBroadcastPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *NetworkUpdate) validateArpBroadcast(formats strfmt.Registry) error { + if swag.IsZero(m.ArpBroadcast) { // not required + return nil + } + + // value enum + if err := m.validateArpBroadcastEnum("arpBroadcast", "body", m.ArpBroadcast); err != nil { + return err + } + + return nil +} + func (m *NetworkUpdate) validateIPAddressRanges(formats strfmt.Registry) error { if swag.IsZero(m.IPAddressRanges) { // not required return nil diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/p_vm_instance_create.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/p_vm_instance_create.go index 49ca93955aaa..a2b037d19546 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/p_vm_instance_create.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/p_vm_instance_create.go @@ -116,7 +116,7 @@ type PVMInstanceCreate struct { // System type used to host the instance SysType string `json:"sysType,omitempty"` - // Cloud init user defined data; For FLS, only cloud-config instance-data is supported and data must not be compressed or exceed 63K + // Cloud init user defined data; For FLS, only cloud-config user-data is supported and data must not be compressed or exceed 63K UserData string `json:"userData,omitempty"` // user tags diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/placement_group.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/placement_group.go index bd3cf515ad2a..cf51a31d40f0 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/placement_group.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/placement_group.go @@ -20,6 +20,9 @@ import ( // swagger:model PlacementGroup type PlacementGroup struct { + // crn + Crn CRN `json:"crn,omitempty"` + // The id of the Placement Group // Required: true ID *string `json:"id"` @@ -36,12 +39,19 @@ type PlacementGroup struct { // Required: true // Enum: ["affinity","anti-affinity"] Policy *string `json:"policy"` + + // user tags + UserTags Tags `json:"userTags,omitempty"` } // Validate validates this placement group func (m *PlacementGroup) Validate(formats strfmt.Registry) error { var res []error + if err := m.validateCrn(formats); err != nil { + res = append(res, err) + } + if err := m.validateID(formats); err != nil { res = append(res, err) } @@ -58,12 +68,33 @@ func (m *PlacementGroup) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateUserTags(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } +func (m *PlacementGroup) validateCrn(formats strfmt.Registry) error { + if swag.IsZero(m.Crn) { // not required + return nil + } + + if err := m.Crn.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("crn") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("crn") + } + return err + } + + return nil +} + func (m *PlacementGroup) validateID(formats strfmt.Registry) error { if err := validate.Required("id", "body", m.ID); err != nil { @@ -134,8 +165,70 @@ func (m *PlacementGroup) validatePolicy(formats strfmt.Registry) error { return nil } -// ContextValidate validates this placement group based on context it is used +func (m *PlacementGroup) validateUserTags(formats strfmt.Registry) error { + if swag.IsZero(m.UserTags) { // not required + return nil + } + + if err := m.UserTags.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + + return nil +} + +// ContextValidate validate this placement group based on the context it is used func (m *PlacementGroup) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCrn(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateUserTags(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *PlacementGroup) contextValidateCrn(ctx context.Context, formats strfmt.Registry) error { + + if swag.IsZero(m.Crn) { // not required + return nil + } + + if err := m.Crn.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("crn") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("crn") + } + return err + } + + return nil +} + +func (m *PlacementGroup) contextValidateUserTags(ctx context.Context, formats strfmt.Registry) error { + + if err := m.UserTags.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/placement_group_create.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/placement_group_create.go index 9c3a804e70b6..d12ec8c0443d 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/placement_group_create.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/placement_group_create.go @@ -28,6 +28,9 @@ type PlacementGroupCreate struct { // Required: true // Enum: ["affinity","anti-affinity"] Policy *string `json:"policy"` + + // user tags + UserTags Tags `json:"userTags,omitempty"` } // Validate validates this placement group create @@ -42,6 +45,10 @@ func (m *PlacementGroupCreate) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateUserTags(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -100,8 +107,48 @@ func (m *PlacementGroupCreate) validatePolicy(formats strfmt.Registry) error { return nil } -// ContextValidate validates this placement group create based on context it is used +func (m *PlacementGroupCreate) validateUserTags(formats strfmt.Registry) error { + if swag.IsZero(m.UserTags) { // not required + return nil + } + + if err := m.UserTags.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + + return nil +} + +// ContextValidate validate this placement group create based on the context it is used func (m *PlacementGroupCreate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUserTags(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *PlacementGroupCreate) contextValidateUserTags(ctx context.Context, formats strfmt.Registry) error { + + if err := m.UserTags.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/route.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route.go new file mode 100644 index 000000000000..2d2b107d45d1 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route.go @@ -0,0 +1,454 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Route route +// +// swagger:model Route +type Route struct { + + // The route action + // Required: true + // Enum: ["deliver"] + Action *string `json:"action"` + + // Indicates if the route is advertised externally of the workspace to PER and\or peer networks + // Required: true + // Enum: ["enable","disable"] + Advertise *string `json:"advertise"` + + // The route's crn + // Required: true + Crn *string `json:"crn"` + + // The route destination + // Required: true + Destination *string `json:"destination"` + + // The destination type + // Required: true + // Enum: ["ipv4-address"] + DestinationType *string `json:"destinationType"` + + // Indicates if the route should be enabled in the fabric + Enabled bool `json:"enabled,omitempty"` + + // The unique route ID + // Required: true + ID *string `json:"id"` + + // Name of the route + // Required: true + // Max Length: 128 + // Pattern: ^[\s]*[A-Za-z0-9:_.\-][A-Za-z0-9\s:_.\-]*$ + Name *string `json:"name"` + + // The next hop + // Required: true + NextHop *string `json:"nextHop"` + + // The next hop type + // Required: true + // Enum: ["ipv4-address"] + NextHopType *string `json:"nextHopType"` + + // The state of the route + // Required: true + // Enum: ["defined","deployed","disabled"] + State *string `json:"state"` + + // user tags + UserTags Tags `json:"userTags,omitempty"` +} + +// Validate validates this route +func (m *Route) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAction(formats); err != nil { + res = append(res, err) + } + + if err := m.validateAdvertise(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCrn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDestination(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDestinationType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNextHop(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNextHopType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateState(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserTags(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var routeTypeActionPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["deliver"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeTypeActionPropEnum = append(routeTypeActionPropEnum, v) + } +} + +const ( + + // RouteActionDeliver captures enum value "deliver" + RouteActionDeliver string = "deliver" +) + +// prop value enum +func (m *Route) validateActionEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeTypeActionPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Route) validateAction(formats strfmt.Registry) error { + + if err := validate.Required("action", "body", m.Action); err != nil { + return err + } + + // value enum + if err := m.validateActionEnum("action", "body", *m.Action); err != nil { + return err + } + + return nil +} + +var routeTypeAdvertisePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeTypeAdvertisePropEnum = append(routeTypeAdvertisePropEnum, v) + } +} + +const ( + + // RouteAdvertiseEnable captures enum value "enable" + RouteAdvertiseEnable string = "enable" + + // RouteAdvertiseDisable captures enum value "disable" + RouteAdvertiseDisable string = "disable" +) + +// prop value enum +func (m *Route) validateAdvertiseEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeTypeAdvertisePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Route) validateAdvertise(formats strfmt.Registry) error { + + if err := validate.Required("advertise", "body", m.Advertise); err != nil { + return err + } + + // value enum + if err := m.validateAdvertiseEnum("advertise", "body", *m.Advertise); err != nil { + return err + } + + return nil +} + +func (m *Route) validateCrn(formats strfmt.Registry) error { + + if err := validate.Required("crn", "body", m.Crn); err != nil { + return err + } + + return nil +} + +func (m *Route) validateDestination(formats strfmt.Registry) error { + + if err := validate.Required("destination", "body", m.Destination); err != nil { + return err + } + + return nil +} + +var routeTypeDestinationTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ipv4-address"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeTypeDestinationTypePropEnum = append(routeTypeDestinationTypePropEnum, v) + } +} + +const ( + + // RouteDestinationTypeIPV4DashAddress captures enum value "ipv4-address" + RouteDestinationTypeIPV4DashAddress string = "ipv4-address" +) + +// prop value enum +func (m *Route) validateDestinationTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeTypeDestinationTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Route) validateDestinationType(formats strfmt.Registry) error { + + if err := validate.Required("destinationType", "body", m.DestinationType); err != nil { + return err + } + + // value enum + if err := m.validateDestinationTypeEnum("destinationType", "body", *m.DestinationType); err != nil { + return err + } + + return nil +} + +func (m *Route) validateID(formats strfmt.Registry) error { + + if err := validate.Required("id", "body", m.ID); err != nil { + return err + } + + return nil +} + +func (m *Route) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 128); err != nil { + return err + } + + if err := validate.Pattern("name", "body", *m.Name, `^[\s]*[A-Za-z0-9:_.\-][A-Za-z0-9\s:_.\-]*$`); err != nil { + return err + } + + return nil +} + +func (m *Route) validateNextHop(formats strfmt.Registry) error { + + if err := validate.Required("nextHop", "body", m.NextHop); err != nil { + return err + } + + return nil +} + +var routeTypeNextHopTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ipv4-address"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeTypeNextHopTypePropEnum = append(routeTypeNextHopTypePropEnum, v) + } +} + +const ( + + // RouteNextHopTypeIPV4DashAddress captures enum value "ipv4-address" + RouteNextHopTypeIPV4DashAddress string = "ipv4-address" +) + +// prop value enum +func (m *Route) validateNextHopTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeTypeNextHopTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Route) validateNextHopType(formats strfmt.Registry) error { + + if err := validate.Required("nextHopType", "body", m.NextHopType); err != nil { + return err + } + + // value enum + if err := m.validateNextHopTypeEnum("nextHopType", "body", *m.NextHopType); err != nil { + return err + } + + return nil +} + +var routeTypeStatePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["defined","deployed","disabled"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeTypeStatePropEnum = append(routeTypeStatePropEnum, v) + } +} + +const ( + + // RouteStateDefined captures enum value "defined" + RouteStateDefined string = "defined" + + // RouteStateDeployed captures enum value "deployed" + RouteStateDeployed string = "deployed" + + // RouteStateDisabled captures enum value "disabled" + RouteStateDisabled string = "disabled" +) + +// prop value enum +func (m *Route) validateStateEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeTypeStatePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Route) validateState(formats strfmt.Registry) error { + + if err := validate.Required("state", "body", m.State); err != nil { + return err + } + + // value enum + if err := m.validateStateEnum("state", "body", *m.State); err != nil { + return err + } + + return nil +} + +func (m *Route) validateUserTags(formats strfmt.Registry) error { + if swag.IsZero(m.UserTags) { // not required + return nil + } + + if err := m.UserTags.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + + return nil +} + +// ContextValidate validate this route based on the context it is used +func (m *Route) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUserTags(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Route) contextValidateUserTags(ctx context.Context, formats strfmt.Registry) error { + + if err := m.UserTags.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Route) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Route) UnmarshalBinary(b []byte) error { + var res Route + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_create.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_create.go new file mode 100644 index 000000000000..6513fe338311 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_create.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// RouteCreate route create +// +// swagger:model RouteCreate +type RouteCreate struct { + + // Action + // Enum: ["deliver"] + Action *string `json:"action,omitempty"` + + // Indicates if the route is advertised externally of the workspace to PER and\or peer networks + // Enum: ["enable","disable"] + Advertise *string `json:"advertise,omitempty"` + + // The route destination + // Required: true + Destination *string `json:"destination"` + + // The destination type + // Enum: ["ipv4-address"] + DestinationType *string `json:"destinationType,omitempty"` + + // Indicates if the route should be enabled in the fabric + Enabled *bool `json:"enabled,omitempty"` + + // Name of the route + // Required: true + // Max Length: 128 + // Pattern: ^[\s]*[A-Za-z0-9:_.\-][A-Za-z0-9\s:_.\-]*$ + Name *string `json:"name"` + + // The next hop + // Required: true + NextHop *string `json:"nextHop"` + + // The next hop type + // Enum: ["ipv4-address"] + NextHopType *string `json:"nextHopType,omitempty"` + + // user tags + UserTags Tags `json:"userTags,omitempty"` +} + +// Validate validates this route create +func (m *RouteCreate) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAction(formats); err != nil { + res = append(res, err) + } + + if err := m.validateAdvertise(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDestination(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDestinationType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNextHop(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNextHopType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserTags(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var routeCreateTypeActionPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["deliver"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeCreateTypeActionPropEnum = append(routeCreateTypeActionPropEnum, v) + } +} + +const ( + + // RouteCreateActionDeliver captures enum value "deliver" + RouteCreateActionDeliver string = "deliver" +) + +// prop value enum +func (m *RouteCreate) validateActionEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeCreateTypeActionPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteCreate) validateAction(formats strfmt.Registry) error { + if swag.IsZero(m.Action) { // not required + return nil + } + + // value enum + if err := m.validateActionEnum("action", "body", *m.Action); err != nil { + return err + } + + return nil +} + +var routeCreateTypeAdvertisePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeCreateTypeAdvertisePropEnum = append(routeCreateTypeAdvertisePropEnum, v) + } +} + +const ( + + // RouteCreateAdvertiseEnable captures enum value "enable" + RouteCreateAdvertiseEnable string = "enable" + + // RouteCreateAdvertiseDisable captures enum value "disable" + RouteCreateAdvertiseDisable string = "disable" +) + +// prop value enum +func (m *RouteCreate) validateAdvertiseEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeCreateTypeAdvertisePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteCreate) validateAdvertise(formats strfmt.Registry) error { + if swag.IsZero(m.Advertise) { // not required + return nil + } + + // value enum + if err := m.validateAdvertiseEnum("advertise", "body", *m.Advertise); err != nil { + return err + } + + return nil +} + +func (m *RouteCreate) validateDestination(formats strfmt.Registry) error { + + if err := validate.Required("destination", "body", m.Destination); err != nil { + return err + } + + return nil +} + +var routeCreateTypeDestinationTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ipv4-address"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeCreateTypeDestinationTypePropEnum = append(routeCreateTypeDestinationTypePropEnum, v) + } +} + +const ( + + // RouteCreateDestinationTypeIPV4DashAddress captures enum value "ipv4-address" + RouteCreateDestinationTypeIPV4DashAddress string = "ipv4-address" +) + +// prop value enum +func (m *RouteCreate) validateDestinationTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeCreateTypeDestinationTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteCreate) validateDestinationType(formats strfmt.Registry) error { + if swag.IsZero(m.DestinationType) { // not required + return nil + } + + // value enum + if err := m.validateDestinationTypeEnum("destinationType", "body", *m.DestinationType); err != nil { + return err + } + + return nil +} + +func (m *RouteCreate) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 128); err != nil { + return err + } + + if err := validate.Pattern("name", "body", *m.Name, `^[\s]*[A-Za-z0-9:_.\-][A-Za-z0-9\s:_.\-]*$`); err != nil { + return err + } + + return nil +} + +func (m *RouteCreate) validateNextHop(formats strfmt.Registry) error { + + if err := validate.Required("nextHop", "body", m.NextHop); err != nil { + return err + } + + return nil +} + +var routeCreateTypeNextHopTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ipv4-address"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeCreateTypeNextHopTypePropEnum = append(routeCreateTypeNextHopTypePropEnum, v) + } +} + +const ( + + // RouteCreateNextHopTypeIPV4DashAddress captures enum value "ipv4-address" + RouteCreateNextHopTypeIPV4DashAddress string = "ipv4-address" +) + +// prop value enum +func (m *RouteCreate) validateNextHopTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeCreateTypeNextHopTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteCreate) validateNextHopType(formats strfmt.Registry) error { + if swag.IsZero(m.NextHopType) { // not required + return nil + } + + // value enum + if err := m.validateNextHopTypeEnum("nextHopType", "body", *m.NextHopType); err != nil { + return err + } + + return nil +} + +func (m *RouteCreate) validateUserTags(formats strfmt.Registry) error { + if swag.IsZero(m.UserTags) { // not required + return nil + } + + if err := m.UserTags.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + + return nil +} + +// ContextValidate validate this route create based on the context it is used +func (m *RouteCreate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUserTags(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RouteCreate) contextValidateUserTags(ctx context.Context, formats strfmt.Registry) error { + + if err := m.UserTags.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RouteCreate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RouteCreate) UnmarshalBinary(b []byte) error { + var res RouteCreate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_report.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_report.go new file mode 100644 index 000000000000..7d21b2c3beac --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_report.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// RouteReport route report +// +// swagger:model RouteReport +type RouteReport struct { + + // A report of routes in a workspace + // Required: true + Routes []*RouteReportRoute `json:"routes"` +} + +// Validate validates this route report +func (m *RouteReport) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRoutes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RouteReport) validateRoutes(formats strfmt.Registry) error { + + if err := validate.Required("routes", "body", m.Routes); err != nil { + return err + } + + for i := 0; i < len(m.Routes); i++ { + if swag.IsZero(m.Routes[i]) { // not required + continue + } + + if m.Routes[i] != nil { + if err := m.Routes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("routes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("routes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this route report based on the context it is used +func (m *RouteReport) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRoutes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RouteReport) contextValidateRoutes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Routes); i++ { + + if m.Routes[i] != nil { + + if swag.IsZero(m.Routes[i]) { // not required + return nil + } + + if err := m.Routes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("routes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("routes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RouteReport) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RouteReport) UnmarshalBinary(b []byte) error { + var res RouteReport + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_report_route.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_report_route.go new file mode 100644 index 000000000000..0f1f87092332 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_report_route.go @@ -0,0 +1,121 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// RouteReportRoute route report route +// +// swagger:model RouteReportRoute +type RouteReportRoute struct { + + // The destination. The destination is a CIDR for the external route type. + // Required: true + Destination *string `json:"destination"` + + // The route type + // Required: true + // Enum: ["external"] + Type *string `json:"type"` +} + +// Validate validates this route report route +func (m *RouteReportRoute) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDestination(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RouteReportRoute) validateDestination(formats strfmt.Registry) error { + + if err := validate.Required("destination", "body", m.Destination); err != nil { + return err + } + + return nil +} + +var routeReportRouteTypeTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["external"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeReportRouteTypeTypePropEnum = append(routeReportRouteTypeTypePropEnum, v) + } +} + +const ( + + // RouteReportRouteTypeExternal captures enum value "external" + RouteReportRouteTypeExternal string = "external" +) + +// prop value enum +func (m *RouteReportRoute) validateTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeReportRouteTypeTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteReportRoute) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + // value enum + if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this route report route based on context it is used +func (m *RouteReportRoute) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RouteReportRoute) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RouteReportRoute) UnmarshalBinary(b []byte) error { + var res RouteReportRoute + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_update.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_update.go new file mode 100644 index 000000000000..6faf62cd6448 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/route_update.go @@ -0,0 +1,280 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// RouteUpdate route update +// +// swagger:model RouteUpdate +type RouteUpdate struct { + + // Action + // Enum: ["deliver"] + Action string `json:"action,omitempty"` + + // Indicates if the route is advertised externally of the workspace to PER and\or peer networks + // Enum: ["enable","disable"] + Advertise string `json:"advertise,omitempty"` + + // The route destination + Destination string `json:"destination,omitempty"` + + // The destination type + // Enum: ["ipv4-address"] + DestinationType string `json:"destinationType,omitempty"` + + // Indicates if the route should be enabled in the fabric + Enabled *bool `json:"enabled,omitempty"` + + // Name of the route + // Max Length: 128 + // Pattern: ^[\s]*[A-Za-z0-9:_.\-][A-Za-z0-9\s:_.\-]*$ + Name string `json:"name,omitempty"` + + // The next hop + NextHop string `json:"nextHop,omitempty"` + + // The next hop type + // Enum: ["ipv4-address"] + NextHopType string `json:"nextHopType,omitempty"` +} + +// Validate validates this route update +func (m *RouteUpdate) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAction(formats); err != nil { + res = append(res, err) + } + + if err := m.validateAdvertise(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDestinationType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNextHopType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var routeUpdateTypeActionPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["deliver"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeUpdateTypeActionPropEnum = append(routeUpdateTypeActionPropEnum, v) + } +} + +const ( + + // RouteUpdateActionDeliver captures enum value "deliver" + RouteUpdateActionDeliver string = "deliver" +) + +// prop value enum +func (m *RouteUpdate) validateActionEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeUpdateTypeActionPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteUpdate) validateAction(formats strfmt.Registry) error { + if swag.IsZero(m.Action) { // not required + return nil + } + + // value enum + if err := m.validateActionEnum("action", "body", m.Action); err != nil { + return err + } + + return nil +} + +var routeUpdateTypeAdvertisePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["enable","disable"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeUpdateTypeAdvertisePropEnum = append(routeUpdateTypeAdvertisePropEnum, v) + } +} + +const ( + + // RouteUpdateAdvertiseEnable captures enum value "enable" + RouteUpdateAdvertiseEnable string = "enable" + + // RouteUpdateAdvertiseDisable captures enum value "disable" + RouteUpdateAdvertiseDisable string = "disable" +) + +// prop value enum +func (m *RouteUpdate) validateAdvertiseEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeUpdateTypeAdvertisePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteUpdate) validateAdvertise(formats strfmt.Registry) error { + if swag.IsZero(m.Advertise) { // not required + return nil + } + + // value enum + if err := m.validateAdvertiseEnum("advertise", "body", m.Advertise); err != nil { + return err + } + + return nil +} + +var routeUpdateTypeDestinationTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ipv4-address"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeUpdateTypeDestinationTypePropEnum = append(routeUpdateTypeDestinationTypePropEnum, v) + } +} + +const ( + + // RouteUpdateDestinationTypeIPV4DashAddress captures enum value "ipv4-address" + RouteUpdateDestinationTypeIPV4DashAddress string = "ipv4-address" +) + +// prop value enum +func (m *RouteUpdate) validateDestinationTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeUpdateTypeDestinationTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteUpdate) validateDestinationType(formats strfmt.Registry) error { + if swag.IsZero(m.DestinationType) { // not required + return nil + } + + // value enum + if err := m.validateDestinationTypeEnum("destinationType", "body", m.DestinationType); err != nil { + return err + } + + return nil +} + +func (m *RouteUpdate) validateName(formats strfmt.Registry) error { + if swag.IsZero(m.Name) { // not required + return nil + } + + if err := validate.MaxLength("name", "body", m.Name, 128); err != nil { + return err + } + + if err := validate.Pattern("name", "body", m.Name, `^[\s]*[A-Za-z0-9:_.\-][A-Za-z0-9\s:_.\-]*$`); err != nil { + return err + } + + return nil +} + +var routeUpdateTypeNextHopTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ipv4-address"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + routeUpdateTypeNextHopTypePropEnum = append(routeUpdateTypeNextHopTypePropEnum, v) + } +} + +const ( + + // RouteUpdateNextHopTypeIPV4DashAddress captures enum value "ipv4-address" + RouteUpdateNextHopTypeIPV4DashAddress string = "ipv4-address" +) + +// prop value enum +func (m *RouteUpdate) validateNextHopTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, routeUpdateTypeNextHopTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *RouteUpdate) validateNextHopType(formats strfmt.Registry) error { + if swag.IsZero(m.NextHopType) { // not required + return nil + } + + // value enum + if err := m.validateNextHopTypeEnum("nextHopType", "body", m.NextHopType); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this route update based on context it is used +func (m *RouteUpdate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RouteUpdate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RouteUpdate) UnmarshalBinary(b []byte) error { + var res RouteUpdate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/routes.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/routes.go new file mode 100644 index 000000000000..1f5cd2777357 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/routes.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Routes routes +// +// swagger:model Routes +type Routes struct { + + // Routes + // Required: true + Routes []*Route `json:"routes"` +} + +// Validate validates this routes +func (m *Routes) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRoutes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Routes) validateRoutes(formats strfmt.Registry) error { + + if err := validate.Required("routes", "body", m.Routes); err != nil { + return err + } + + for i := 0; i < len(m.Routes); i++ { + if swag.IsZero(m.Routes[i]) { // not required + continue + } + + if m.Routes[i] != nil { + if err := m.Routes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("routes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("routes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this routes based on the context it is used +func (m *Routes) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRoutes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Routes) contextValidateRoutes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Routes); i++ { + + if m.Routes[i] != nil { + + if swag.IsZero(m.Routes[i]) { // not required + return nil + } + + if err := m.Routes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("routes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("routes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Routes) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Routes) UnmarshalBinary(b []byte) error { + var res Routes + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_a_p_create.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_a_p_create.go index 0f221db4ace8..1659a9292ef1 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_a_p_create.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_a_p_create.go @@ -52,6 +52,7 @@ type SAPCreate struct { // SAP Profile ID for the amount of cores and memory // Required: true + // Pattern: ^[\s]*[A-Za-z][A-Za-z0-9\-]{3,}$ ProfileID *string `json:"profileID"` // Indicates the replication site of the boot volume @@ -75,7 +76,7 @@ type SAPCreate struct { // System type used to host the instance. Only e880, e980, e1080 are supported SysType string `json:"sysType,omitempty"` - // Cloud init user defined data; For FLS, only cloud-config instance-data is supported and data must not be compressed or exceed 63K + // Cloud init user defined data; For FLS, only cloud-config user-data is supported and data must not be compressed or exceed 63K UserData string `json:"userData,omitempty"` // user tags @@ -237,6 +238,10 @@ func (m *SAPCreate) validateProfileID(formats strfmt.Registry) error { return err } + if err := validate.Pattern("profileID", "body", *m.ProfileID, `^[\s]*[A-Za-z][A-Za-z0-9\-]{3,}$`); err != nil { + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_a_p_profile.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_a_p_profile.go index 227c7a965427..0ae04109bd24 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_a_p_profile.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_a_p_profile.go @@ -54,7 +54,7 @@ type SAPProfile struct { // Type of profile // Required: true - // Enum: ["balanced","compute","memory","non-production","ultra-memory","small","SAP Rise Optimized"] + // Enum: ["balanced","compute","memory","ultra-memory","small","sap-rise","sap-rise-app"] Type *string `json:"type"` // List of supported workload types @@ -168,7 +168,7 @@ var sAPProfileTypeTypePropEnum []interface{} func init() { var res []string - if err := json.Unmarshal([]byte(`["balanced","compute","memory","non-production","ultra-memory","small","SAP Rise Optimized"]`), &res); err != nil { + if err := json.Unmarshal([]byte(`["balanced","compute","memory","ultra-memory","small","sap-rise","sap-rise-app"]`), &res); err != nil { panic(err) } for _, v := range res { @@ -187,17 +187,17 @@ const ( // SAPProfileTypeMemory captures enum value "memory" SAPProfileTypeMemory string = "memory" - // SAPProfileTypeNonDashProduction captures enum value "non-production" - SAPProfileTypeNonDashProduction string = "non-production" - // SAPProfileTypeUltraDashMemory captures enum value "ultra-memory" SAPProfileTypeUltraDashMemory string = "ultra-memory" // SAPProfileTypeSmall captures enum value "small" SAPProfileTypeSmall string = "small" - // SAPProfileTypeSAPRiseOptimized captures enum value "SAP Rise Optimized" - SAPProfileTypeSAPRiseOptimized string = "SAP Rise Optimized" + // SAPProfileTypeSapDashRise captures enum value "sap-rise" + SAPProfileTypeSapDashRise string = "sap-rise" + + // SAPProfileTypeSapDashRiseDashApp captures enum value "sap-rise-app" + SAPProfileTypeSapDashRiseDashApp string = "sap-rise-app" ) // prop value enum diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_p_p_placement_group.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_p_p_placement_group.go index a230c32a6fd0..d85567fc33b0 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_p_p_placement_group.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_p_p_placement_group.go @@ -19,6 +19,9 @@ import ( // swagger:model SPPPlacementGroup type SPPPlacementGroup struct { + // crn + Crn CRN `json:"crn,omitempty"` + // The id of the Shared Processor Pool Placement Group // Required: true ID *string `json:"id"` @@ -33,12 +36,19 @@ type SPPPlacementGroup struct { // The Shared Processor Pool Placement Group policy // Required: true Policy *string `json:"policy"` + + // user tags + UserTags Tags `json:"userTags,omitempty"` } // Validate validates this s p p placement group func (m *SPPPlacementGroup) Validate(formats strfmt.Registry) error { var res []error + if err := m.validateCrn(formats); err != nil { + res = append(res, err) + } + if err := m.validateID(formats); err != nil { res = append(res, err) } @@ -51,12 +61,33 @@ func (m *SPPPlacementGroup) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateUserTags(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } +func (m *SPPPlacementGroup) validateCrn(formats strfmt.Registry) error { + if swag.IsZero(m.Crn) { // not required + return nil + } + + if err := m.Crn.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("crn") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("crn") + } + return err + } + + return nil +} + func (m *SPPPlacementGroup) validateID(formats strfmt.Registry) error { if err := validate.Required("id", "body", m.ID); err != nil { @@ -84,8 +115,70 @@ func (m *SPPPlacementGroup) validatePolicy(formats strfmt.Registry) error { return nil } -// ContextValidate validates this s p p placement group based on context it is used +func (m *SPPPlacementGroup) validateUserTags(formats strfmt.Registry) error { + if swag.IsZero(m.UserTags) { // not required + return nil + } + + if err := m.UserTags.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + + return nil +} + +// ContextValidate validate this s p p placement group based on the context it is used func (m *SPPPlacementGroup) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCrn(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateUserTags(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SPPPlacementGroup) contextValidateCrn(ctx context.Context, formats strfmt.Registry) error { + + if swag.IsZero(m.Crn) { // not required + return nil + } + + if err := m.Crn.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("crn") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("crn") + } + return err + } + + return nil +} + +func (m *SPPPlacementGroup) contextValidateUserTags(ctx context.Context, formats strfmt.Registry) error { + + if err := m.UserTags.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_p_p_placement_group_create.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_p_p_placement_group_create.go index acf4c06d724e..a69cbbb19dd7 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_p_p_placement_group_create.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/s_p_p_placement_group_create.go @@ -22,12 +22,18 @@ type SPPPlacementGroupCreate struct { // The name of the Shared Processor Pool Placement Group; minimum of 2 characters, maximum of 12, the only special character allowed is the underscore '_'. // Required: true + // Max Length: 12 + // Min Length: 2 + // Pattern: ^[a-zA-Z0-9_]+$ Name *string `json:"name"` // The placement group policy // Required: true // Enum: ["affinity","anti-affinity"] Policy *string `json:"policy"` + + // user tags + UserTags Tags `json:"userTags,omitempty"` } // Validate validates this s p p placement group create @@ -42,6 +48,10 @@ func (m *SPPPlacementGroupCreate) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateUserTags(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -54,6 +64,18 @@ func (m *SPPPlacementGroupCreate) validateName(formats strfmt.Registry) error { return err } + if err := validate.MinLength("name", "body", *m.Name, 2); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 12); err != nil { + return err + } + + if err := validate.Pattern("name", "body", *m.Name, `^[a-zA-Z0-9_]+$`); err != nil { + return err + } + return nil } @@ -100,8 +122,48 @@ func (m *SPPPlacementGroupCreate) validatePolicy(formats strfmt.Registry) error return nil } -// ContextValidate validates this s p p placement group create based on context it is used +func (m *SPPPlacementGroupCreate) validateUserTags(formats strfmt.Registry) error { + if swag.IsZero(m.UserTags) { // not required + return nil + } + + if err := m.UserTags.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + + return nil +} + +// ContextValidate validate this s p p placement group create based on the context it is used func (m *SPPPlacementGroupCreate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUserTags(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SPPPlacementGroupCreate) contextValidateUserTags(ctx context.Context, formats strfmt.Registry) error { + + if err := m.UserTags.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userTags") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userTags") + } + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot.go index 3d7319f7c374..59a91324b7d3 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot.go @@ -51,9 +51,12 @@ type Snapshot struct { // Required: true SnapshotID *string `json:"snapshotID"` - // Status of the PVM instancesnapshot + // Status of the PVM instance snapshot Status string `json:"status,omitempty"` + // Detailed information for the last PVM instance snapshot action + StatusDetail string `json:"statusDetail,omitempty"` + // A map of volume snapshots included in the PVM instance snapshot // Required: true VolumeSnapshots map[string]string `json:"volumeSnapshots"` diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot_create.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot_create.go index 8d85520aac5f..dbd12da8c99c 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot_create.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot_create.go @@ -24,6 +24,8 @@ type SnapshotCreate struct { // Name of the PVM instance snapshot to create // Required: true + // Max Length: 120 + // Pattern: ^[a-zA-Z0-9_.-]+$ Name *string `json:"name"` // user tags @@ -57,6 +59,14 @@ func (m *SnapshotCreate) validateName(formats strfmt.Registry) error { return err } + if err := validate.MaxLength("name", "body", *m.Name, 120); err != nil { + return err + } + + if err := validate.Pattern("name", "body", *m.Name, `^[a-zA-Z0-9_.-]+$`); err != nil { + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot_update.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot_update.go index 162102e53d94..e924ad1160fd 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot_update.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/snapshot_update.go @@ -8,8 +8,10 @@ package models import ( "context" + "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" + "github.com/go-openapi/validate" ) // SnapshotUpdate snapshot update @@ -21,11 +23,38 @@ type SnapshotUpdate struct { Description string `json:"description,omitempty"` // Name of the PVM instance snapshot + // Max Length: 120 + // Pattern: ^[a-zA-Z0-9_.-]+$ Name string `json:"name,omitempty"` } // Validate validates this snapshot update func (m *SnapshotUpdate) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SnapshotUpdate) validateName(formats strfmt.Registry) error { + if swag.IsZero(m.Name) { // not required + return nil + } + + if err := validate.MaxLength("name", "body", m.Name, 120); err != nil { + return err + } + + if err := validate.Pattern("name", "body", m.Name, `^[a-zA-Z0-9_.-]+$`); err != nil { + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/software_tier.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/software_tier.go new file mode 100644 index 000000000000..3f471c59c812 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/software_tier.go @@ -0,0 +1,84 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// SoftwareTier Software tier (IBMi licensing) +// +// swagger:model SoftwareTier +type SoftwareTier string + +func NewSoftwareTier(value SoftwareTier) *SoftwareTier { + return &value +} + +// Pointer returns a pointer to a freshly-allocated SoftwareTier. +func (m SoftwareTier) Pointer() *SoftwareTier { + return &m +} + +const ( + + // SoftwareTierP05 captures enum value "P05" + SoftwareTierP05 SoftwareTier = "P05" + + // SoftwareTierP10 captures enum value "P10" + SoftwareTierP10 SoftwareTier = "P10" + + // SoftwareTierP20 captures enum value "P20" + SoftwareTierP20 SoftwareTier = "P20" + + // SoftwareTierP30 captures enum value "P30" + SoftwareTierP30 SoftwareTier = "P30" +) + +// for schema +var softwareTierEnum []interface{} + +func init() { + var res []SoftwareTier + if err := json.Unmarshal([]byte(`["P05","P10","P20","P30"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + softwareTierEnum = append(softwareTierEnum, v) + } +} + +func (m SoftwareTier) validateSoftwareTierEnum(path, location string, value SoftwareTier) error { + if err := validate.EnumCase(path, location, value, softwareTierEnum, true); err != nil { + return err + } + return nil +} + +// Validate validates this software tier +func (m SoftwareTier) Validate(formats strfmt.Registry) error { + var res []error + + // value enum + if err := m.validateSoftwareTierEnum("", "body", m); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// ContextValidate validates this software tier based on context it is used +func (m SoftwareTier) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/supported_software_tier.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/supported_software_tier.go new file mode 100644 index 000000000000..dce5eedf9731 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/supported_software_tier.go @@ -0,0 +1,107 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SupportedSoftwareTier supported software tier +// +// swagger:model SupportedSoftwareTier +type SupportedSoftwareTier struct { + + // supported systems + SupportedSystems []string `json:"supportedSystems"` + + // tier + Tier SoftwareTier `json:"tier,omitempty"` +} + +// Validate validates this supported software tier +func (m *SupportedSoftwareTier) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTier(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SupportedSoftwareTier) validateTier(formats strfmt.Registry) error { + if swag.IsZero(m.Tier) { // not required + return nil + } + + if err := m.Tier.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("tier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("tier") + } + return err + } + + return nil +} + +// ContextValidate validate this supported software tier based on the context it is used +func (m *SupportedSoftwareTier) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateTier(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SupportedSoftwareTier) contextValidateTier(ctx context.Context, formats strfmt.Registry) error { + + if swag.IsZero(m.Tier) { // not required + return nil + } + + if err := m.Tier.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("tier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("tier") + } + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SupportedSoftwareTier) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SupportedSoftwareTier) UnmarshalBinary(b []byte) error { + var res SupportedSoftwareTier + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/supported_software_tier_list.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/supported_software_tier_list.go new file mode 100644 index 000000000000..de22fd67ebf2 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/supported_software_tier_list.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SupportedSoftwareTierList List of supported software tiers (IBMi licensing) +// +// swagger:model SupportedSoftwareTierList +type SupportedSoftwareTierList []*SupportedSoftwareTier + +// Validate validates this supported software tier list +func (m SupportedSoftwareTierList) Validate(formats strfmt.Registry) error { + var res []error + + for i := 0; i < len(m); i++ { + if swag.IsZero(m[i]) { // not required + continue + } + + if m[i] != nil { + if err := m[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName(strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName(strconv.Itoa(i)) + } + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// ContextValidate validate this supported software tier list based on the context it is used +func (m SupportedSoftwareTierList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + for i := 0; i < len(m); i++ { + + if m[i] != nil { + + if swag.IsZero(m[i]) { // not required + return nil + } + + if err := m[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName(strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName(strconv.Itoa(i)) + } + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/system.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/system.go index b08e28f1bc30..716cebffb842 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/system.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/system.go @@ -29,6 +29,9 @@ type System struct { // Required: true Cores *float64 `json:"cores"` + // The host MTMS name + HostMTMSName string `json:"hostMTMSName,omitempty"` + // The host identifier ID int64 `json:"id,omitempty"` diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/system_resources.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/system_resources.go index 597b7bc0fcee..e85496eeef7b 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/system_resources.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/system_resources.go @@ -23,6 +23,9 @@ type SystemResources struct { // Required: true Cores *float64 `json:"cores"` + // The host MTMS name + HostMTMSName string `json:"hostMTMSName,omitempty"` + // The host identifier // Required: true ID *int64 `json:"id"` diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/update_server_virtual_serial_number.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/update_server_virtual_serial_number.go index 921dcdd64b7b..c1dbba537e9c 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/update_server_virtual_serial_number.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/update_server_virtual_serial_number.go @@ -11,7 +11,6 @@ import ( "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" - "github.com/go-openapi/validate" ) // UpdateServerVirtualSerialNumber update server virtual serial number @@ -20,15 +19,17 @@ import ( type UpdateServerVirtualSerialNumber struct { // Description of the Virtual Serial Number - // Required: true - Description *string `json:"description"` + Description *string `json:"description,omitempty"` + + // software tier + SoftwareTier SoftwareTier `json:"softwareTier,omitempty"` } // Validate validates this update server virtual serial number func (m *UpdateServerVirtualSerialNumber) Validate(formats strfmt.Registry) error { var res []error - if err := m.validateDescription(formats); err != nil { + if err := m.validateSoftwareTier(formats); err != nil { res = append(res, err) } @@ -38,17 +39,52 @@ func (m *UpdateServerVirtualSerialNumber) Validate(formats strfmt.Registry) erro return nil } -func (m *UpdateServerVirtualSerialNumber) validateDescription(formats strfmt.Registry) error { +func (m *UpdateServerVirtualSerialNumber) validateSoftwareTier(formats strfmt.Registry) error { + if swag.IsZero(m.SoftwareTier) { // not required + return nil + } - if err := validate.Required("description", "body", m.Description); err != nil { + if err := m.SoftwareTier.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("softwareTier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("softwareTier") + } return err } return nil } -// ContextValidate validates this update server virtual serial number based on context it is used +// ContextValidate validate this update server virtual serial number based on the context it is used func (m *UpdateServerVirtualSerialNumber) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSoftwareTier(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UpdateServerVirtualSerialNumber) contextValidateSoftwareTier(ctx context.Context, formats strfmt.Registry) error { + + if swag.IsZero(m.SoftwareTier) { // not required + return nil + } + + if err := m.SoftwareTier.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("softwareTier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("softwareTier") + } + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/update_workspace_ssh_key.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/update_workspace_ssh_key.go new file mode 100644 index 000000000000..d923a9a09e70 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/update_workspace_ssh_key.go @@ -0,0 +1,136 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// UpdateWorkspaceSSHKey update workspace SSH key +// +// swagger:model UpdateWorkspaceSSHKey +type UpdateWorkspaceSSHKey struct { + + // Description of the sshkey + Description *string `json:"description,omitempty" datastore:"description"` + + // User defined name for the SSH key + // Max Length: 128 + // Pattern: ^[A-Za-z0-9-_]+(?: +[A-Za-z0-9-_]+)*$ + Name *string `json:"name,omitempty" datastore:"name"` + + // SSH RSA key + SSHKey *string `json:"sshKey,omitempty" datastore:"sshKey"` + + // Visibility of the sshkey; workspace suggests ssh-key is only accessible in a workspace, account suggests ssh-key is accessible throughout an account + // Enum: ["account","workspace"] + Visibility *string `json:"visibility,omitempty" datastore:"visibility"` +} + +// Validate validates this update workspace SSH key +func (m *UpdateWorkspaceSSHKey) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVisibility(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UpdateWorkspaceSSHKey) validateName(formats strfmt.Registry) error { + if swag.IsZero(m.Name) { // not required + return nil + } + + if err := validate.MaxLength("name", "body", *m.Name, 128); err != nil { + return err + } + + if err := validate.Pattern("name", "body", *m.Name, `^[A-Za-z0-9-_]+(?: +[A-Za-z0-9-_]+)*$`); err != nil { + return err + } + + return nil +} + +var updateWorkspaceSshKeyTypeVisibilityPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["account","workspace"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + updateWorkspaceSshKeyTypeVisibilityPropEnum = append(updateWorkspaceSshKeyTypeVisibilityPropEnum, v) + } +} + +const ( + + // UpdateWorkspaceSSHKeyVisibilityAccount captures enum value "account" + UpdateWorkspaceSSHKeyVisibilityAccount string = "account" + + // UpdateWorkspaceSSHKeyVisibilityWorkspace captures enum value "workspace" + UpdateWorkspaceSSHKeyVisibilityWorkspace string = "workspace" +) + +// prop value enum +func (m *UpdateWorkspaceSSHKey) validateVisibilityEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, updateWorkspaceSshKeyTypeVisibilityPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *UpdateWorkspaceSSHKey) validateVisibility(formats strfmt.Registry) error { + if swag.IsZero(m.Visibility) { // not required + return nil + } + + // value enum + if err := m.validateVisibilityEnum("visibility", "body", *m.Visibility); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this update workspace SSH key based on context it is used +func (m *UpdateWorkspaceSSHKey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UpdateWorkspaceSSHKey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UpdateWorkspaceSSHKey) UnmarshalBinary(b []byte) error { + var res UpdateWorkspaceSSHKey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/virtual_serial_number.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/virtual_serial_number.go index 96c211c58524..4e712394b04d 100644 --- a/vendor/github.com/IBM-Cloud/power-go-client/power/models/virtual_serial_number.go +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/virtual_serial_number.go @@ -30,6 +30,9 @@ type VirtualSerialNumber struct { // Virtual Serial Number assigned to the PVM Instance // Required: true Serial *string `json:"serial"` + + // software tier + SoftwareTier SoftwareTier `json:"softwareTier,omitempty"` } // Validate validates this virtual serial number @@ -48,6 +51,10 @@ func (m *VirtualSerialNumber) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateSoftwareTier(formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { return errors.CompositeValidationError(res...) } @@ -81,8 +88,52 @@ func (m *VirtualSerialNumber) validateSerial(formats strfmt.Registry) error { return nil } -// ContextValidate validates this virtual serial number based on context it is used +func (m *VirtualSerialNumber) validateSoftwareTier(formats strfmt.Registry) error { + if swag.IsZero(m.SoftwareTier) { // not required + return nil + } + + if err := m.SoftwareTier.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("softwareTier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("softwareTier") + } + return err + } + + return nil +} + +// ContextValidate validate this virtual serial number based on the context it is used func (m *VirtualSerialNumber) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSoftwareTier(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *VirtualSerialNumber) contextValidateSoftwareTier(ctx context.Context, formats strfmt.Registry) error { + + if swag.IsZero(m.SoftwareTier) { // not required + return nil + } + + if err := m.SoftwareTier.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("softwareTier") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("softwareTier") + } + return err + } + return nil } diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/workspace_ssh_key.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/workspace_ssh_key.go new file mode 100644 index 000000000000..ff3d10878192 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/workspace_ssh_key.go @@ -0,0 +1,206 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// WorkspaceSSHKey workspace SSH key +// +// swagger:model WorkspaceSSHKey +type WorkspaceSSHKey struct { + + // Date/Time of sshkey creation + // Format: date-time + CreationDate *strfmt.DateTime `json:"creationDate,omitempty" datastore:"creationDate"` + + // Description of the sshkey + Description string `json:"description" datastore:"description"` + + // Unique id of ssh-key + // Required: true + ID *string `json:"id" datastore:"id"` + + // User defined name for the SSH key + // Required: true + // Max Length: 128 + // Pattern: ^[A-Za-z0-9-_]+(?: +[A-Za-z0-9-_]+)*$ + Name *string `json:"name" datastore:"name"` + + // Indicates if the current workspace owns the ssh key or not + // Required: true + PrimaryWorkspace *bool `json:"primaryWorkspace"` + + // SSH RSA key + // Required: true + SSHKey *string `json:"sshKey" datastore:"sshKey"` + + // Visibility of the sshkey; workspace suggests ssh-key is only accessible in a workspace, account suggests ssh-key is accessible throughout an account + // Enum: ["account","workspace"] + Visibility *string `json:"visibility,omitempty" datastore:"visibility"` +} + +// Validate validates this workspace SSH key +func (m *WorkspaceSSHKey) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreationDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePrimaryWorkspace(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSSHKey(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVisibility(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *WorkspaceSSHKey) validateCreationDate(formats strfmt.Registry) error { + if swag.IsZero(m.CreationDate) { // not required + return nil + } + + if err := validate.FormatOf("creationDate", "body", "date-time", m.CreationDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *WorkspaceSSHKey) validateID(formats strfmt.Registry) error { + + if err := validate.Required("id", "body", m.ID); err != nil { + return err + } + + return nil +} + +func (m *WorkspaceSSHKey) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 128); err != nil { + return err + } + + if err := validate.Pattern("name", "body", *m.Name, `^[A-Za-z0-9-_]+(?: +[A-Za-z0-9-_]+)*$`); err != nil { + return err + } + + return nil +} + +func (m *WorkspaceSSHKey) validatePrimaryWorkspace(formats strfmt.Registry) error { + + if err := validate.Required("primaryWorkspace", "body", m.PrimaryWorkspace); err != nil { + return err + } + + return nil +} + +func (m *WorkspaceSSHKey) validateSSHKey(formats strfmt.Registry) error { + + if err := validate.Required("sshKey", "body", m.SSHKey); err != nil { + return err + } + + return nil +} + +var workspaceSshKeyTypeVisibilityPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["account","workspace"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + workspaceSshKeyTypeVisibilityPropEnum = append(workspaceSshKeyTypeVisibilityPropEnum, v) + } +} + +const ( + + // WorkspaceSSHKeyVisibilityAccount captures enum value "account" + WorkspaceSSHKeyVisibilityAccount string = "account" + + // WorkspaceSSHKeyVisibilityWorkspace captures enum value "workspace" + WorkspaceSSHKeyVisibilityWorkspace string = "workspace" +) + +// prop value enum +func (m *WorkspaceSSHKey) validateVisibilityEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, workspaceSshKeyTypeVisibilityPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *WorkspaceSSHKey) validateVisibility(formats strfmt.Registry) error { + if swag.IsZero(m.Visibility) { // not required + return nil + } + + // value enum + if err := m.validateVisibilityEnum("visibility", "body", *m.Visibility); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this workspace SSH key based on context it is used +func (m *WorkspaceSSHKey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *WorkspaceSSHKey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *WorkspaceSSHKey) UnmarshalBinary(b []byte) error { + var res WorkspaceSSHKey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM-Cloud/power-go-client/power/models/workspace_ssh_keys.go b/vendor/github.com/IBM-Cloud/power-go-client/power/models/workspace_ssh_keys.go new file mode 100644 index 000000000000..44eaea4cba90 --- /dev/null +++ b/vendor/github.com/IBM-Cloud/power-go-client/power/models/workspace_ssh_keys.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// WorkspaceSSHKeys workspace SSH keys +// +// swagger:model WorkspaceSSHKeys +type WorkspaceSSHKeys struct { + + // SSH Keys + // Required: true + SSHKeys []*WorkspaceSSHKey `json:"sshKeys"` +} + +// Validate validates this workspace SSH keys +func (m *WorkspaceSSHKeys) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSSHKeys(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *WorkspaceSSHKeys) validateSSHKeys(formats strfmt.Registry) error { + + if err := validate.Required("sshKeys", "body", m.SSHKeys); err != nil { + return err + } + + for i := 0; i < len(m.SSHKeys); i++ { + if swag.IsZero(m.SSHKeys[i]) { // not required + continue + } + + if m.SSHKeys[i] != nil { + if err := m.SSHKeys[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshKeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshKeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this workspace SSH keys based on the context it is used +func (m *WorkspaceSSHKeys) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSSHKeys(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *WorkspaceSSHKeys) contextValidateSSHKeys(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SSHKeys); i++ { + + if m.SSHKeys[i] != nil { + + if swag.IsZero(m.SSHKeys[i]) { // not required + return nil + } + + if err := m.SSHKeys[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshKeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshKeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *WorkspaceSSHKeys) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *WorkspaceSSHKeys) UnmarshalBinary(b []byte) error { + var res WorkspaceSSHKeys + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/authenticator_factory.go b/vendor/github.com/IBM/go-sdk-core/v5/core/authenticator_factory.go index 586e38d072e4..87ce7e146df3 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/authenticator_factory.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/authenticator_factory.go @@ -1,6 +1,6 @@ package core -// (C) Copyright IBM Corp. 2019, 2024. +// (C) Copyright IBM Corp. 2019, 2025. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -63,6 +63,8 @@ func GetAuthenticatorFromEnvironment(credentialKey string) (authenticator Authen authenticator, err = newCloudPakForDataAuthenticatorFromMap(properties) } else if strings.EqualFold(authType, AUTHTYPE_MCSP) { authenticator, err = newMCSPAuthenticatorFromMap(properties) + } else if strings.EqualFold(authType, AUTHTYPE_MCSPV2) { + authenticator, err = newMCSPV2AuthenticatorFromMap(properties) } else if strings.EqualFold(authType, AUTHTYPE_NOAUTH) { authenticator, err = NewNoAuthAuthenticator() } else { diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/base_service.go b/vendor/github.com/IBM/go-sdk-core/v5/core/base_service.go index ce2d753945f8..5585494571a9 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/base_service.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/base_service.go @@ -357,13 +357,13 @@ func (service *BaseService) SetUserAgent(userAgent string) { // // err: a non-nil error object if an error occurred func (service *BaseService) Request(req *http.Request, result interface{}) (detailedResponse *DetailedResponse, err error) { - // Add default headers. + // Set default headers on the request. if service.DefaultHeaders != nil { for k, v := range service.DefaultHeaders { - req.Header.Add(k, strings.Join(v, "")) + req.Header.Set(k, strings.Join(v, "")) } - // After adding the default headers, make one final check to see if the user + // After setting the default headers, make one final check to see if the user // specified the "Host" header within the default headers. // This needs to be handled separately because it will be ignored by // the Request.Write() method. diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/constants.go b/vendor/github.com/IBM/go-sdk-core/v5/core/constants.go index b6f5a7e70ba3..3f2dada8512a 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/constants.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/constants.go @@ -1,6 +1,6 @@ package core -// (C) Copyright IBM Corp. 2019, 2023. +// (C) Copyright IBM Corp. 2019, 2025. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ const ( AUTHTYPE_CONTAINER = "container" AUTHTYPE_VPC = "vpc" AUTHTYPE_MCSP = "mcsp" + AUTHTYPE_MCSPV2 = "mcspv2" // Names of properties that can be defined as part of an external configuration (credential file, env vars, etc.). // Example: export MYSERVICE_URL=https://myurl @@ -38,22 +39,29 @@ const ( PROPNAME_SVC_RETRY_INTERVAL = "RETRY_INTERVAL" // Authenticator properties. - PROPNAME_AUTH_TYPE = "AUTH_TYPE" - PROPNAME_USERNAME = "USERNAME" - PROPNAME_PASSWORD = "PASSWORD" - PROPNAME_BEARER_TOKEN = "BEARER_TOKEN" - PROPNAME_AUTH_URL = "AUTH_URL" - PROPNAME_AUTH_DISABLE_SSL = "AUTH_DISABLE_SSL" - PROPNAME_APIKEY = "APIKEY" - PROPNAME_REFRESH_TOKEN = "REFRESH_TOKEN" // #nosec G101 - PROPNAME_CLIENT_ID = "CLIENT_ID" - PROPNAME_CLIENT_SECRET = "CLIENT_SECRET" - PROPNAME_SCOPE = "SCOPE" - PROPNAME_CRTOKEN_FILENAME = "CR_TOKEN_FILENAME" // #nosec G101 - PROPNAME_IAM_PROFILE_CRN = "IAM_PROFILE_CRN" - PROPNAME_IAM_PROFILE_NAME = "IAM_PROFILE_NAME" - PROPNAME_IAM_PROFILE_ID = "IAM_PROFILE_ID" - PROPNAME_IAM_ACCOUNT_ID = "IAM_ACCOUNT_ID" + PROPNAME_AUTH_TYPE = "AUTH_TYPE" + PROPNAME_USERNAME = "USERNAME" + PROPNAME_PASSWORD = "PASSWORD" + PROPNAME_BEARER_TOKEN = "BEARER_TOKEN" + PROPNAME_AUTH_URL = "AUTH_URL" + PROPNAME_AUTH_DISABLE_SSL = "AUTH_DISABLE_SSL" + PROPNAME_APIKEY = "APIKEY" + PROPNAME_REFRESH_TOKEN = "REFRESH_TOKEN" // #nosec G101 + PROPNAME_CLIENT_ID = "CLIENT_ID" + PROPNAME_CLIENT_SECRET = "CLIENT_SECRET" + PROPNAME_SCOPE = "SCOPE" + PROPNAME_CRTOKEN_FILENAME = "CR_TOKEN_FILENAME" // #nosec G101 + PROPNAME_IAM_PROFILE_CRN = "IAM_PROFILE_CRN" + PROPNAME_IAM_PROFILE_NAME = "IAM_PROFILE_NAME" + PROPNAME_IAM_PROFILE_ID = "IAM_PROFILE_ID" + PROPNAME_IAM_ACCOUNT_ID = "IAM_ACCOUNT_ID" + PROPNAME_SCOPE_COLLECTION_TYPE = "SCOPE_COLLECTION_TYPE" + PROPNAME_SCOPE_ID = "SCOPE_ID" + PROPNAME_INCLUDE_BUILTIN_ACTIONS = "INCLUDE_BUILTIN_ACTIONS" + PROPNAME_INCLUDE_CUSTOM_ACTIONS = "INCLUDE_CUSTOM_ACTIONS" + PROPNAME_INCLUDE_ROLES = "INCLUDE_ROLES" + PROPNAME_PREFIX_ROLES = "PREFIX_ROLES" + PROPNAME_CALLER_EXT_CLAIM = "CALLER_EXT_CLAIM" // SSL error SSL_CERTIFICATION_ERROR = "x509: certificate" @@ -86,6 +94,7 @@ const ( ERRORMSG_UNABLE_RETRIEVE_IITOKEN = "unable to retrieve instance identity token value: %s" // #nosec G101 ERRORMSG_VPCMDS_OPERATION_ERROR = "VPC metadata service error, status code %d received from '%s': %s" ERRORMSG_ACCOUNTID_PROP_ERROR = "IAMAccountID must be specified if and only if IAMProfileName is specified" + ERRORMSG_PROP_PARSE_ERROR = "error parsing configuration property %s, value=%s" // The name of this module - matches the value in the go.mod file. MODULE_NAME = "github.com/IBM/go-sdk-core/v5" diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/container_authenticator.go b/vendor/github.com/IBM/go-sdk-core/v5/core/container_authenticator.go index 651ae07811b1..2a47409f4154 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/container_authenticator.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/container_authenticator.go @@ -195,6 +195,7 @@ func (authenticator *ContainerAuthenticator) client() *http.Client { transport := &http.Transport{ // #nosec G402 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + Proxy: http.ProxyFromEnvironment, } authenticator.Client.Transport = transport } diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/cp4d_authenticator.go b/vendor/github.com/IBM/go-sdk-core/v5/core/cp4d_authenticator.go index fb8e30434440..72917521277d 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/cp4d_authenticator.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/cp4d_authenticator.go @@ -177,6 +177,7 @@ func (authenticator *CloudPakForDataAuthenticator) client() *http.Client { transport := &http.Transport{ // #nosec G402 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + Proxy: http.ProxyFromEnvironment, } authenticator.Client.Transport = transport } diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/iam_assume_authenticator.go b/vendor/github.com/IBM/go-sdk-core/v5/core/iam_assume_authenticator.go index 0132b41f21a5..634f30a10540 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/iam_assume_authenticator.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/iam_assume_authenticator.go @@ -265,6 +265,7 @@ func (authenticator *IamAssumeAuthenticator) getClient() *http.Client { transport := &http.Transport{ // #nosec G402 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + Proxy: http.ProxyFromEnvironment, } authenticator.client.Transport = transport } diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/iam_authenticator.go b/vendor/github.com/IBM/go-sdk-core/v5/core/iam_authenticator.go index ff083083ce5d..aea048411005 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/iam_authenticator.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/iam_authenticator.go @@ -187,6 +187,7 @@ func (authenticator *IamAuthenticator) client() *http.Client { transport := &http.Transport{ // #nosec G402 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + Proxy: http.ProxyFromEnvironment, } authenticator.Client.Transport = transport } diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_authenticator.go b/vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_v1_authenticator.go similarity index 99% rename from vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_authenticator.go rename to vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_v1_authenticator.go index 1fae07ed4149..0bf05c88cd88 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_authenticator.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_v1_authenticator.go @@ -133,6 +133,7 @@ func (authenticator *MCSPAuthenticator) client() *http.Client { transport := &http.Transport{ // #nosec G402 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + Proxy: http.ProxyFromEnvironment, } authenticator.Client.Transport = transport } diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_v2_authenticator.go b/vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_v2_authenticator.go new file mode 100644 index 000000000000..ec88a6d47b97 --- /dev/null +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/mcsp_v2_authenticator.go @@ -0,0 +1,619 @@ +package core + +// (C) Copyright IBM Corp. 2025. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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/json" + "errors" + "fmt" + "net/http" + "net/http/httputil" + "strconv" + "sync" + "time" +) + +// MCSPV2Authenticator invokes the MCSP v2 token-exchange operation (POST /api/2.0/{scopeCollectionType}/{scopeId}/apikeys/token) +// to obtain an access token for an apikey, and adds the access token to requests via an Authorization header +// of the form: "Authorization: Bearer " +type MCSPV2Authenticator struct { + // [Required] The apikey used to fetch the access token from the token server. + ApiKey string + + // [Required] The endpoint base URL for the token server. + URL string + + // [Required] The scope collection type of item(s). + // Valid values are: "accounts", "subscriptions", "services". + ScopeCollectionType string + + // [Required] The scope identifier of item(s). + ScopeID string + + // [Optional] A flag to include builtin actions in the "actions" claim in the MCSP access token (default: false). + IncludeBuiltinActions bool + + // [Optional] A flag to include custom actions in the "actions" claim in the MCSP access token (default: false). + IncludeCustomActions bool + + // [Optional] A flag to include the "roles" claim in the MCSP access token (default: true). + IncludeRoles bool + + // [Optional] A flag to add a prefix with the scope level where the role is defined in the "roles" claim (default: false). + PrefixRoles bool + + // [Optional] A map containing keys and values to be injected into the access token as the "callerExt" claim. + // The keys used in this map must be enabled in the apikey by setting the "callerExtClaimNames" property when the apikey is created. + // This property is typically only used in scenarios involving an apikey with identityType `SERVICEID`. + CallerExtClaim map[string]string + + // [Optional] A flag that indicates whether verification of the token server's SSL certificate + // should be disabled; defaults to false. + DisableSSLVerification bool + + // [Optional] A set of key/value pairs that will be sent as HTTP headers in requests + // made to the token server. + Headers map[string]string + + // [Optional] The http.Client object used to invoke token server requests. + // If not specified by the user, a suitable default Client will be constructed. + Client *http.Client + clientInit sync.Once + + // The User-Agent header value to be included with each token request. + userAgent string + userAgentInit sync.Once + + // The cached token and expiration time. + tokenData *mcspv2TokenData + + // Mutex to make the tokenData field thread safe. + tokenDataMutex sync.Mutex +} + +var ( + mcspv2RequestTokenMutex sync.Mutex + mcspv2NeedsRefreshMutex sync.Mutex +) + +const ( + mcspv2AuthOperationPath = "/api/2.0/{scopeCollectionType}/{scopeId}/apikeys/token" +) + +// MCSPV2AuthenticatorBuilder is used to construct an MCSPV2Authenticator instance. +type MCSPV2AuthenticatorBuilder struct { + MCSPV2Authenticator +} + +// NewMCSPV2AuthenticatorBuilder returns a new builder struct that +// can be used to construct an MCSPV2Authenticator instance. +func NewMCSPV2AuthenticatorBuilder() *MCSPV2AuthenticatorBuilder { + auth := &MCSPV2AuthenticatorBuilder{} + + // Set fields whose default value is not the "zero value". + auth.MCSPV2Authenticator.IncludeRoles = true + + return auth +} + +// SetApiKey sets the ApiKey field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetApiKey(s string) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.ApiKey = s + return builder +} + +// SetURL sets the URL field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetURL(s string) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.URL = s + return builder +} + +// SetScopeCollectionType sets the ScopeCollectionType field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetScopeCollectionType(s string) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.ScopeCollectionType = s + return builder +} + +// SetScopeID sets the ScopeID field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetScopeID(s string) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.ScopeID = s + return builder +} + +// SetIncludeBuiltinActions sets the IncludeBuiltinActions field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetIncludeBuiltinActions(b bool) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.IncludeBuiltinActions = b + return builder +} + +// SetIncludeCustomActions sets the IncludeCustomActions field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetIncludeCustomActions(b bool) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.IncludeCustomActions = b + return builder +} + +// SetIncludeRoles sets the IncludeRoles field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetIncludeRoles(b bool) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.IncludeRoles = b + return builder +} + +// SetPrefixRoles sets the PrefixRoles field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetPrefixRoles(b bool) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.PrefixRoles = b + return builder +} + +// SetCallerExtClaim sets the CallerExtClaim field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetCallerExtClaim(m map[string]string) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.CallerExtClaim = m + return builder +} + +// SetDisableSSLVerification sets the DisableSSLVerification field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetDisableSSLVerification(b bool) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.DisableSSLVerification = b + return builder +} + +// SetHeaders sets the Headers field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetHeaders(headers map[string]string) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.Headers = headers + return builder +} + +// SetClient sets the Client field in the builder. +func (builder *MCSPV2AuthenticatorBuilder) SetClient(client *http.Client) *MCSPV2AuthenticatorBuilder { + builder.MCSPV2Authenticator.Client = client + return builder +} + +// Build returns a validated instance of the MCSPV2Authenticator with the config that was set in the builder. +func (builder *MCSPV2AuthenticatorBuilder) Build() (*MCSPV2Authenticator, error) { + // Make sure the config is valid. + err := builder.MCSPV2Authenticator.Validate() + if err != nil { + return nil, RepurposeSDKProblem(err, "validation-failed") + } + + return &builder.MCSPV2Authenticator, nil +} + +// Validate the authenticator's configuration. +func (authenticator *MCSPV2Authenticator) Validate() error { + if authenticator.ApiKey == "" { + err := fmt.Errorf(ERRORMSG_PROP_MISSING, "ApiKey") + return SDKErrorf(err, "", "missing-api-key", getComponentInfo()) + } + + if authenticator.URL == "" { + err := fmt.Errorf(ERRORMSG_PROP_MISSING, "URL") + return SDKErrorf(err, "", "missing-url", getComponentInfo()) + } + + if authenticator.ScopeCollectionType == "" { + err := fmt.Errorf(ERRORMSG_PROP_MISSING, "ScopeCollectionType") + return SDKErrorf(err, "", "missing-scope-collection-type", getComponentInfo()) + } + + if authenticator.ScopeID == "" { + err := fmt.Errorf(ERRORMSG_PROP_MISSING, "ScopeID") + return SDKErrorf(err, "", "missing-scope-id", getComponentInfo()) + } + + return nil +} + +// client returns the authenticator's http client after potentially initializing it. +func (authenticator *MCSPV2Authenticator) client() *http.Client { + authenticator.clientInit.Do(func() { + if authenticator.Client == nil { + authenticator.Client = DefaultHTTPClient() + authenticator.Client.Timeout = time.Second * 30 + + // If the user told us to disable SSL verification, then do it now. + if authenticator.DisableSSLVerification { + transport := &http.Transport{ + // #nosec G402 + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + Proxy: http.ProxyFromEnvironment, + } + authenticator.Client.Transport = transport + } + } + }) + return authenticator.Client +} + +// getUserAgent returns the User-Agent header value to be included in each token request invoked by the authenticator. +func (authenticator *MCSPV2Authenticator) getUserAgent() string { + authenticator.userAgentInit.Do(func() { + authenticator.userAgent = fmt.Sprintf("%s/%s-%s %s", sdkName, "mcspv2-authenticator", __VERSION__, SystemInfo()) + }) + return authenticator.userAgent +} + +// newMCSPV2AuthenticatorFromMap constructs a new MCSPV2Authenticator instance from a map. +func newMCSPV2AuthenticatorFromMap(properties map[string]string) (authenticator *MCSPV2Authenticator, err error) { + if properties == nil { + err = errors.New(ERRORMSG_PROPS_MAP_NIL) + return nil, SDKErrorf(err, "", "missing-props", getComponentInfo()) + } + + // Initialize the builder first with the required properties. + builder := NewMCSPV2AuthenticatorBuilder(). + SetApiKey(properties[PROPNAME_APIKEY]). + SetURL(properties[PROPNAME_AUTH_URL]). + SetScopeCollectionType(properties[PROPNAME_SCOPE_COLLECTION_TYPE]). + SetScopeID(properties[PROPNAME_SCOPE_ID]) + + // Now add the optional properties to the builder. + var strValue string + var boolValue bool + + strValue = properties[PROPNAME_INCLUDE_BUILTIN_ACTIONS] + if strValue != "" { + boolValue, err = strconv.ParseBool(strValue) + if err != nil { + err = SDKErrorf(err, + fmt.Sprintf(ERRORMSG_PROP_PARSE_ERROR, PROPNAME_INCLUDE_BUILTIN_ACTIONS, strValue), + "validation-error", getComponentInfo()) + return + } + builder.SetIncludeBuiltinActions(boolValue) + } + + strValue = properties[PROPNAME_INCLUDE_CUSTOM_ACTIONS] + if strValue != "" { + boolValue, err = strconv.ParseBool(strValue) + if err != nil { + err = SDKErrorf(err, + fmt.Sprintf(ERRORMSG_PROP_PARSE_ERROR, PROPNAME_INCLUDE_CUSTOM_ACTIONS, strValue), + "validation-error", getComponentInfo()) + return + } + builder.SetIncludeCustomActions(boolValue) + } + + strValue = properties[PROPNAME_INCLUDE_ROLES] + if strValue != "" { + boolValue, err = strconv.ParseBool(strValue) + if err != nil { + err = SDKErrorf(err, + fmt.Sprintf(ERRORMSG_PROP_PARSE_ERROR, PROPNAME_INCLUDE_ROLES, strValue), + "validation-error", getComponentInfo()) + return + } + builder.SetIncludeRoles(boolValue) + } + + strValue = properties[PROPNAME_PREFIX_ROLES] + if strValue != "" { + boolValue, err = strconv.ParseBool(strValue) + if err != nil { + err = SDKErrorf(err, + fmt.Sprintf(ERRORMSG_PROP_PARSE_ERROR, PROPNAME_PREFIX_ROLES, strValue), + "validation-error", getComponentInfo()) + return + } + builder.SetPrefixRoles(boolValue) + } + + strValue = properties[PROPNAME_AUTH_DISABLE_SSL] + if strValue != "" { + boolValue, err = strconv.ParseBool(strValue) + if err != nil { + err = SDKErrorf(err, + fmt.Sprintf(ERRORMSG_PROP_PARSE_ERROR, PROPNAME_AUTH_DISABLE_SSL, strValue), + "validation-error", getComponentInfo()) + return + } + builder.SetDisableSSLVerification(boolValue) + } + + // The CallerExtClaim property is a map[string]string and we allow the + // user to set it as a JSON string when using an external config property. + // Here we retrieve it from the config as a string and unmarshal into a map. + strValue = properties[PROPNAME_CALLER_EXT_CLAIM] + if strValue != "" { + var m map[string]string + err = json.Unmarshal([]byte(strValue), &m) + if err != nil { + err = SDKErrorf(err, + fmt.Sprintf(ERRORMSG_PROP_PARSE_ERROR, PROPNAME_CALLER_EXT_CLAIM, strValue), + "validation-error", getComponentInfo()) + return + } + builder.SetCallerExtClaim(m) + } + + authenticator, err = builder.Build() + + return +} + +// AuthenticationType returns the authentication type for this authenticator. +func (*MCSPV2Authenticator) AuthenticationType() string { + return AUTHTYPE_MCSPV2 +} + +// Authenticate adds the Authorization header to the request. +// The value will be of the form: "Authorization: Bearer "" +func (authenticator *MCSPV2Authenticator) Authenticate(request *http.Request) error { + token, err := authenticator.GetToken() + if err != nil { + return RepurposeSDKProblem(err, "get-token-fail") + } + + request.Header.Set("Authorization", "Bearer "+token) + GetLogger().Debug("Authenticated outbound request (type=%s)\n", authenticator.AuthenticationType()) + return nil +} + +// getTokenData returns the tokenData field from the authenticator. +func (authenticator *MCSPV2Authenticator) getTokenData() *mcspv2TokenData { + authenticator.tokenDataMutex.Lock() + defer authenticator.tokenDataMutex.Unlock() + + return authenticator.tokenData +} + +// setTokenData sets the given mcspv2TokenData to the tokenData field of the authenticator. +func (authenticator *MCSPV2Authenticator) setTokenData(tokenData *mcspv2TokenData) { + authenticator.tokenDataMutex.Lock() + defer authenticator.tokenDataMutex.Unlock() + + authenticator.tokenData = tokenData + GetLogger().Debug("setTokenData: expiration=%d, refreshTime=%d", + authenticator.tokenData.Expiration, authenticator.tokenData.RefreshTime) +} + +// GetToken: returns an access token to be used in an Authorization header. +// Whenever a new token is needed (when a token doesn't yet exist, needs to be refreshed, +// or the existing token has expired), a new access token is fetched from the token server. +func (authenticator *MCSPV2Authenticator) GetToken() (string, error) { + if authenticator.getTokenData() == nil || !authenticator.getTokenData().isTokenValid() { + GetLogger().Debug("Performing synchronous token fetch...") + // synchronously request the token + err := authenticator.synchronizedRequestToken() + if err != nil { + return "", RepurposeSDKProblem(err, "request-token-fail") + } + } else if authenticator.getTokenData().needsRefresh() { + GetLogger().Debug("Performing background asynchronous token fetch...") + // If refresh needed, kick off a go routine in the background to get a new token. + //nolint: errcheck + go authenticator.invokeRequestTokenData() + } else { + GetLogger().Debug("Using cached access token...") + } + + // return an error if the access token is not valid or was not fetched + if authenticator.getTokenData() == nil || authenticator.getTokenData().AccessToken == "" { + err := errors.New("Error while trying to get access token") + return "", SDKErrorf(err, "", "no-token", getComponentInfo()) + } + + return authenticator.getTokenData().AccessToken, nil +} + +// synchronizedRequestToken: synchronously checks if the current token in cache +// is valid. If token is not valid or does not exist, it will fetch a new token. +func (authenticator *MCSPV2Authenticator) synchronizedRequestToken() error { + mcspv2RequestTokenMutex.Lock() + defer mcspv2RequestTokenMutex.Unlock() + // if cached token is still valid, then just continue to use it + if authenticator.getTokenData() != nil && authenticator.getTokenData().isTokenValid() { + return nil + } + + return authenticator.invokeRequestTokenData() +} + +// invokeRequestTokenData: requests a new token from the access server and +// unmarshals the token information to the tokenData cache. Returns +// an error if the token was unable to be fetched, otherwise returns nil +func (authenticator *MCSPV2Authenticator) invokeRequestTokenData() error { + tokenResponse, err := authenticator.RequestToken() + if err != nil { + return err + } + + GetLogger().Debug("invokeRequestTokenData(): RequestToken returned tokenResponse:\n%+v", *tokenResponse) + tokenData, err := newMCSPV2TokenData(tokenResponse) + if err != nil { + tokenData = &mcspv2TokenData{} + } + + authenticator.setTokenData(tokenData) + + return nil +} + +// RequestToken fetches a new access token from the token server. +func (authenticator *MCSPV2Authenticator) RequestToken() (*MCSPV2TokenServerResponse, error) { + builder := NewRequestBuilder(POST) + pathParams := map[string]string{ + "scopeCollectionType": authenticator.ScopeCollectionType, + "scopeId": authenticator.ScopeID, + } + _, err := builder.ResolveRequestURL(authenticator.URL, mcspv2AuthOperationPath, pathParams) + if err != nil { + err = RepurposeSDKProblem(err, "url-resolve-error") + return nil, err + } + + // Add the request headers. + builder.AddHeader(CONTENT_TYPE, APPLICATION_JSON) + builder.AddHeader(Accept, APPLICATION_JSON) + builder.AddHeader(headerNameUserAgent, authenticator.getUserAgent()) + + // Add the query params. + builder.AddQuery("includeBuiltinActions", strconv.FormatBool(authenticator.IncludeBuiltinActions)) + builder.AddQuery("includeCustomActions", strconv.FormatBool(authenticator.IncludeCustomActions)) + builder.AddQuery("includeRoles", strconv.FormatBool(authenticator.IncludeRoles)) + builder.AddQuery("prefixRolesWithDefinitionScope", strconv.FormatBool(authenticator.PrefixRoles)) + + // The requestBody will consist of the apikey and (optionally) the callerExtClaim map. + requestBody := make(map[string]any) + requestBody["apikey"] = authenticator.ApiKey + if len(authenticator.CallerExtClaim) > 0 { + requestBody["callerExtClaim"] = authenticator.CallerExtClaim + } + _, _ = builder.SetBodyContentJSON(requestBody) + + // Add user-defined headers to request. + for headerName, headerValue := range authenticator.Headers { + builder.AddHeader(headerName, headerValue) + } + + req, err := builder.Build() + if err != nil { + return nil, RepurposeSDKProblem(err, "request-build-error") + } + + // If debug is enabled, then dump the request. + if GetLogger().IsLogLevelEnabled(LevelDebug) { + buf, dumpErr := httputil.DumpRequestOut(req, req.Body != nil) + if dumpErr == nil { + GetLogger().Debug("Request:\n%s\n", RedactSecrets(string(buf))) + } else { + GetLogger().Debug(fmt.Sprintf("error while attempting to log outbound request: %s", dumpErr.Error())) + } + } + + GetLogger().Debug("Invoking MCSP 'get token' operation: %s", builder.URL) + resp, err := authenticator.client().Do(req) + if err != nil { + err = SDKErrorf(err, "", "request-error", getComponentInfo()) + return nil, err + } + GetLogger().Debug("Returned from MCSP 'get token' operation, received status code %d", resp.StatusCode) + + // If debug is enabled, then dump the response. + if GetLogger().IsLogLevelEnabled(LevelDebug) { + buf, dumpErr := httputil.DumpResponse(resp, req.Body != nil) + if dumpErr == nil { + GetLogger().Debug("Response:\n%s\n", RedactSecrets(string(buf))) + } else { + GetLogger().Debug(fmt.Sprintf("error while attempting to log inbound response: %s", dumpErr.Error())) + } + } + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + detailedResponse, err := processErrorResponse(resp) + authError := authenticationErrorf(err, detailedResponse, "get_token", authenticator.getComponentInfo()) + + // The err Summary is typically the message computed for the HTTPError instance in + // processErrorResponse(). If the response body is non-JSON, the message will be generic + // text based on the status code but authenticators have always used the stringified + // RawResult, so update that here for compatilibility. + errorMsg := err.Summary + if detailedResponse.RawResult != nil { + // RawResult is only populated if the response body is + // non-JSON and we couldn't extract a message. + errorMsg = string(detailedResponse.RawResult) + } + + authError.Summary = errorMsg + + return nil, authError + } + + tokenResponse := &MCSPV2TokenServerResponse{} + _ = json.NewDecoder(resp.Body).Decode(tokenResponse) + defer resp.Body.Close() // #nosec G307 + + return tokenResponse, nil +} + +func (authenticator *MCSPV2Authenticator) getComponentInfo() *ProblemComponent { + return NewProblemComponent("mscp_token_server", "1.0") +} + +// MCSPTokenServerResponse : This struct models a response received from the token server. +type MCSPV2TokenServerResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresIn int64 `json:"expires_in"` + Expiration int64 `json:"expiration"` +} + +// mcspv2TokenData : This struct represents the cached information related to a fetched access token. +type mcspv2TokenData struct { + AccessToken string + RefreshTime int64 + Expiration int64 +} + +// newMCSPV2TokenData: constructs a new mcspv2TokenData instance from the specified +// MCSPV2TokenServerResponse instance. +func newMCSPV2TokenData(tokenResponse *MCSPV2TokenServerResponse) (*mcspv2TokenData, error) { + if tokenResponse == nil || tokenResponse.Token == "" { + err := errors.New("Error while trying to parse access token!") + return nil, SDKErrorf(err, "", "token-parse", getComponentInfo()) + } + + // Need to crack open the access token (a JWT) to get the expiration and issued-at times + // so that we can compute the refresh time. + claims, err := parseJWT(tokenResponse.Token) + if err != nil { + return nil, err + } + + // Compute the adjusted refresh time (expiration time - 20% of timeToLive) + timeToLive := claims.ExpiresAt - claims.IssuedAt + expireTime := claims.ExpiresAt + refreshTime := expireTime - int64(float64(timeToLive)*0.2) + + tokenData := &mcspv2TokenData{ + AccessToken: tokenResponse.Token, + Expiration: expireTime, + RefreshTime: refreshTime, + } + + GetLogger().Debug("newMCSPV2TokenData: expiration=%d, refreshTime=%d", tokenData.Expiration, tokenData.RefreshTime) + + return tokenData, nil +} + +// isTokenValid: returns true iff the mcspv2TokenData instance represents a valid (non-expired) access token. +func (tokenData *mcspv2TokenData) isTokenValid() bool { + if tokenData.AccessToken != "" && GetCurrentTime() < tokenData.Expiration { + GetLogger().Debug("isTokenValid: Token is valid!") + return true + } + GetLogger().Debug("isTokenValid: Token is NOT valid!") + GetLogger().Debug("isTokenValid: expiration=%d, refreshTime=%d", tokenData.Expiration, tokenData.RefreshTime) + GetLogger().Debug("GetCurrentTime(): %d\n", GetCurrentTime()) + return false +} + +// needsRefresh: synchronously returns true iff the currently stored access token should be refreshed. This method also +// updates the refresh time if it determines the token needs refreshed to prevent other threads from +// making multiple refresh calls. +func (tokenData *mcspv2TokenData) needsRefresh() bool { + mcspv2NeedsRefreshMutex.Lock() + defer mcspv2NeedsRefreshMutex.Unlock() + + // Advance refresh by one minute + if tokenData.RefreshTime >= 0 && GetCurrentTime() > tokenData.RefreshTime { + tokenData.RefreshTime = GetCurrentTime() + 60 + return true + } + + return false +} diff --git a/vendor/github.com/IBM/go-sdk-core/v5/core/version.go b/vendor/github.com/IBM/go-sdk-core/v5/core/version.go index 3da426afa595..5b70ae7ff9c5 100644 --- a/vendor/github.com/IBM/go-sdk-core/v5/core/version.go +++ b/vendor/github.com/IBM/go-sdk-core/v5/core/version.go @@ -15,4 +15,4 @@ package core // limitations under the License. // Version of the SDK -const __VERSION__ = "5.19.1" +const __VERSION__ = "5.21.0" diff --git a/vendor/github.com/IBM/ibm-cos-sdk-go/aws/version.go b/vendor/github.com/IBM/ibm-cos-sdk-go/aws/version.go index 95757b25c49c..770f83fd6024 100644 --- a/vendor/github.com/IBM/ibm-cos-sdk-go/aws/version.go +++ b/vendor/github.com/IBM/ibm-cos-sdk-go/aws/version.go @@ -7,6 +7,6 @@ package aws const SDKName = "ibm-cos-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "1.12.2" +const SDKVersion = "1.12.3" // IBM COS SDK Code -- END diff --git a/vendor/github.com/IBM/networking-go-sdk/common/version.go b/vendor/github.com/IBM/networking-go-sdk/common/version.go index 5bdde8593a74..e8e8941a73ab 100644 --- a/vendor/github.com/IBM/networking-go-sdk/common/version.go +++ b/vendor/github.com/IBM/networking-go-sdk/common/version.go @@ -17,4 +17,4 @@ package common // Version of the SDK -const Version = "0.51.4" +const Version = "0.51.5" diff --git a/vendor/github.com/IBM/networking-go-sdk/transitgatewayapisv1/transit_gateway_apis_v1.go b/vendor/github.com/IBM/networking-go-sdk/transitgatewayapisv1/transit_gateway_apis_v1.go index efc046d23336..df0c02ccff83 100644 --- a/vendor/github.com/IBM/networking-go-sdk/transitgatewayapisv1/transit_gateway_apis_v1.go +++ b/vendor/github.com/IBM/networking-go-sdk/transitgatewayapisv1/transit_gateway_apis_v1.go @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2024. + * (C) Copyright IBM Corp. 2025. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -283,6 +283,9 @@ func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayWithContext( if createTransitGatewayOptions.Global != nil { body["global"] = createTransitGatewayOptions.Global } + if createTransitGatewayOptions.GreEnhancedRoutePropagation != nil { + body["gre_enhanced_route_propagation"] = createTransitGatewayOptions.GreEnhancedRoutePropagation + } if createTransitGatewayOptions.ResourceGroup != nil { body["resource_group"] = createTransitGatewayOptions.ResourceGroup } @@ -471,6 +474,9 @@ func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayWithContext( if updateTransitGatewayOptions.Global != nil { body["global"] = updateTransitGatewayOptions.Global } + if updateTransitGatewayOptions.GreEnhancedRoutePropagation != nil { + body["gre_enhanced_route_propagation"] = updateTransitGatewayOptions.GreEnhancedRoutePropagation + } if updateTransitGatewayOptions.Name != nil { body["name"] = updateTransitGatewayOptions.Name } @@ -541,6 +547,9 @@ func (transitGatewayApis *TransitGatewayApisV1) ListConnectionsWithContext(ctx c if listConnectionsOptions.NetworkID != nil { builder.AddQuery("network_id", fmt.Sprint(*listConnectionsOptions.NetworkID)) } + if listConnectionsOptions.NetworkType != nil { + builder.AddQuery("network_type", fmt.Sprint(*listConnectionsOptions.NetworkType)) + } request, err := builder.Build() if err != nil { @@ -634,7 +643,7 @@ func (transitGatewayApis *TransitGatewayApisV1) ListTransitGatewayConnectionsWit return } -// CreateTransitGatewayConnection : Add connection to a Transit Gateway +// CreateTransitGatewayConnection : Adds a connection to a Transit Gateway // Add a connection to Transit Gateway. func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayConnection(createTransitGatewayConnectionOptions *CreateTransitGatewayConnectionOptions) (result *TransitGatewayConnectionCust, response *core.DetailedResponse, err error) { return transitGatewayApis.CreateTransitGatewayConnectionWithContext(context.Background(), createTransitGatewayConnectionOptions) @@ -686,6 +695,9 @@ func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayConnectionWi if createTransitGatewayConnectionOptions.BaseNetworkType != nil { body["base_network_type"] = createTransitGatewayConnectionOptions.BaseNetworkType } + if createTransitGatewayConnectionOptions.Cidr != nil { + body["cidr"] = createTransitGatewayConnectionOptions.Cidr + } if createTransitGatewayConnectionOptions.LocalGatewayIp != nil { body["local_gateway_ip"] = createTransitGatewayConnectionOptions.LocalGatewayIp } @@ -748,7 +760,7 @@ func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayConnectionWi return } -// DeleteTransitGatewayConnection : Remove connection from Transit Gateway +// DeleteTransitGatewayConnection : Removes a connection from Transit Gateway // After the specified connection is detached, entities still within the Transit Gateway will no longer be able to // communicate directly to it through the IBM Cloud private backbone. func (transitGatewayApis *TransitGatewayApisV1) DeleteTransitGatewayConnection(deleteTransitGatewayConnectionOptions *DeleteTransitGatewayConnectionOptions) (response *core.DetailedResponse, err error) { @@ -939,7 +951,7 @@ func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionWi return } -// CreateTransitGatewayConnectionActions : Perform actions on a connection for a Transit Gateway +// CreateTransitGatewayConnectionActions : Performs actions on a connection for a Transit Gateway // Allow a network owner to approve or reject a cross-account connection request. func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayConnectionActions(createTransitGatewayConnectionActionsOptions *CreateTransitGatewayConnectionActionsOptions) (response *core.DetailedResponse, err error) { return transitGatewayApis.CreateTransitGatewayConnectionActionsWithContext(context.Background(), createTransitGatewayConnectionActionsOptions) @@ -1000,26 +1012,26 @@ func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayConnectionAc return } -// GetTransitGatewayGreTunnel : Retrieves specified Transit Gateway redundant gre connection tunnels -// This request retrieves a list of all the tunnels for the redundant gre conneciton. -func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayGreTunnel(getTransitGatewayGreTunnelOptions *GetTransitGatewayGreTunnelOptions) (result *RedundantGRETunnelCollection, response *core.DetailedResponse, err error) { - return transitGatewayApis.GetTransitGatewayGreTunnelWithContext(context.Background(), getTransitGatewayGreTunnelOptions) +// ListTransitGatewayGreTunnel : Retrieves specified Transit Gateway redundant gre connection tunnels +// This request retrieves a list of all the tunnels for connection. +func (transitGatewayApis *TransitGatewayApisV1) ListTransitGatewayGreTunnel(listTransitGatewayGreTunnelOptions *ListTransitGatewayGreTunnelOptions) (result *TransitGatewayTunnelCollection, response *core.DetailedResponse, err error) { + return transitGatewayApis.ListTransitGatewayGreTunnelWithContext(context.Background(), listTransitGatewayGreTunnelOptions) } -// GetTransitGatewayGreTunnelWithContext is an alternate form of the GetTransitGatewayGreTunnel method which supports a Context parameter -func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayGreTunnelWithContext(ctx context.Context, getTransitGatewayGreTunnelOptions *GetTransitGatewayGreTunnelOptions) (result *RedundantGRETunnelCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getTransitGatewayGreTunnelOptions, "getTransitGatewayGreTunnelOptions cannot be nil") +// ListTransitGatewayGreTunnelWithContext is an alternate form of the ListTransitGatewayGreTunnel method which supports a Context parameter +func (transitGatewayApis *TransitGatewayApisV1) ListTransitGatewayGreTunnelWithContext(ctx context.Context, listTransitGatewayGreTunnelOptions *ListTransitGatewayGreTunnelOptions) (result *TransitGatewayTunnelCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listTransitGatewayGreTunnelOptions, "listTransitGatewayGreTunnelOptions cannot be nil") if err != nil { return } - err = core.ValidateStruct(getTransitGatewayGreTunnelOptions, "getTransitGatewayGreTunnelOptions") + err = core.ValidateStruct(listTransitGatewayGreTunnelOptions, "listTransitGatewayGreTunnelOptions") if err != nil { return } pathParamsMap := map[string]string{ - "transit_gateway_id": *getTransitGatewayGreTunnelOptions.TransitGatewayID, - "id": *getTransitGatewayGreTunnelOptions.ID, + "transit_gateway_id": *listTransitGatewayGreTunnelOptions.TransitGatewayID, + "id": *listTransitGatewayGreTunnelOptions.ID, } builder := core.NewRequestBuilder(core.GET) @@ -1030,11 +1042,11 @@ func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayGreTunnelWithCo return } - for headerName, headerValue := range getTransitGatewayGreTunnelOptions.Headers { + for headerName, headerValue := range listTransitGatewayGreTunnelOptions.Headers { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("transit_gateway_apis", "V1", "GetTransitGatewayGreTunnel") + sdkHeaders := common.GetSdkHeaders("transit_gateway_apis", "V1", "ListTransitGatewayGreTunnel") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } @@ -1053,7 +1065,7 @@ func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayGreTunnelWithCo return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRedundantGRETunnelCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTransitGatewayTunnelCollection) if err != nil { return } @@ -1063,14 +1075,14 @@ func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayGreTunnelWithCo return } -// CreateTransitGatewayGreTunnel : Create Transit Gateway redundant GRE tunnel +// CreateTransitGatewayGreTunnel : Creates a Transit Gateway redundant GRE tunnel // Add a tunnel to an existing Redundant GRE connection. -func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayGreTunnel(createTransitGatewayGreTunnelOptions *CreateTransitGatewayGreTunnelOptions) (result *RedundantGRETunnelReference, response *core.DetailedResponse, err error) { +func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayGreTunnel(createTransitGatewayGreTunnelOptions *CreateTransitGatewayGreTunnelOptions) (result *TransitGatewayTunnel, response *core.DetailedResponse, err error) { return transitGatewayApis.CreateTransitGatewayGreTunnelWithContext(context.Background(), createTransitGatewayGreTunnelOptions) } // CreateTransitGatewayGreTunnelWithContext is an alternate form of the CreateTransitGatewayGreTunnel method which supports a Context parameter -func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayGreTunnelWithContext(ctx context.Context, createTransitGatewayGreTunnelOptions *CreateTransitGatewayGreTunnelOptions) (result *RedundantGRETunnelReference, response *core.DetailedResponse, err error) { +func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayGreTunnelWithContext(ctx context.Context, createTransitGatewayGreTunnelOptions *CreateTransitGatewayGreTunnelOptions) (result *TransitGatewayTunnel, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(createTransitGatewayGreTunnelOptions, "createTransitGatewayGreTunnelOptions cannot be nil") if err != nil { return @@ -1144,7 +1156,7 @@ func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayGreTunnelWit return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRedundantGRETunnelReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTransitGatewayTunnel) if err != nil { return } @@ -1154,7 +1166,7 @@ func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayGreTunnelWit return } -// DeleteTransitGatewayConnectionTunnels : Delete specified Transit Gateway redundant GRE tunnel +// DeleteTransitGatewayConnectionTunnels : Deletes a specified Transit Gateway redundant GRE tunnel // Remove a tunnel from a redundant GRE connection. func (transitGatewayApis *TransitGatewayApisV1) DeleteTransitGatewayConnectionTunnels(deleteTransitGatewayConnectionTunnelsOptions *DeleteTransitGatewayConnectionTunnelsOptions) (response *core.DetailedResponse, err error) { return transitGatewayApis.DeleteTransitGatewayConnectionTunnelsWithContext(context.Background(), deleteTransitGatewayConnectionTunnelsOptions) @@ -1207,13 +1219,13 @@ func (transitGatewayApis *TransitGatewayApisV1) DeleteTransitGatewayConnectionTu } // GetTransitGatewayConnectionTunnels : Retrieves specified Transit Gateway connection tunnel -// This request retrieves a connection tunnel from the Transit Gateway Connection. -func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayConnectionTunnels(getTransitGatewayConnectionTunnelsOptions *GetTransitGatewayConnectionTunnelsOptions) (result *RedundantGRETunnelReference, response *core.DetailedResponse, err error) { +// This request retrieves a connection tunnel from the Transit Gateway connection. +func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayConnectionTunnels(getTransitGatewayConnectionTunnelsOptions *GetTransitGatewayConnectionTunnelsOptions) (result *TransitGatewayTunnel, response *core.DetailedResponse, err error) { return transitGatewayApis.GetTransitGatewayConnectionTunnelsWithContext(context.Background(), getTransitGatewayConnectionTunnelsOptions) } // GetTransitGatewayConnectionTunnelsWithContext is an alternate form of the GetTransitGatewayConnectionTunnels method which supports a Context parameter -func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayConnectionTunnelsWithContext(ctx context.Context, getTransitGatewayConnectionTunnelsOptions *GetTransitGatewayConnectionTunnelsOptions) (result *RedundantGRETunnelReference, response *core.DetailedResponse, err error) { +func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayConnectionTunnelsWithContext(ctx context.Context, getTransitGatewayConnectionTunnelsOptions *GetTransitGatewayConnectionTunnelsOptions) (result *TransitGatewayTunnel, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getTransitGatewayConnectionTunnelsOptions, "getTransitGatewayConnectionTunnelsOptions cannot be nil") if err != nil { return @@ -1260,7 +1272,7 @@ func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayConnectionTunne return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRedundantGRETunnelReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTransitGatewayTunnel) if err != nil { return } @@ -1272,12 +1284,12 @@ func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayConnectionTunne // UpdateTransitGatewayConnectionTunnels : Updates specified Transit Gateway redundant GRE tunnel // Update the name of a connection tunnel. -func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionTunnels(updateTransitGatewayConnectionTunnelsOptions *UpdateTransitGatewayConnectionTunnelsOptions) (result *RedundantGRETunnelReference, response *core.DetailedResponse, err error) { +func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionTunnels(updateTransitGatewayConnectionTunnelsOptions *UpdateTransitGatewayConnectionTunnelsOptions) (result *TransitGatewayTunnel, response *core.DetailedResponse, err error) { return transitGatewayApis.UpdateTransitGatewayConnectionTunnelsWithContext(context.Background(), updateTransitGatewayConnectionTunnelsOptions) } // UpdateTransitGatewayConnectionTunnelsWithContext is an alternate form of the UpdateTransitGatewayConnectionTunnels method which supports a Context parameter -func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionTunnelsWithContext(ctx context.Context, updateTransitGatewayConnectionTunnelsOptions *UpdateTransitGatewayConnectionTunnelsOptions) (result *RedundantGRETunnelReference, response *core.DetailedResponse, err error) { +func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionTunnelsWithContext(ctx context.Context, updateTransitGatewayConnectionTunnelsOptions *UpdateTransitGatewayConnectionTunnelsOptions) (result *TransitGatewayTunnel, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(updateTransitGatewayConnectionTunnelsOptions, "updateTransitGatewayConnectionTunnelsOptions cannot be nil") if err != nil { return @@ -1310,15 +1322,11 @@ func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionTu builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*transitGatewayApis.Version)) - body := make(map[string]interface{}) - if updateTransitGatewayConnectionTunnelsOptions.Name != nil { - body["name"] = updateTransitGatewayConnectionTunnelsOptions.Name - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(updateTransitGatewayConnectionTunnelsOptions.TransitGatewayTunnelPatch) if err != nil { return } @@ -1334,7 +1342,7 @@ func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionTu return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRedundantGRETunnelReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTransitGatewayTunnel) if err != nil { return } @@ -1344,7 +1352,7 @@ func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionTu return } -// ListGatewayLocations : List all locations that support Transit Gateways +// ListGatewayLocations : Lists all locations that support Transit Gateways // List all locations that support Transit Gateways. func (transitGatewayApis *TransitGatewayApisV1) ListGatewayLocations(listGatewayLocationsOptions *ListGatewayLocationsOptions) (result *TSCollection, response *core.DetailedResponse, err error) { return transitGatewayApis.ListGatewayLocationsWithContext(context.Background(), listGatewayLocationsOptions) @@ -1398,7 +1406,7 @@ func (transitGatewayApis *TransitGatewayApisV1) ListGatewayLocationsWithContext( return } -// GetGatewayLocation : Show the details of a given Transit Gateway location +// GetGatewayLocation : Shows the details of a given Transit Gateway location // Get the details of a Transit Gateway Location. func (transitGatewayApis *TransitGatewayApisV1) GetGatewayLocation(getGatewayLocationOptions *GetGatewayLocationOptions) (result *TSLocation, response *core.DetailedResponse, err error) { return transitGatewayApis.GetGatewayLocationWithContext(context.Background(), getGatewayLocationOptions) @@ -1523,8 +1531,8 @@ func (transitGatewayApis *TransitGatewayApisV1) ListTransitGatewayConnectionPref return } -// CreateTransitGatewayConnectionPrefixFilter : Add a prefix filter to a Transit Gateway Connection -// Add a prefix filter to a Transit Gateway Connection. +// CreateTransitGatewayConnectionPrefixFilter : Add a prefix filter to a Transit Gateway connection +// Add a prefix filter to a Transit Gateway connection. func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayConnectionPrefixFilter(createTransitGatewayConnectionPrefixFilterOptions *CreateTransitGatewayConnectionPrefixFilterOptions) (result *PrefixFilterCust, response *core.DetailedResponse, err error) { return transitGatewayApis.CreateTransitGatewayConnectionPrefixFilterWithContext(context.Background(), createTransitGatewayConnectionPrefixFilterOptions) } @@ -1608,8 +1616,8 @@ func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayConnectionPr return } -// ReplaceTransitGatewayConnectionPrefixFilter : Replaces the prefix filters of the Transit Gateway Connection -// Replaces the prefix filters of the Transit Gateway Connection. +// ReplaceTransitGatewayConnectionPrefixFilter : Replaces the prefix filters of the Transit Gateway connection +// Replaces the prefix filters of the Transit Gateway connection. func (transitGatewayApis *TransitGatewayApisV1) ReplaceTransitGatewayConnectionPrefixFilter(replaceTransitGatewayConnectionPrefixFilterOptions *ReplaceTransitGatewayConnectionPrefixFilterOptions) (result *PrefixFilterCollection, response *core.DetailedResponse, err error) { return transitGatewayApis.ReplaceTransitGatewayConnectionPrefixFilterWithContext(context.Background(), replaceTransitGatewayConnectionPrefixFilterOptions) } @@ -1681,7 +1689,7 @@ func (transitGatewayApis *TransitGatewayApisV1) ReplaceTransitGatewayConnectionP return } -// DeleteTransitGatewayConnectionPrefixFilter : Remove prefix filter from Transit Gateway Connection +// DeleteTransitGatewayConnectionPrefixFilter : Remove prefix filter from Transit Gateway connection // Delete a prefix filter. func (transitGatewayApis *TransitGatewayApisV1) DeleteTransitGatewayConnectionPrefixFilter(deleteTransitGatewayConnectionPrefixFilterOptions *DeleteTransitGatewayConnectionPrefixFilterOptions) (response *core.DetailedResponse, err error) { return transitGatewayApis.DeleteTransitGatewayConnectionPrefixFilterWithContext(context.Background(), deleteTransitGatewayConnectionPrefixFilterOptions) @@ -1734,7 +1742,7 @@ func (transitGatewayApis *TransitGatewayApisV1) DeleteTransitGatewayConnectionPr } // GetTransitGatewayConnectionPrefixFilter : Retrieves specified Transit Gateway connection prefix filter -// This request retrieves a prefix filter from the Transit Gateway Connection. +// This request retrieves a prefix filter from the Transit Gateway connection. func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayConnectionPrefixFilter(getTransitGatewayConnectionPrefixFilterOptions *GetTransitGatewayConnectionPrefixFilterOptions) (result *PrefixFilterCust, response *core.DetailedResponse, err error) { return transitGatewayApis.GetTransitGatewayConnectionPrefixFilterWithContext(context.Background(), getTransitGatewayConnectionPrefixFilterOptions) } @@ -1883,7 +1891,7 @@ func (transitGatewayApis *TransitGatewayApisV1) UpdateTransitGatewayConnectionPr return } -// ListTransitGatewayRouteReports : List route reports +// ListTransitGatewayRouteReports : Lists route reports // Retrieve all route reports for the specified Transit Gateway. There will normally be at most one completed report // and one pending report. Additionally, completed route reports are written to IBM Cloud Activity Tracker. func (transitGatewayApis *TransitGatewayApisV1) ListTransitGatewayRouteReports(listTransitGatewayRouteReportsOptions *ListTransitGatewayRouteReportsOptions) (result *RouteReportCollection, response *core.DetailedResponse, err error) { @@ -1946,7 +1954,7 @@ func (transitGatewayApis *TransitGatewayApisV1) ListTransitGatewayRouteReportsWi return } -// CreateTransitGatewayRouteReport : Request a route report +// CreateTransitGatewayRouteReport : Requests a route report // Request route report generation. While report generation is in progress, additional requests to generate a report // are ignored and return the current pending report. func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayRouteReport(createTransitGatewayRouteReportOptions *CreateTransitGatewayRouteReportOptions) (result *RouteReport, response *core.DetailedResponse, err error) { @@ -2009,7 +2017,7 @@ func (transitGatewayApis *TransitGatewayApisV1) CreateTransitGatewayRouteReportW return } -// DeleteTransitGatewayRouteReport : Delete route report +// DeleteTransitGatewayRouteReport : Deletes a route report // Delete a route report. func (transitGatewayApis *TransitGatewayApisV1) DeleteTransitGatewayRouteReport(deleteTransitGatewayRouteReportOptions *DeleteTransitGatewayRouteReportOptions) (response *core.DetailedResponse, err error) { return transitGatewayApis.DeleteTransitGatewayRouteReportWithContext(context.Background(), deleteTransitGatewayRouteReportOptions) @@ -2060,7 +2068,7 @@ func (transitGatewayApis *TransitGatewayApisV1) DeleteTransitGatewayRouteReportW return } -// GetTransitGatewayRouteReport : Retrieve route report +// GetTransitGatewayRouteReport : Retrieves a route report // Retrieve a route report. func (transitGatewayApis *TransitGatewayApisV1) GetTransitGatewayRouteReport(getTransitGatewayRouteReportOptions *GetTransitGatewayRouteReportOptions) (result *RouteReport, response *core.DetailedResponse, err error) { return transitGatewayApis.GetTransitGatewayRouteReportWithContext(context.Background(), getTransitGatewayRouteReportOptions) @@ -2186,105 +2194,115 @@ type CreateTransitGatewayConnectionOptions struct { // Defines what type of network is connected via this connection. NetworkType *string `json:"network_type" validate:"required"` - // network_type 'gre_tunnel' connections must be created over an existing network_type 'classic' connection. This field - // must specify the ID of an active transit gateway network_type 'classic' connection in the same transit gateway. + // network_type `gre_tunnel` connections must be created over an existing network_type `classic` connection. This field + // must specify the ID of an active transit gateway network_type `classic` connection in the same transit gateway. // - // This field is required for network type 'gre_tunnel' connections. + // This field is required for network type `gre_tunnel` connections. // - // This field is required to be unspecified for network type 'classic', 'directlink', 'vpc', - // 'power_virtual_server', 'unbound_gre_tunnel' and 'redundant_gre' connections. + // This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, + // `power_virtual_server`, `unbound_gre_tunnel`, `vpn_gateway` and `redundant_gre` connections. // Deprecated: this field is deprecated and may be removed in a future release. BaseConnectionID *string `json:"base_connection_id,omitempty"` // The type of network the Unbound GRE tunnel is targeting. This field is required for network type - // 'unbound_gre_tunnel' and must be set to 'classic'. For a 'redundant_gre' network type, the value is required and - // can be either VPC or Classic. This field is required to be unspecified for network type 'classic', 'directlink', - // 'vpc', 'power_virtual_server' and 'gre_tunnel' connections. + // `unbound_gre_tunnel` and must be set to `classic`. For a `redundant_gre` network type, the value is required and + // can be either VPC or Classic. This field is required to be unspecified for network type `classic`, `directlink`, + // `vpc`, `power_virtual_server`, `vpn_gateway` and `gre_tunnel` connections. BaseNetworkType *string `json:"base_network_type,omitempty"` - // Local gateway IP address. This field is required for network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. - // This field is required to be unspecified for network type 'classic', 'directlink', 'vpc', 'power_virtual_server' and - // 'redundant_gre' connections. + // network_type 'vpn_gateway' connections use 'cidr' to specify the CIDR to use for the VPN GRE tunnels. + // + // This field is required for network type `vpn_gateway` connections. + // + // This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, `power_virtual_server`, + // `gre_tunnel`, `unbound_gre_tunnel`, and `redundant_gre` connections. + Cidr *string `json:"cidr,omitempty"` + + // Local gateway IP address. This field is required for network type `gre_tunnel` and `unbound_gre_tunnel` connections. + // This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, `power_virtual_server`, + // `vpn_gateway` and `redundant_gre` connections. LocalGatewayIp *string `json:"local_gateway_ip,omitempty"` // Local tunnel IP address. The local_tunnel_ip and remote_tunnel_ip addresses must be in the same /30 network. Neither // can be the network nor broadcast addresses. // - // This field is required for network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // This field is required for network type `gre_tunnel` and `unbound_gre_tunnel` connections. // - // This field is required to be unspecified for network type 'classic', 'directlink', 'vpc', 'power_virtual_server' and - // 'redundant_gre' connections. + // This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, `power_virtual_server`, + // `vpn_gateway` and `redundant_gre` connections. LocalTunnelIp *string `json:"local_tunnel_ip,omitempty"` - // The user-defined name for this transit gateway connection. Network type 'vpc' connections are defaulted to the name - // of the VPC. Network type 'classic' connections are named 'Classic'. + // The user-defined name for this transit gateway connection. Network type `vpc` connections are defaulted to the name + // of the VPC. Network type `classic` connections are named `classic`. // - // This field is required for network type 'gre_tunnel', 'unbound_gre_tunnel' and 'redundant_gre' connections. + // This field is required for network type `power_virtual_server`, `directlink`, `gre_tunnel`, `unbound_gre_tunnel`, + // `vpn_gateway` and `redundant_gre` connections. // - // This field is optional for network type 'classic', 'directlink', 'vpc' and 'power_virtual_server' connections. + // This field is optional for network type `classic`, `vpc` connections. Name *string `json:"name,omitempty"` // The ID of the account which owns the network that is being connected. Generally only used if the network is in a - // different account than the gateway. This field is required for type 'unbound_gre_tunnel' when the - // associated_network_type is 'classic' or network_type is 'redundant_gre' and the GRE tunnel is in a different account + // different account than the gateway. This field is required for type `unbound_gre_tunnel` when the + // associated_network_type is `classic` or network_type is `redundant_gre` and the GRE tunnel is in a different account // than the gateway. NetworkAccountID *string `json:"network_account_id,omitempty"` - // The ID of the network being connected via this connection. For network types 'vpc','power_virtual_server' and - // 'directlink' this is the CRN of the VPC / PowerVS / Direct Link gateway respectively. This field is required for - // network type 'vpc', 'power_virtual_server' and 'directlink' connections. It is also required for 'redundant_gre' - // connections when the base_network_type is set to VPC. This field is required to be unspecified for network type - // 'classic', 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // The ID of the network being connected via this connection. For network types `vpc`,`power_virtual_server`, + // `directlink` and `vpn_gateway` this is the CRN of the VPC / PowerVS / VDC / Direct Link / VPN gateway respectively. + // This field is required for network type `vpc`, `power_virtual_server`, `vpn_gateway`, and `directlink` connections. + // It is also required for `redundant_gre` connections when the base_network_type is set to VPC. This field is required + // to be unspecified for network type `classic`, `gre_tunnel` and `unbound_gre_tunnel` connections. NetworkID *string `json:"network_id,omitempty"` // Array of prefix route filters for a transit gateway connection. Prefix filters can be specified for netowrk type - // 'vpc', 'classic', 'power_virtual_server' and 'directlink' connections. They are not allowed for type 'gre_tunnel' + // `vpc`, `classic`, `power_virtual_server` and `directlink` connections. They are not allowed for type `gre_tunnel` // connections. This is order dependent with those first in the array being applied first, and those at the end of the - // array being applied last, or just before applying the default. This field is optional for network type 'classic', - // 'vpc', 'directlink', and 'power_virtual_server' connections. This field is required to be unspecified for network - // type 'gre_tunnel', 'unbound_gre_tunnel' and 'redundant_gre' connections. + // array being applied last, or just before applying the default. This field is optional for network type `classic`, + // `vpc`, `directlink`, and `power_virtual_server` connections. This field is required to be unspecified for network + // type `gre_tunnel`, `unbound_gre_tunnel`, `vpn_gateway` and `redundant_gre` connections. PrefixFilters []TransitGatewayConnectionPrefixFilter `json:"prefix_filters,omitempty"` // Default setting of permit or deny which applies to any routes that don't match a specified filter. This field is - // optional for network type 'classic', 'vpc', 'directlink', and 'power_virtual_server' connections. This field is - // required to be unspecified for network type 'gre_tunnel', 'unbound_gre_tunnel' and 'redundant_gre' connections. + // optional for network type `classic`, `vpc`, `directlink`, and `power_virtual_server` connections. This field is + // required to be unspecified for network type `gre_tunnel`, `unbound_gre_tunnel`, `vpn_gateway` and `redundant_gre` + // connections. PrefixFiltersDefault *string `json:"prefix_filters_default,omitempty"` // Remote network BGP ASN. The following ASN values are reserved and unavailable 0, 13884, 36351, 64512-64513, 65100, - // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If 'remote_bgp_asn' is omitted on gre_tunnel or + // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If `remote_bgp_asn` is omitted on gre_tunnel or // unbound_gre_tunnel connection create requests IBM will assign an ASN. // - // This field is optional for network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // This field is optional for network type `gre_tunnel` and `unbound_gre_tunnel` connections. // - // This field is required to be unspecified for network type 'classic', 'directlink', 'vpc', 'power_virtual_server' and - // 'gre_tunnel' connections. + // This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, `power_virtual_server`, + // `vpn_gateway` and `gre_tunnel` connections. RemoteBgpAsn *int64 `json:"remote_bgp_asn,omitempty"` - // Remote gateway IP address. This field is required for network type 'gre_tunnel' and 'unbound_gre_tunnel' - // connections. This field is required to be unspecified for network type 'classic', 'directlink', 'vpc', - // 'power_virtual_server' and 'redundant_gre' connections. + // Remote gateway IP address. This field is required for network type `gre_tunnel` and `unbound_gre_tunnel` + // connections. This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, + // `power_virtual_server`, `vpn_gateway` and `redundant_gre` connections. RemoteGatewayIp *string `json:"remote_gateway_ip,omitempty"` // Remote tunnel IP address. The local_tunnel_ip and remote_tunnel_ip addresses must be in the same /30 network. // Neither can be the network nor broadcast addresses. // - // This field is required for network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // This field is required for network type `gre_tunnel` and `unbound_gre_tunnel` connections. // - // This field is required to be unspecified for network type 'classic', 'directlink', 'vpc', 'power_virtual_server' - // and 'redundant_gre' connections. + // This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, `power_virtual_server`, + // `vpn_gateway` and `redundant_gre` connections. RemoteTunnelIp *string `json:"remote_tunnel_ip,omitempty"` - // Array of GRE tunnels for a transit gateway redundant GRE tunnel connection. This field is required for - // 'redundant_gre' connections. - Tunnels []TransitGatewayRedundantGRETunnelTemplate `json:"tunnels,omitempty"` + // Array of GRE tunnels for a transit gateway `redundant_gre` and `vpn_gateway` connections. This field is required + // for `redundant_gre` and `vpn_gateway` connections. + Tunnels []TransitGatewayTunnelTemplate `json:"tunnels,omitempty"` // Specify the connection's location. The specified availability zone must reside in the gateway's region. // Use the IBM Cloud global catalog to list zones within the desired region. // - // This field is required for network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // This field is required for network type `gre_tunnel`, `unbound_gre_tunnel` and `vpn_gateway` connections. // - // This field is required to be unspecified for network type 'classic', 'directlink', 'vpc', 'power_virtual_server' and - // 'redundant_gre' connections. + // This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, `power_virtual_server` and + // `redundant_gre` connections. Zone ZoneIdentityIntf `json:"zone,omitempty"` // Allows users to set headers on API requests @@ -2301,13 +2319,14 @@ const ( CreateTransitGatewayConnectionOptions_NetworkType_RedundantGre = "redundant_gre" CreateTransitGatewayConnectionOptions_NetworkType_UnboundGreTunnel = "unbound_gre_tunnel" CreateTransitGatewayConnectionOptions_NetworkType_Vpc = "vpc" + CreateTransitGatewayConnectionOptions_NetworkType_VpnGateway = "vpn_gateway" ) // Constants associated with the CreateTransitGatewayConnectionOptions.BaseNetworkType property. -// The type of network the Unbound GRE tunnel is targeting. This field is required for network type 'unbound_gre_tunnel' -// and must be set to 'classic'. For a 'redundant_gre' network type, the value is required and can be either VPC or -// Classic. This field is required to be unspecified for network type 'classic', 'directlink', 'vpc', -// 'power_virtual_server' and 'gre_tunnel' connections. +// The type of network the Unbound GRE tunnel is targeting. This field is required for network type `unbound_gre_tunnel` +// and must be set to `classic`. For a `redundant_gre` network type, the value is required and can be either VPC or +// Classic. This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, +// `power_virtual_server`, `vpn_gateway` and `gre_tunnel` connections. const ( CreateTransitGatewayConnectionOptions_BaseNetworkType_Classic = "classic" CreateTransitGatewayConnectionOptions_BaseNetworkType_Vpc = "vpc" @@ -2315,8 +2334,9 @@ const ( // Constants associated with the CreateTransitGatewayConnectionOptions.PrefixFiltersDefault property. // Default setting of permit or deny which applies to any routes that don't match a specified filter. This field is -// optional for network type 'classic', 'vpc', 'directlink', and 'power_virtual_server' connections. This field is -// required to be unspecified for network type 'gre_tunnel', 'unbound_gre_tunnel' and 'redundant_gre' connections. +// optional for network type `classic`, `vpc`, `directlink`, and `power_virtual_server` connections. This field is +// required to be unspecified for network type `gre_tunnel`, `unbound_gre_tunnel`, `vpn_gateway` and `redundant_gre` +// connections. const ( CreateTransitGatewayConnectionOptions_PrefixFiltersDefault_Deny = "deny" CreateTransitGatewayConnectionOptions_PrefixFiltersDefault_Permit = "permit" @@ -2355,6 +2375,12 @@ func (_options *CreateTransitGatewayConnectionOptions) SetBaseNetworkType(baseNe return _options } +// SetCidr : Allow user to set Cidr +func (_options *CreateTransitGatewayConnectionOptions) SetCidr(cidr string) *CreateTransitGatewayConnectionOptions { + _options.Cidr = core.StringPtr(cidr) + return _options +} + // SetLocalGatewayIp : Allow user to set LocalGatewayIp func (_options *CreateTransitGatewayConnectionOptions) SetLocalGatewayIp(localGatewayIp string) *CreateTransitGatewayConnectionOptions { _options.LocalGatewayIp = core.StringPtr(localGatewayIp) @@ -2416,7 +2442,7 @@ func (_options *CreateTransitGatewayConnectionOptions) SetRemoteTunnelIp(remoteT } // SetTunnels : Allow user to set Tunnels -func (_options *CreateTransitGatewayConnectionOptions) SetTunnels(tunnels []TransitGatewayRedundantGRETunnelTemplate) *CreateTransitGatewayConnectionOptions { +func (_options *CreateTransitGatewayConnectionOptions) SetTunnels(tunnels []TransitGatewayTunnelTemplate) *CreateTransitGatewayConnectionOptions { _options.Tunnels = tunnels return _options } @@ -2444,10 +2470,10 @@ type CreateTransitGatewayConnectionPrefixFilterOptions struct { // Whether or not this prefix filter should allow or deny prefixes matching this filter's prefix definition. Action *string `json:"action" validate:"required"` - // The IPv4 Prefix to be matched by this filter. If both the 'le' and 'ge' are zero, then this filter will only apply - // to routes that exactly match this prefix, while a non-zero value for either 'le' or 'ge', this filter can apply to + // The IPv4 Prefix to be matched by this filter. If both the `le` and `ge` are zero, then this filter will only apply + // to routes that exactly match this prefix, while a non-zero value for either `le` or `ge`, this filter can apply to // multiple routes with different prefix lengths, but will still only apply to prefixes contained in the address space - // defined by 'prefix'. + // defined by `prefix`. Prefix *string `json:"prefix" validate:"required"` // A reference to the prefix filter that will be the next filter applied to the Transit Gateway connection. @@ -2459,20 +2485,20 @@ type CreateTransitGatewayConnectionPrefixFilterOptions struct { Before *string `json:"before,omitempty"` // Defines the minimum matched prefix precision. If this field is non-zero then the filter will match all routes within - // the 'prefix' that have a prefix length greater than or equal to this value. + // the `prefix` that have a prefix length greater than or equal to this value. // // This value can be zero, or a non-negative number greater than or equal to the prefix length of the filter's prefix - // or less then or equal to 32. If this value is set to zero, the filter will not use the 'ge' route matching behavior. - // If the 'le' value is non-zero the the 'ge' value must between the prefix length and the - // 'le' value, inclusive. + // or less then or equal to 32. If this value is set to zero, the filter will not use the `ge` route matching behavior. + // If the `le` value is non-zero the the `ge` value must between the prefix length and the + // `le` value, inclusive. Ge *int64 `json:"ge,omitempty"` // Defines the maximum matched prefix precision. If this field is non-zero then the filter will match all routes within - // the 'prefix' that have a prefix length less than or equal to this value. + // the `prefix` that have a prefix length less than or equal to this value. // // This value can be zero, or a non-negative number greater than or equal to the prefix length of the filter's prefix - // or less then or equal to 32. If this value is set to zero, the filter will not use the 'le' route matching behavior. - // If the 'ge' value is non-zero the the 'le' value must between the 'ge' value and 32, inclusive. + // or less then or equal to 32. If this value is set to zero, the filter will not use the `le` route matching behavior. + // If the `ge` value is non-zero the the `le` value must between the `ge` value and 32, inclusive. Le *int64 `json:"le,omitempty"` // Allows users to set headers on API requests @@ -2574,7 +2600,7 @@ type CreateTransitGatewayGreTunnelOptions struct { Zone ZoneIdentityIntf `json:"zone" validate:"required"` // Remote network BGP ASN. The following ASN values are reserved and unavailable 0, 13884, 36351, 64512-64513, 65100, - // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If 'remote_bgp_asn' is omitted on create requests, IBM + // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If `remote_bgp_asn` is omitted on create requests, IBM // will assign an ASN. RemoteBgpAsn *int64 `json:"remote_bgp_asn,omitempty"` @@ -2661,12 +2687,15 @@ type CreateTransitGatewayOptions struct { // Location of Transit Gateway Services. Location *string `json:"location" validate:"required"` - // Name Transit Gateway Services. + // A human readable name for the transit gateway. Name *string `json:"name" validate:"required"` // Allow global routing for a Transit Gateway. If unspecified, the default value is false. Global *bool `json:"global,omitempty"` + // Allow GRE Enhanced Route Propagation on this gateway. + GreEnhancedRoutePropagation *bool `json:"gre_enhanced_route_propagation,omitempty"` + // The resource group to use. If unspecified, the account's [default resource // group](https://console.bluemix.net/apidocs/resource-manager#introduction) is used. ResourceGroup *ResourceGroupIdentity `json:"resource_group,omitempty"` @@ -2701,6 +2730,12 @@ func (_options *CreateTransitGatewayOptions) SetGlobal(global bool) *CreateTrans return _options } +// SetGreEnhancedRoutePropagation : Allow user to set GreEnhancedRoutePropagation +func (_options *CreateTransitGatewayOptions) SetGreEnhancedRoutePropagation(greEnhancedRoutePropagation bool) *CreateTransitGatewayOptions { + _options.GreEnhancedRoutePropagation = core.BoolPtr(greEnhancedRoutePropagation) + return _options +} + // SetResourceGroup : Allow user to set ResourceGroup func (_options *CreateTransitGatewayOptions) SetResourceGroup(resourceGroup *ResourceGroupIdentity) *CreateTransitGatewayOptions { _options.ResourceGroup = resourceGroup @@ -3103,44 +3138,6 @@ func (options *GetTransitGatewayConnectionTunnelsOptions) SetHeaders(param map[s return options } -// GetTransitGatewayGreTunnelOptions : The GetTransitGatewayGreTunnel options. -type GetTransitGatewayGreTunnelOptions struct { - // The Transit Gateway identifier. - TransitGatewayID *string `json:"transit_gateway_id" validate:"required,ne="` - - // The connection identifier. - ID *string `json:"id" validate:"required,ne="` - - // Allows users to set headers on API requests - Headers map[string]string -} - -// NewGetTransitGatewayGreTunnelOptions : Instantiate GetTransitGatewayGreTunnelOptions -func (*TransitGatewayApisV1) NewGetTransitGatewayGreTunnelOptions(transitGatewayID string, id string) *GetTransitGatewayGreTunnelOptions { - return &GetTransitGatewayGreTunnelOptions{ - TransitGatewayID: core.StringPtr(transitGatewayID), - ID: core.StringPtr(id), - } -} - -// SetTransitGatewayID : Allow user to set TransitGatewayID -func (_options *GetTransitGatewayGreTunnelOptions) SetTransitGatewayID(transitGatewayID string) *GetTransitGatewayGreTunnelOptions { - _options.TransitGatewayID = core.StringPtr(transitGatewayID) - return _options -} - -// SetID : Allow user to set ID -func (_options *GetTransitGatewayGreTunnelOptions) SetID(id string) *GetTransitGatewayGreTunnelOptions { - _options.ID = core.StringPtr(id) - return _options -} - -// SetHeaders : Allow user to set Headers -func (options *GetTransitGatewayGreTunnelOptions) SetHeaders(param map[string]string) *GetTransitGatewayGreTunnelOptions { - options.Headers = param - return options -} - // GetTransitGatewayOptions : The GetTransitGateway options. type GetTransitGatewayOptions struct { // The Transit Gateway identifier. @@ -3207,23 +3204,6 @@ func (options *GetTransitGatewayRouteReportOptions) SetHeaders(param map[string] return options } -// GreTunnelZoneReference : Location of GRE tunnel. This field only applies to network type 'gre_tunnel' connections. -type GreTunnelZoneReference struct { - // Availability zone name. - Name *string `json:"name" validate:"required"` -} - -// UnmarshalGreTunnelZoneReference unmarshals an instance of GreTunnelZoneReference from the specified map of raw messages. -func UnmarshalGreTunnelZoneReference(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(GreTunnelZoneReference) - err = core.UnmarshalPrimitive(m, "name", &obj.Name) - if err != nil { - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - // ListConnectionsOptions : The ListConnections options. type ListConnectionsOptions struct { // The maximum number of resources to return per page. @@ -3235,6 +3215,9 @@ type ListConnectionsOptions struct { // Search for connections with the given network_id value. NetworkID *string `json:"network_id,omitempty"` + // Search for connections with the given network_type value. + NetworkType *string `json:"network_type,omitempty"` + // Allows users to set headers on API requests Headers map[string]string } @@ -3262,6 +3245,12 @@ func (_options *ListConnectionsOptions) SetNetworkID(networkID string) *ListConn return _options } +// SetNetworkType : Allow user to set NetworkType +func (_options *ListConnectionsOptions) SetNetworkType(networkType string) *ListConnectionsOptions { + _options.NetworkType = core.StringPtr(networkType) + return _options +} + // SetHeaders : Allow user to set Headers func (options *ListConnectionsOptions) SetHeaders(param map[string]string) *ListConnectionsOptions { options.Headers = param @@ -3379,6 +3368,44 @@ func (options *ListTransitGatewayConnectionsOptions) SetHeaders(param map[string return options } +// ListTransitGatewayGreTunnelOptions : The ListTransitGatewayGreTunnel options. +type ListTransitGatewayGreTunnelOptions struct { + // The Transit Gateway identifier. + TransitGatewayID *string `json:"transit_gateway_id" validate:"required,ne="` + + // The connection identifier. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewListTransitGatewayGreTunnelOptions : Instantiate ListTransitGatewayGreTunnelOptions +func (*TransitGatewayApisV1) NewListTransitGatewayGreTunnelOptions(transitGatewayID string, id string) *ListTransitGatewayGreTunnelOptions { + return &ListTransitGatewayGreTunnelOptions{ + TransitGatewayID: core.StringPtr(transitGatewayID), + ID: core.StringPtr(id), + } +} + +// SetTransitGatewayID : Allow user to set TransitGatewayID +func (_options *ListTransitGatewayGreTunnelOptions) SetTransitGatewayID(transitGatewayID string) *ListTransitGatewayGreTunnelOptions { + _options.TransitGatewayID = core.StringPtr(transitGatewayID) + return _options +} + +// SetID : Allow user to set ID +func (_options *ListTransitGatewayGreTunnelOptions) SetID(id string) *ListTransitGatewayGreTunnelOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *ListTransitGatewayGreTunnelOptions) SetHeaders(param map[string]string) *ListTransitGatewayGreTunnelOptions { + options.Headers = param + return options +} + // ListTransitGatewayRouteReportsOptions : The ListTransitGatewayRouteReports options. type ListTransitGatewayRouteReportsOptions struct { // The Transit Gateway identifier. @@ -3600,29 +3627,29 @@ type PrefixFilterCust struct { CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` // Defines the minimum matched prefix precision. If this field is non-zero then the filter will match all routes within - // the 'prefix' that have a prefix length greater or equal to this value. + // the `prefix` that have a prefix length greater or equal to this value. // // This value can be zero, or a non-negative number greater than or equal to the prefix length of the filter's prefix - // or less then or equal to 32. If this value is set to zero, the filter will not use the 'ge' route matching behavior. - // If the 'le' value is non-zero the the 'ge' value must between the prefix length and the - // 'le' value, inclusive. + // or less then or equal to 32. If this value is set to zero, the filter will not use the `ge` route matching behavior. + // If the `le` value is non-zero the the `ge` value must between the prefix length and the + // `le` value, inclusive. Ge *int64 `json:"ge,omitempty"` // Prefix Filter identifier. ID *string `json:"id" validate:"required"` // Defines the maximum matched prefix precision. If this field is non-zero then the filter will match all routes within - // the 'prefix' that have a prefix length less than or equal to this value. + // the `prefix` that have a prefix length less than or equal to this value. // // This value can be zero, or a non-negative number greater than or equal to the prefix length of the filter's prefix - // or less then or equal to 32. If this value is set to zero, the filter will not use the 'le' route matching behavior. - // If the 'ge' value is non-zero the the 'le' value must between the 'ge' value and 32, inclusive. + // or less then or equal to 32. If this value is set to zero, the filter will not use the `le` route matching behavior. + // If the `ge` value is non-zero the the `le` value must between the `ge` value and 32, inclusive. Le *int64 `json:"le,omitempty"` - // The IPv4 Prefix to be matched by this filter. If both the 'le' and 'ge' are zero, then this filter will only apply - // to routes that exactly match this prefix, while a non-zero value for either 'le' or 'ge', this filter can apply to + // The IPv4 Prefix to be matched by this filter. If both the `le` and `ge` are zero, then this filter will only apply + // to routes that exactly match this prefix, while a non-zero value for either `le` or `ge`, this filter can apply to // multiple routes with different prefix lengths, but will still only apply to prefixes contained in the address space - // defined by 'prefix'. + // defined by `prefix`. Prefix *string `json:"prefix" validate:"required"` // The date and time that this prefix filter was last updated. @@ -3681,26 +3708,26 @@ type PrefixFilterPut struct { Action *string `json:"action" validate:"required"` // Defines the minimum matched prefix precision. If this field is non-zero then the filter will match all routes within - // the 'prefix' that have a prefix length greater or equal to this value. + // the `prefix` that have a prefix length greater or equal to this value. // // This value can be zero, or a non-negative number greater than or equal to the prefix length of the filter's prefix - // or less then or equal to 32. If this value is set to zero, the filter will not use the 'ge' route matching behavior. - // If the 'le' value is non-zero the the 'ge' value must between the prefix length and the - // 'le' value, inclusive. + // or less then or equal to 32. If this value is set to zero, the filter will not use the `ge` route matching behavior. + // If the `le` value is non-zero the the `ge` value must between the prefix length and the + // `le` value, inclusive. Ge *int64 `json:"ge,omitempty"` // Defines the maximum matched prefix precision. If this field is non-zero then the filter will match all routes within - // the 'prefix' that have a prefix length less than or equal to this value. + // the `prefix` that have a prefix length less than or equal to this value. // // This value can be zero, or a non-negative number greater than or equal to the prefix length of the filter's prefix - // or less then or equal to 32. If this value is set to zero, the filter will not use the 'le' route matching behavior. - // If the 'ge' value is non-zero the the 'le' value must between the 'ge' value and 32, inclusive. + // or less then or equal to 32. If this value is set to zero, the filter will not use the `le` route matching behavior. + // If the `ge` value is non-zero the the `le` value must between the `ge` value and 32, inclusive. Le *int64 `json:"le,omitempty"` - // The IPv4 Prefix to be matched by this filter. If both the 'le' and 'ge' are zero, then this filter will only apply - // to routes that exactly match this prefix, while a non-zero value for either 'le' or 'ge', this filter can apply to + // The IPv4 Prefix to be matched by this filter. If both the `le` and `ge` are zero, then this filter will only apply + // to routes that exactly match this prefix, while a non-zero value for either `le` or `ge`, this filter can apply to // multiple routes with different prefix lengths, but will still only apply to prefixes contained in the address space - // defined by 'prefix'. + // defined by `prefix`. Prefix *string `json:"prefix" validate:"required"` } @@ -3744,173 +3771,6 @@ func UnmarshalPrefixFilterPut(m map[string]json.RawMessage, result interface{}) return } -// RedundantGRETunnelCollection : Collection of all tunnels for redundant gre connection. -type RedundantGRETunnelCollection struct { - // Collection of all tunnels for redundant gre connection. - Tunnels []RedundantGRETunnelReference `json:"tunnels" validate:"required"` -} - -// UnmarshalRedundantGRETunnelCollection unmarshals an instance of RedundantGRETunnelCollection from the specified map of raw messages. -func UnmarshalRedundantGRETunnelCollection(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(RedundantGRETunnelCollection) - err = core.UnmarshalModel(m, "tunnels", &obj.Tunnels, UnmarshalRedundantGRETunnelReference) - if err != nil { - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - -// RedundantGRETunnelReference : Details for a redundant GRE tunnel. -type RedundantGRETunnelReference struct { - // The type of network the redundant GRE tunnel is targeting. - BaseNetworkType *string `json:"base_network_type" validate:"required"` - - // The date and time that this GRE tunnel was created. - CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` - - // The unique identifier for this redundant GRE tunnel. - ID *string `json:"id" validate:"required"` - - // Local network BGP ASN. It is assigned by IBM when the tunnel is created. - LocalBgpAsn *int64 `json:"local_bgp_asn" validate:"required"` - - // Local gateway IP address. - LocalGatewayIp *string `json:"local_gateway_ip" validate:"required"` - - // Local tunnel IP address. The local_tunnel_ip and remote_tunnel_ip addresses must be in the same /30 network. Neither - // can be the network nor broadcast addresses. - LocalTunnelIp *string `json:"local_tunnel_ip" validate:"required"` - - // GRE tunnel MTU. - Mtu *int64 `json:"mtu" validate:"required"` - - // The user-defined name for this tunnel. - Name *string `json:"name" validate:"required"` - - // The ID of the account for cross account Classic connections. This field is required when the GRE tunnel is in a - // different account than the gateway and the base network is Classic. - NetworkAccountID *string `json:"network_account_id,omitempty"` - - // The ID of the network VPC being connected via this connection. - NetworkID *string `json:"network_id,omitempty"` - - // Remote network BGP ASN. The following ASN values are reserved and unavailable 0, 13884, 36351, 64512-64513, 65100, - // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If 'remote_bgp_asn' is omitted on create requests, IBM - // will assign an ASN. - RemoteBgpAsn *int64 `json:"remote_bgp_asn" validate:"required"` - - // Remote gateway IP address. - RemoteGatewayIp *string `json:"remote_gateway_ip" validate:"required"` - - // Remote tunnel IP address. The local_tunnel_ip and remote_tunnel_ip addresses must be in the same /30 network. - // Neither can be the network nor broadcast addresses. - RemoteTunnelIp *string `json:"remote_tunnel_ip" validate:"required"` - - // Tunnel's current configuration state. The list of enumerated values for this property may expand in the future. Code - // and processes using this field must tolerate unexpected values. - Status *string `json:"status" validate:"required"` - - // The date and time that this tunnel was last updated. - UpdatedAt *strfmt.DateTime `json:"updated_at" validate:"required"` - - // The tunnel's location. The specified availability zone must reside in the gateway's region. Use the IBM Cloud - // global catalog to list zones within the desired region. - Zone *RgreTunnelZoneReference `json:"zone" validate:"required"` -} - -// Constants associated with the RedundantGRETunnelReference.BaseNetworkType property. -// The type of network the redundant GRE tunnel is targeting. -const ( - RedundantGRETunnelReference_BaseNetworkType_Classic = "classic" - RedundantGRETunnelReference_BaseNetworkType_Vpc = "vpc" -) - -// Constants associated with the RedundantGRETunnelReference.Status property. -// Tunnel's current configuration state. The list of enumerated values for this property may expand in the future. Code -// and processes using this field must tolerate unexpected values. -const ( - RedundantGRETunnelReference_Status_Attached = "attached" - RedundantGRETunnelReference_Status_Deleting = "deleting" - RedundantGRETunnelReference_Status_Detached = "detached" - RedundantGRETunnelReference_Status_Detaching = "detaching" - RedundantGRETunnelReference_Status_Failed = "failed" - RedundantGRETunnelReference_Status_Pending = "pending" - RedundantGRETunnelReference_Status_Suspended = "suspended" - RedundantGRETunnelReference_Status_Suspending = "suspending" -) - -// UnmarshalRedundantGRETunnelReference unmarshals an instance of RedundantGRETunnelReference from the specified map of raw messages. -func UnmarshalRedundantGRETunnelReference(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(RedundantGRETunnelReference) - err = core.UnmarshalPrimitive(m, "base_network_type", &obj.BaseNetworkType) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "id", &obj.ID) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "local_bgp_asn", &obj.LocalBgpAsn) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "local_gateway_ip", &obj.LocalGatewayIp) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "local_tunnel_ip", &obj.LocalTunnelIp) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "mtu", &obj.Mtu) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "name", &obj.Name) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "network_account_id", &obj.NetworkAccountID) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "network_id", &obj.NetworkID) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "remote_bgp_asn", &obj.RemoteBgpAsn) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "remote_gateway_ip", &obj.RemoteGatewayIp) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "remote_tunnel_ip", &obj.RemoteTunnelIp) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "status", &obj.Status) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "updated_at", &obj.UpdatedAt) - if err != nil { - return - } - err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalRgreTunnelZoneReference) - if err != nil { - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - // ReplaceTransitGatewayConnectionPrefixFilterOptions : The ReplaceTransitGatewayConnectionPrefixFilter options. type ReplaceTransitGatewayConnectionPrefixFilterOptions struct { // The Transit Gateway identifier. @@ -4011,24 +3871,6 @@ func UnmarshalResourceGroupReference(m map[string]json.RawMessage, result interf return } -// RgreTunnelZoneReference : The tunnel's location. The specified availability zone must reside in the gateway's region. Use the IBM Cloud global -// catalog to list zones within the desired region. -type RgreTunnelZoneReference struct { - // Availability zone name. - Name *string `json:"name" validate:"required"` -} - -// UnmarshalRgreTunnelZoneReference unmarshals an instance of RgreTunnelZoneReference from the specified map of raw messages. -func UnmarshalRgreTunnelZoneReference(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(RgreTunnelZoneReference) - err = core.UnmarshalPrimitive(m, "name", &obj.Name) - if err != nil { - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - // RouteReport : route report. type RouteReport struct { // Array of connections with their routes. @@ -4056,6 +3898,7 @@ type RouteReport struct { // using this field must tolerate unexpected values. const ( RouteReport_Status_Complete = "complete" + RouteReport_Status_Failed = "failed" RouteReport_Status_Pending = "pending" ) @@ -4329,7 +4172,7 @@ type TSLocation struct { LocalConnectionLocations []TSLocalLocation `json:"local_connection_locations" validate:"required"` // List of valid zones for GRE tunnels. - Zones []ZoneReferenceCollection `json:"zones" validate:"required"` + Zones []ZoneReference `json:"zones" validate:"required"` } // UnmarshalTSLocation unmarshals an instance of TSLocation from the specified map of raw messages. @@ -4351,7 +4194,7 @@ func UnmarshalTSLocation(m map[string]json.RawMessage, result interface{}) (err if err != nil { return } - err = core.UnmarshalModel(m, "zones", &obj.Zones, UnmarshalZoneReferenceCollection) + err = core.UnmarshalModel(m, "zones", &obj.Zones, UnmarshalZoneReference) if err != nil { return } @@ -4398,39 +4241,40 @@ type TransitConnection struct { // The user-defined name for this transit gateway connection. Name *string `json:"name" validate:"required"` - // The ID of the network being connected via this connection. This field is required for some types, such as 'vpc', - // 'power_virtual_server', 'directlink' and 'redundant_gre'. For network types 'vpc', 'redundant_gre', - // 'power_virtual_server' and 'directlink' this is the CRN of the VPC / PowerVS / Direct Link gateway respectively. + // The ID of the network being connected via this connection. This field is required for some types, such as `vpc`, + // `power_virtual_server`, `directlink`, `vpn_gateway` and `redundant_gre`. For network types `vpc`, `redundant_gre`, + // `power_virtual_server` and `directlink` this is the CRN of the VPC / PowerVS / VDC / Direct Link gateway + // respectively. NetworkID *string `json:"network_id,omitempty"` // Defines what type of network is connected via this connection. The list of enumerated values for this property may // expand in the future. Code and processes using this field must tolerate unexpected values. NetworkType *string `json:"network_type" validate:"required"` - // The unique identifier for this Transit Gateway Connection. + // The unique identifier for this Transit Gateway connection. ID *string `json:"id" validate:"required"` - // network_type 'gre_tunnel' connections use 'base_connection_id' to specify the ID of a network_type 'classic' + // network_type `gre_tunnel` connections use `base_connection_id` to specify the ID of a network_type `classic` // connection the tunnel is configured over. The specified connection must reside in the same transit gateway and be in - // an active state. The 'classic' connection cannot be deleted until any 'gre_tunnel' connections using it are deleted. - // This field only applies to and is required for network type 'gre_tunnel' connections. + // an active state. The `classic` connection cannot be deleted until any `gre_tunnel` connections using it are deleted. + // This field only applies to and is required for network type `gre_tunnel` connections. // Deprecated: this field is deprecated and may be removed in a future release. BaseConnectionID *string `json:"base_connection_id,omitempty"` // The date and time that this connection was created. CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` - // Local network BGP ASN. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // Local network BGP ASN. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` connections. LocalBgpAsn *int64 `json:"local_bgp_asn,omitempty"` - // Local gateway IP address. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' + // Local gateway IP address. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` // connections. LocalGatewayIp *string `json:"local_gateway_ip,omitempty"` - // Local tunnel IP address. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // Local tunnel IP address. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` connections. LocalTunnelIp *string `json:"local_tunnel_ip,omitempty"` - // GRE tunnel MTU. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // GRE tunnel MTU. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` connections. Mtu *int64 `json:"mtu,omitempty"` // The ID of the account which owns the connected network. Generally only used if the network is in a different IBM @@ -4440,22 +4284,22 @@ type TransitConnection struct { // Array of prefix route filters for a transit gateway connection. This is order dependent with those first in the // array being applied first, and those at the end of the array is applied last, or just before the default. // - // This field does not apply to the 'redundant_gre' network type. + // This field does not apply to the `redundant_gre` network types. PrefixFilters []TransitGatewayConnectionPrefixFilterReference `json:"prefix_filters,omitempty"` // Default setting of permit or deny which applies to any routes that don't match a specified filter. // - // This field does not apply to the 'redundant_gre' network type. + // This field does not apply to the `redundant_gre` network types. PrefixFiltersDefault *string `json:"prefix_filters_default,omitempty"` - // Remote network BGP ASN. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // Remote network BGP ASN. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` connections. RemoteBgpAsn *int64 `json:"remote_bgp_asn,omitempty"` - // Remote gateway IP address. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' + // Remote gateway IP address. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` // connections. RemoteGatewayIp *string `json:"remote_gateway_ip,omitempty"` - // Remote tunnel IP address. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' + // Remote tunnel IP address. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` // connections. RemoteTunnelIp *string `json:"remote_tunnel_ip,omitempty"` @@ -4471,14 +4315,14 @@ type TransitConnection struct { // Transit gateway reference. TransitGateway *TransitGatewayReference `json:"transit_gateway" validate:"required"` - // Collection of all tunnels for 'redundant_gre' connection. - Tunnels []TransitGatewayRedundantGRETunnelReference `json:"tunnels,omitempty"` + // Collection of all tunnels for `redundant_gre` and `vpn_gateway` connections. + Tunnels []TransitGatewayTunnel `json:"tunnels,omitempty"` // The date and time that this connection was last updated. UpdatedAt *strfmt.DateTime `json:"updated_at" validate:"required"` - // Location of GRE tunnel. This field only applies to network type 'gre_tunnel' connections. - Zone *GreTunnelZoneReference `json:"zone,omitempty"` + // Availability zone reference. + Zone *ZoneReference `json:"zone,omitempty"` } // Constants associated with the TransitConnection.BaseNetworkType property. @@ -4499,12 +4343,13 @@ const ( TransitConnection_NetworkType_RedundantGre = "redundant_gre" TransitConnection_NetworkType_UnboundGreTunnel = "unbound_gre_tunnel" TransitConnection_NetworkType_Vpc = "vpc" + TransitConnection_NetworkType_VpnGateway = "vpn_gateway" ) // Constants associated with the TransitConnection.PrefixFiltersDefault property. // Default setting of permit or deny which applies to any routes that don't match a specified filter. // -// This field does not apply to the 'redundant_gre' network type. +// This field does not apply to the `redundant_gre` network types. const ( TransitConnection_PrefixFiltersDefault_Deny = "deny" TransitConnection_PrefixFiltersDefault_Permit = "permit" @@ -4620,7 +4465,7 @@ func UnmarshalTransitConnection(m map[string]json.RawMessage, result interface{} if err != nil { return } - err = core.UnmarshalModel(m, "tunnels", &obj.Tunnels, UnmarshalTransitGatewayRedundantGRETunnelReference) + err = core.UnmarshalModel(m, "tunnels", &obj.Tunnels, UnmarshalTransitGatewayTunnel) if err != nil { return } @@ -4628,7 +4473,7 @@ func UnmarshalTransitConnection(m map[string]json.RawMessage, result interface{} if err != nil { return } - err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalGreTunnelZoneReference) + err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalZoneReference) if err != nil { return } @@ -4684,24 +4529,33 @@ func (resp *TransitConnectionCollection) GetNextStart() (*string, error) { // TransitGateway : Details of a Transit Gateway. type TransitGateway struct { - // The unique identifier for this Transit Gateway. - ID *string `json:"id" validate:"required"` - - // The CRN for this Transit Gateway. - Crn *string `json:"crn" validate:"required"` - - // A human readable name for the transit gateway. - Name *string `json:"name" validate:"required"` + // The number of connections associated with this Transit Gateway. + ConnectionCount *int64 `json:"connection_count,omitempty"` - // Location of Transit Gateway Services. - Location *string `json:"location" validate:"required"` + // Indicates if this Transit Gateway has a connection that needs attention (Such as cross account approval). + ConnectionNeedsAttention *bool `json:"connection_needs_attention,omitempty"` // The date and time that this gateway was created. CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` + // Cloud Resource Name of a transit gateway. + Crn *string `json:"crn,omitempty"` + // Allow global routing for a Transit Gateway. Global *bool `json:"global" validate:"required"` + // Allow GRE Enhanced Route Propagation on this gateway. + GreEnhancedRoutePropagation *bool `json:"gre_enhanced_route_propagation,omitempty"` + + // A unique identifier for this transit gateway. + ID *string `json:"id" validate:"required"` + + // Location of Transit Gateway Services. + Location *string `json:"location" validate:"required"` + + // A human readable name for the transit gateway. + Name *string `json:"name" validate:"required"` + // The resource group to use. If unspecified, the account's [default resource // group](https://console.bluemix.net/apidocs/resource-manager#introduction) is used. ResourceGroup *ResourceGroupReference `json:"resource_group,omitempty"` @@ -4729,7 +4583,15 @@ const ( // UnmarshalTransitGateway unmarshals an instance of TransitGateway from the specified map of raw messages. func UnmarshalTransitGateway(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(TransitGateway) - err = core.UnmarshalPrimitive(m, "id", &obj.ID) + err = core.UnmarshalPrimitive(m, "connection_count", &obj.ConnectionCount) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "connection_needs_attention", &obj.ConnectionNeedsAttention) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) if err != nil { return } @@ -4737,19 +4599,23 @@ func UnmarshalTransitGateway(m map[string]json.RawMessage, result interface{}) ( if err != nil { return } - err = core.UnmarshalPrimitive(m, "name", &obj.Name) + err = core.UnmarshalPrimitive(m, "global", &obj.Global) if err != nil { return } - err = core.UnmarshalPrimitive(m, "location", &obj.Location) + err = core.UnmarshalPrimitive(m, "gre_enhanced_route_propagation", &obj.GreEnhancedRoutePropagation) if err != nil { return } - err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) if err != nil { return } - err = core.UnmarshalPrimitive(m, "global", &obj.Global) + err = core.UnmarshalPrimitive(m, "location", &obj.Location) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } @@ -4872,68 +4738,81 @@ func (resp *TransitGatewayConnectionCollection) GetNextStart() (*string, error) // TransitGatewayConnectionCust : Connection included in transit gateway. type TransitGatewayConnectionCust struct { - // The type of network the GRE tunnel is targeting. - BaseNetworkType *string `json:"base_network_type,omitempty"` - - // The user-defined name for this transit gateway connection. - Name *string `json:"name" validate:"required"` - - // The ID of the network being connected via this connection. This field is required for some types, such as 'vpc', - // 'power_virtual_server', 'directlink' and 'redundant_gre'. For network types 'vpc', 'redundant_gre', - // 'power_virtual_server' and 'directlink' this is the CRN of the VPC / PowerVS / Direct Link gateway respectively. - NetworkID *string `json:"network_id,omitempty"` - - // Defines what type of network is connected via this connection. The list of enumerated values for this property may - // expand in the future. Code and processes using this field must tolerate unexpected values. - NetworkType *string `json:"network_type" validate:"required"` - - // The unique identifier for this Transit Gateway Connection. - ID *string `json:"id" validate:"required"` - - // network_type 'gre_tunnel' connections use 'base_connection_id' to specify the ID of a network_type 'classic' + // network_type `gre_tunnel` connections use `base_connection_id` to specify the ID of a network_type `classic` // connection the tunnel is configured over. The specified connection must reside in the same transit gateway and be in - // an active state. The 'classic' connection cannot be deleted until any 'gre_tunnel' connections using it are deleted. - // This field only applies to and is required for network type 'gre_tunnel' connections. + // an active state. The `classic` connection cannot be deleted until any `gre_tunnel` connections using it are deleted. + // This field only applies to and is required for network type `gre_tunnel` connections. // Deprecated: this field is deprecated and may be removed in a future release. BaseConnectionID *string `json:"base_connection_id,omitempty"` + // The type of network the Unbound GRE tunnel is targeting. This field is required for network type + // `unbound_gre_tunnel` and must be set to `classic`. For a `redundant_gre` network type, the value is required and + // can be either VPC or Classic. This field is required to be unspecified for network type `classic`, `directlink`, + // `vpc`, `power_virtual_server`, `vpn_gateway` and `gre_tunnel` connections. + BaseNetworkType *string `json:"base_network_type,omitempty"` + + // network_type 'vpn_gateway' connections use 'cidr' to specify the CIDR to use for the VPN GRE tunnels. + Cidr *string `json:"cidr,omitempty"` + // The date and time that this connection was created. CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` - // Local network BGP ASN. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // The unique identifier for this Transit Gateway connection. + ID *string `json:"id" validate:"required"` + + // Local network BGP ASN. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` connections. LocalBgpAsn *int64 `json:"local_bgp_asn,omitempty"` - // Local gateway IP address. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' + // Local gateway IP address. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` // connections. LocalGatewayIp *string `json:"local_gateway_ip,omitempty"` - // Local tunnel IP address. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // Local tunnel IP address. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` connections. LocalTunnelIp *string `json:"local_tunnel_ip,omitempty"` - // GRE tunnel MTU. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // GRE tunnel MTU. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` connections. Mtu *int64 `json:"mtu,omitempty"` + // The user-defined name for this transit gateway connection. Network type `vpc` connections are defaulted to the name + // of the VPC. Network type `classic` connections are named `classic`. + // + // This field is required for network type `power_virtual_server`, `directlink`, `gre_tunnel`, `unbound_gre_tunnel`, + // `vpn_gateway` and `redundant_gre` connections. + // + // This field is optional for network type `classic`, `vpc` connections. + Name *string `json:"name,omitempty"` + // The ID of the account which owns the connected network. Generally only used if the network is in a different IBM // Cloud account than the gateway. NetworkAccountID *string `json:"network_account_id,omitempty"` + // The ID of the network being connected via this connection. For network types `vpc`,`power_virtual_server`, + // `directlink` and `vpn_gateway` this is the CRN of the VPC / PowerVS / VDC / Direct Link / VPN gateway respectively. + // This field is required for network type `vpc`, `power_virtual_server`, `vpn_gateway`, and `directlink` connections. + // It is also required for `redundant_gre` connections when the base_network_type is set to VPC. This field is required + // to be unspecified for network type `classic`, `gre_tunnel` and `unbound_gre_tunnel` connections. + NetworkID *string `json:"network_id,omitempty"` + + // Defines what type of network is connected via this connection. + NetworkType *string `json:"network_type,omitempty"` + // Array of prefix route filters for a transit gateway connection. This is order dependent with those first in the // array being applied first, and those at the end of the array is applied last, or just before the default. This field - // does not apply to the 'redundant_gre' network type. + // does not apply to the `redundant_gre` network type. PrefixFilters []TransitGatewayConnectionPrefixFilterReference `json:"prefix_filters,omitempty"` // Default setting of permit or deny which applies to any routes that don't match a specified filter. This field does - // not apply to the 'redundant_gre' network type. + // not apply to the `redundant_gre` network type. PrefixFiltersDefault *string `json:"prefix_filters_default,omitempty"` - // Remote network BGP ASN. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' connections. + // Remote network BGP ASN. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` connections. RemoteBgpAsn *int64 `json:"remote_bgp_asn,omitempty"` - // Remote gateway IP address. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' + // Remote gateway IP address. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` // connections. RemoteGatewayIp *string `json:"remote_gateway_ip,omitempty"` - // Remote tunnel IP address. This field only applies to network type 'gre_tunnel' and 'unbound_gre_tunnel' + // Remote tunnel IP address. This field only applies to network type `gre_tunnel` and `unbound_gre_tunnel` // connections. RemoteTunnelIp *string `json:"remote_tunnel_ip,omitempty"` @@ -4946,26 +4825,28 @@ type TransitGatewayConnectionCust struct { // Code and processes using this field must tolerate unexpected values. Status *string `json:"status" validate:"required"` - // Collection of all tunnels for 'redundant_gre' connection. - Tunnels []TransitGatewayRedundantGRETunnelReference `json:"tunnels,omitempty"` + // Collection of all tunnels for `redundant_gre` and `vpn_gateway` connections. + Tunnels []TransitGatewayTunnel `json:"tunnels,omitempty"` // The date and time that this connection was last updated. UpdatedAt *strfmt.DateTime `json:"updated_at" validate:"required"` - // Location of GRE tunnel. This field only applies to network type 'gre_tunnel' connections. - Zone *GreTunnelZoneReference `json:"zone,omitempty"` + // Location of GRE tunnel. This field is required for network type `gre_tunnel` and `vpn_gateway` connections. + Zone *ZoneReference `json:"zone,omitempty"` } // Constants associated with the TransitGatewayConnectionCust.BaseNetworkType property. -// The type of network the GRE tunnel is targeting. +// The type of network the Unbound GRE tunnel is targeting. This field is required for network type `unbound_gre_tunnel` +// and must be set to `classic`. For a `redundant_gre` network type, the value is required and can be either VPC or +// Classic. This field is required to be unspecified for network type `classic`, `directlink`, `vpc`, +// `power_virtual_server`, `vpn_gateway` and `gre_tunnel` connections. const ( TransitGatewayConnectionCust_BaseNetworkType_Classic = "classic" TransitGatewayConnectionCust_BaseNetworkType_Vpc = "vpc" ) // Constants associated with the TransitGatewayConnectionCust.NetworkType property. -// Defines what type of network is connected via this connection. The list of enumerated values for this property may -// expand in the future. Code and processes using this field must tolerate unexpected values. +// Defines what type of network is connected via this connection. const ( TransitGatewayConnectionCust_NetworkType_Classic = "classic" TransitGatewayConnectionCust_NetworkType_Directlink = "directlink" @@ -4974,11 +4855,12 @@ const ( TransitGatewayConnectionCust_NetworkType_RedundantGre = "redundant_gre" TransitGatewayConnectionCust_NetworkType_UnboundGreTunnel = "unbound_gre_tunnel" TransitGatewayConnectionCust_NetworkType_Vpc = "vpc" + TransitGatewayConnectionCust_NetworkType_VpnGateway = "vpn_gateway" ) // Constants associated with the TransitGatewayConnectionCust.PrefixFiltersDefault property. // Default setting of permit or deny which applies to any routes that don't match a specified filter. This field does -// not apply to the 'redundant_gre' network type. +// not apply to the `redundant_gre` network type. const ( TransitGatewayConnectionCust_PrefixFiltersDefault_Deny = "deny" TransitGatewayConnectionCust_PrefixFiltersDefault_Permit = "permit" @@ -5014,19 +4896,19 @@ const ( // UnmarshalTransitGatewayConnectionCust unmarshals an instance of TransitGatewayConnectionCust from the specified map of raw messages. func UnmarshalTransitGatewayConnectionCust(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(TransitGatewayConnectionCust) - err = core.UnmarshalPrimitive(m, "base_network_type", &obj.BaseNetworkType) + err = core.UnmarshalPrimitive(m, "base_connection_id", &obj.BaseConnectionID) if err != nil { return } - err = core.UnmarshalPrimitive(m, "name", &obj.Name) + err = core.UnmarshalPrimitive(m, "base_network_type", &obj.BaseNetworkType) if err != nil { return } - err = core.UnmarshalPrimitive(m, "network_id", &obj.NetworkID) + err = core.UnmarshalPrimitive(m, "cidr", &obj.Cidr) if err != nil { return } - err = core.UnmarshalPrimitive(m, "network_type", &obj.NetworkType) + err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) if err != nil { return } @@ -5034,31 +4916,35 @@ func UnmarshalTransitGatewayConnectionCust(m map[string]json.RawMessage, result if err != nil { return } - err = core.UnmarshalPrimitive(m, "base_connection_id", &obj.BaseConnectionID) + err = core.UnmarshalPrimitive(m, "local_bgp_asn", &obj.LocalBgpAsn) if err != nil { return } - err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) + err = core.UnmarshalPrimitive(m, "local_gateway_ip", &obj.LocalGatewayIp) if err != nil { return } - err = core.UnmarshalPrimitive(m, "local_bgp_asn", &obj.LocalBgpAsn) + err = core.UnmarshalPrimitive(m, "local_tunnel_ip", &obj.LocalTunnelIp) if err != nil { return } - err = core.UnmarshalPrimitive(m, "local_gateway_ip", &obj.LocalGatewayIp) + err = core.UnmarshalPrimitive(m, "mtu", &obj.Mtu) if err != nil { return } - err = core.UnmarshalPrimitive(m, "local_tunnel_ip", &obj.LocalTunnelIp) + err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } - err = core.UnmarshalPrimitive(m, "mtu", &obj.Mtu) + err = core.UnmarshalPrimitive(m, "network_account_id", &obj.NetworkAccountID) if err != nil { return } - err = core.UnmarshalPrimitive(m, "network_account_id", &obj.NetworkAccountID) + err = core.UnmarshalPrimitive(m, "network_id", &obj.NetworkID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "network_type", &obj.NetworkType) if err != nil { return } @@ -5090,7 +4976,7 @@ func UnmarshalTransitGatewayConnectionCust(m map[string]json.RawMessage, result if err != nil { return } - err = core.UnmarshalModel(m, "tunnels", &obj.Tunnels, UnmarshalTransitGatewayRedundantGRETunnelReference) + err = core.UnmarshalModel(m, "tunnels", &obj.Tunnels, UnmarshalTransitGatewayTunnel) if err != nil { return } @@ -5098,7 +4984,7 @@ func UnmarshalTransitGatewayConnectionCust(m map[string]json.RawMessage, result if err != nil { return } - err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalGreTunnelZoneReference) + err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalZoneReference) if err != nil { return } @@ -5249,8 +5135,42 @@ func UnmarshalTransitGatewayConnectionPrefixFilterReference(m map[string]json.Ra return } -// TransitGatewayRedundantGRETunnelReference : Details for a redundant GRE tunnel. -type TransitGatewayRedundantGRETunnelReference struct { +// TransitGatewayReference : Transit gateway reference. +type TransitGatewayReference struct { + // gateway CRN. + Crn *string `json:"crn" validate:"required"` + + // gateway ID. + ID *string `json:"id" validate:"required"` + + // transit gateway name. + Name *string `json:"name" validate:"required"` +} + +// UnmarshalTransitGatewayReference unmarshals an instance of TransitGatewayReference from the specified map of raw messages. +func UnmarshalTransitGatewayReference(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(TransitGatewayReference) + err = core.UnmarshalPrimitive(m, "crn", &obj.Crn) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// TransitGatewayTunnel : Details for a redundant GRE tunnel. +type TransitGatewayTunnel struct { + // The type of network the redundant GRE tunnel is targeting. + BaseNetworkType *string `json:"base_network_type" validate:"required"` + // The date and time that this GRE tunnel was created. CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` @@ -5273,8 +5193,15 @@ type TransitGatewayRedundantGRETunnelReference struct { // The user-defined name for this tunnel. Name *string `json:"name" validate:"required"` + // The ID of the account for cross account Classic connections. This field is required when the GRE tunnel is in a + // different account than the gateway and the base network is Classic. + NetworkAccountID *string `json:"network_account_id,omitempty"` + + // The ID of the network VPC being connected via this connection. + NetworkID *string `json:"network_id,omitempty"` + // Remote network BGP ASN. The following ASN values are reserved and unavailable 0, 13884, 36351, 64512-64513, 65100, - // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If 'remote_bgp_asn' is omitted on create requests, IBM + // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If `remote_bgp_asn` is omitted on create requests, IBM // will assign an ASN. RemoteBgpAsn *int64 `json:"remote_bgp_asn" validate:"required"` @@ -5292,28 +5219,38 @@ type TransitGatewayRedundantGRETunnelReference struct { // The date and time that this tunnel was last updated. UpdatedAt *strfmt.DateTime `json:"updated_at" validate:"required"` - // The tunnel's location. The specified availability zone must reside in the gateway's region. Use the IBM Cloud - // global catalog to list zones within the desired region. - Zone *RgreTunnelZoneReference `json:"zone" validate:"required"` + // Availability zone reference. + Zone *ZoneReference `json:"zone" validate:"required"` } -// Constants associated with the TransitGatewayRedundantGRETunnelReference.Status property. +// Constants associated with the TransitGatewayTunnel.BaseNetworkType property. +// The type of network the redundant GRE tunnel is targeting. +const ( + TransitGatewayTunnel_BaseNetworkType_Classic = "classic" + TransitGatewayTunnel_BaseNetworkType_Vpc = "vpc" +) + +// Constants associated with the TransitGatewayTunnel.Status property. // Tunnel's current configuration state. The list of enumerated values for this property may expand in the future. Code // and processes using this field must tolerate unexpected values. const ( - TransitGatewayRedundantGRETunnelReference_Status_Attached = "attached" - TransitGatewayRedundantGRETunnelReference_Status_Deleting = "deleting" - TransitGatewayRedundantGRETunnelReference_Status_Detached = "detached" - TransitGatewayRedundantGRETunnelReference_Status_Detaching = "detaching" - TransitGatewayRedundantGRETunnelReference_Status_Failed = "failed" - TransitGatewayRedundantGRETunnelReference_Status_Pending = "pending" - TransitGatewayRedundantGRETunnelReference_Status_Suspended = "suspended" - TransitGatewayRedundantGRETunnelReference_Status_Suspending = "suspending" + TransitGatewayTunnel_Status_Attached = "attached" + TransitGatewayTunnel_Status_Deleting = "deleting" + TransitGatewayTunnel_Status_Detached = "detached" + TransitGatewayTunnel_Status_Detaching = "detaching" + TransitGatewayTunnel_Status_Failed = "failed" + TransitGatewayTunnel_Status_Pending = "pending" + TransitGatewayTunnel_Status_Suspended = "suspended" + TransitGatewayTunnel_Status_Suspending = "suspending" ) -// UnmarshalTransitGatewayRedundantGRETunnelReference unmarshals an instance of TransitGatewayRedundantGRETunnelReference from the specified map of raw messages. -func UnmarshalTransitGatewayRedundantGRETunnelReference(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(TransitGatewayRedundantGRETunnelReference) +// UnmarshalTransitGatewayTunnel unmarshals an instance of TransitGatewayTunnel from the specified map of raw messages. +func UnmarshalTransitGatewayTunnel(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(TransitGatewayTunnel) + err = core.UnmarshalPrimitive(m, "base_network_type", &obj.BaseNetworkType) + if err != nil { + return + } err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) if err != nil { return @@ -5342,6 +5279,14 @@ func UnmarshalTransitGatewayRedundantGRETunnelReference(m map[string]json.RawMes if err != nil { return } + err = core.UnmarshalPrimitive(m, "network_account_id", &obj.NetworkAccountID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "network_id", &obj.NetworkID) + if err != nil { + return + } err = core.UnmarshalPrimitive(m, "remote_bgp_asn", &obj.RemoteBgpAsn) if err != nil { return @@ -5362,7 +5307,24 @@ func UnmarshalTransitGatewayRedundantGRETunnelReference(m map[string]json.RawMes if err != nil { return } - err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalRgreTunnelZoneReference) + err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalZoneReference) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// TransitGatewayTunnelCollection : Collection of all tunnels for `redundant_gre` and `vpn_gateway` connections. +type TransitGatewayTunnelCollection struct { + // Collection of all tunnels for `redundant_gre` and `vpn_gateway` connections. + Tunnels []TransitGatewayTunnel `json:"tunnels" validate:"required"` +} + +// UnmarshalTransitGatewayTunnelCollection unmarshals an instance of TransitGatewayTunnelCollection from the specified map of raw messages. +func UnmarshalTransitGatewayTunnelCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(TransitGatewayTunnelCollection) + err = core.UnmarshalModel(m, "tunnels", &obj.Tunnels, UnmarshalTransitGatewayTunnel) if err != nil { return } @@ -5370,8 +5332,35 @@ func UnmarshalTransitGatewayRedundantGRETunnelReference(m map[string]json.RawMes return } -// TransitGatewayRedundantGRETunnelTemplate : A create template with information for redundant GRE tunnel. -type TransitGatewayRedundantGRETunnelTemplate struct { +// TransitGatewayTunnelPatch : An update template for a Transit Gateway connection tunnel. +type TransitGatewayTunnelPatch struct { + // The user-defined name for this connection tunnel. + Name *string `json:"name,omitempty"` +} + +// UnmarshalTransitGatewayTunnelPatch unmarshals an instance of TransitGatewayTunnelPatch from the specified map of raw messages. +func UnmarshalTransitGatewayTunnelPatch(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(TransitGatewayTunnelPatch) + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// AsPatch returns a generic map representation of the TransitGatewayTunnelPatch +func (transitGatewayTunnelPatch *TransitGatewayTunnelPatch) AsPatch() (_patch map[string]interface{}, err error) { + var jsonData []byte + jsonData, err = json.Marshal(transitGatewayTunnelPatch) + if err == nil { + err = json.Unmarshal(jsonData, &_patch) + } + return +} + +// TransitGatewayTunnelTemplate : A create template with information for redundant GRE tunnel. +type TransitGatewayTunnelTemplate struct { // Local gateway IP address. LocalGatewayIp *string `json:"local_gateway_ip" validate:"required"` @@ -5383,7 +5372,7 @@ type TransitGatewayRedundantGRETunnelTemplate struct { Name *string `json:"name" validate:"required"` // Remote network BGP ASN. The following ASN values are reserved and unavailable 0, 13884, 36351, 64512-64513, 65100, - // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If 'remote_bgp_asn' is omitted on create requests, IBM + // 65200-65234, 65402-65433, 65500 and 4201065000-4201065999. If `remote_bgp_asn` is omitted on create requests, IBM // will assign an ASN. RemoteBgpAsn *int64 `json:"remote_bgp_asn,omitempty"` @@ -5399,9 +5388,9 @@ type TransitGatewayRedundantGRETunnelTemplate struct { Zone ZoneIdentityIntf `json:"zone" validate:"required"` } -// NewTransitGatewayRedundantGRETunnelTemplate : Instantiate TransitGatewayRedundantGRETunnelTemplate (Generic Model Constructor) -func (*TransitGatewayApisV1) NewTransitGatewayRedundantGRETunnelTemplate(localGatewayIp string, localTunnelIp string, name string, remoteGatewayIp string, remoteTunnelIp string, zone ZoneIdentityIntf) (_model *TransitGatewayRedundantGRETunnelTemplate, err error) { - _model = &TransitGatewayRedundantGRETunnelTemplate{ +// NewTransitGatewayTunnelTemplate : Instantiate TransitGatewayTunnelTemplate (Generic Model Constructor) +func (*TransitGatewayApisV1) NewTransitGatewayTunnelTemplate(localGatewayIp string, localTunnelIp string, name string, remoteGatewayIp string, remoteTunnelIp string, zone ZoneIdentityIntf) (_model *TransitGatewayTunnelTemplate, err error) { + _model = &TransitGatewayTunnelTemplate{ LocalGatewayIp: core.StringPtr(localGatewayIp), LocalTunnelIp: core.StringPtr(localTunnelIp), Name: core.StringPtr(name), @@ -5413,9 +5402,9 @@ func (*TransitGatewayApisV1) NewTransitGatewayRedundantGRETunnelTemplate(localGa return } -// UnmarshalTransitGatewayRedundantGRETunnelTemplate unmarshals an instance of TransitGatewayRedundantGRETunnelTemplate from the specified map of raw messages. -func UnmarshalTransitGatewayRedundantGRETunnelTemplate(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(TransitGatewayRedundantGRETunnelTemplate) +// UnmarshalTransitGatewayTunnelTemplate unmarshals an instance of TransitGatewayTunnelTemplate from the specified map of raw messages. +func UnmarshalTransitGatewayTunnelTemplate(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(TransitGatewayTunnelTemplate) err = core.UnmarshalPrimitive(m, "local_gateway_ip", &obj.LocalGatewayIp) if err != nil { return @@ -5448,37 +5437,6 @@ func UnmarshalTransitGatewayRedundantGRETunnelTemplate(m map[string]json.RawMess return } -// TransitGatewayReference : Transit gateway reference. -type TransitGatewayReference struct { - // gateway CRN. - Crn *string `json:"crn" validate:"required"` - - // gateway ID. - ID *string `json:"id" validate:"required"` - - // transit gateway name. - Name *string `json:"name" validate:"required"` -} - -// UnmarshalTransitGatewayReference unmarshals an instance of TransitGatewayReference from the specified map of raw messages. -func UnmarshalTransitGatewayReference(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(TransitGatewayReference) - err = core.UnmarshalPrimitive(m, "crn", &obj.Crn) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "id", &obj.ID) - if err != nil { - return - } - err = core.UnmarshalPrimitive(m, "name", &obj.Name) - if err != nil { - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - // UpdateTransitGatewayConnectionOptions : The UpdateTransitGatewayConnection options. type UpdateTransitGatewayConnectionOptions struct { // The Transit Gateway identifier. @@ -5488,8 +5446,8 @@ type UpdateTransitGatewayConnectionOptions struct { ID *string `json:"id" validate:"required,ne="` // The user-defined name for this transit gateway. If specified as empty string or nil, the name will be the network - // name (the name of the VPC in the case of network type 'vpc', and the word Classic, in the case of network type - // 'classic'). + // name (the name of the VPC in the case of network type `vpc`, and the word Classic, in the case of network type + // `classic`). Name *string `json:"name,omitempty"` // Default setting of permit or deny which applies to any routes that don't match a specified filter. @@ -5567,20 +5525,20 @@ type UpdateTransitGatewayConnectionPrefixFilterOptions struct { Before *string `json:"before,omitempty"` // Defines the minimum matched prefix precision. If this field is non-zero then the filter will match all routes within - // the 'prefix' that have a prefix length greater or equal to this value. + // the `prefix` that have a prefix length greater or equal to this value. // // This value can be zero, or a non-negative number greater than or equal to the prefix length of the filter's prefix - // or less then or equal to 32. If this value is set to zero, the filter will not use the 'ge' route matching behavior. - // If the 'le' value is non-zero the the 'ge' value must between the prefix length and the - // 'le' value, inclusive. + // or less then or equal to 32. If this value is set to zero, the filter will not use the `ge` route matching behavior. + // If the `le` value is non-zero the the `ge` value must between the prefix length and the + // `le` value, inclusive. Ge *int64 `json:"ge,omitempty"` // Defines the maximum matched prefix precision. If this field is non-zero then the filter will match all routes within - // the 'prefix' that have a prefix length less than or equal to this value. + // the `prefix` that have a prefix length less than or equal to this value. // // This value can be zero, or a non-negative number greater than or equal to the prefix length of the filter's prefix - // or less then or equal to 32. If this value is set to zero, the filter will not use the 'le' route matching behavior. - // If the 'ge' value is non-zero the the 'le' value must between the 'ge' value and 32, inclusive. + // or less then or equal to 32. If this value is set to zero, the filter will not use the `le` route matching behavior. + // If the `ge` value is non-zero the the `le` value must between the `ge` value and 32, inclusive. Le *int64 `json:"le,omitempty"` // The IPv4 Prefix to be matched by this filter. @@ -5671,19 +5629,20 @@ type UpdateTransitGatewayConnectionTunnelsOptions struct { // The tunnel identifier. GreTunnelID *string `json:"gre_tunnel_id" validate:"required,ne="` - // The user-defined name for this connection tunnel. - Name *string `json:"name,omitempty"` + // The update connection tunnel template. + TransitGatewayTunnelPatch map[string]interface{} `json:"TransitGatewayTunnel_patch" validate:"required"` // Allows users to set headers on API requests Headers map[string]string } // NewUpdateTransitGatewayConnectionTunnelsOptions : Instantiate UpdateTransitGatewayConnectionTunnelsOptions -func (*TransitGatewayApisV1) NewUpdateTransitGatewayConnectionTunnelsOptions(transitGatewayID string, id string, greTunnelID string) *UpdateTransitGatewayConnectionTunnelsOptions { +func (*TransitGatewayApisV1) NewUpdateTransitGatewayConnectionTunnelsOptions(transitGatewayID string, id string, greTunnelID string, transitGatewayTunnelPatch map[string]interface{}) *UpdateTransitGatewayConnectionTunnelsOptions { return &UpdateTransitGatewayConnectionTunnelsOptions{ - TransitGatewayID: core.StringPtr(transitGatewayID), - ID: core.StringPtr(id), - GreTunnelID: core.StringPtr(greTunnelID), + TransitGatewayID: core.StringPtr(transitGatewayID), + ID: core.StringPtr(id), + GreTunnelID: core.StringPtr(greTunnelID), + TransitGatewayTunnelPatch: transitGatewayTunnelPatch, } } @@ -5705,9 +5664,9 @@ func (_options *UpdateTransitGatewayConnectionTunnelsOptions) SetGreTunnelID(gre return _options } -// SetName : Allow user to set Name -func (_options *UpdateTransitGatewayConnectionTunnelsOptions) SetName(name string) *UpdateTransitGatewayConnectionTunnelsOptions { - _options.Name = core.StringPtr(name) +// SetTransitGatewayTunnelPatch : Allow user to set TransitGatewayTunnelPatch +func (_options *UpdateTransitGatewayConnectionTunnelsOptions) SetTransitGatewayTunnelPatch(transitGatewayTunnelPatch map[string]interface{}) *UpdateTransitGatewayConnectionTunnelsOptions { + _options.TransitGatewayTunnelPatch = transitGatewayTunnelPatch return _options } @@ -5725,7 +5684,10 @@ type UpdateTransitGatewayOptions struct { // Allow global routing for a Transit Gateway. Global *bool `json:"global,omitempty"` - // The user-defined name for this transit gateway. + // Allow GRE Enhanced Route Propagation on this gateway. + GreEnhancedRoutePropagation *bool `json:"gre_enhanced_route_propagation,omitempty"` + + // A human readable name for a resource. Name *string `json:"name,omitempty"` // Allows users to set headers on API requests @@ -5751,6 +5713,12 @@ func (_options *UpdateTransitGatewayOptions) SetGlobal(global bool) *UpdateTrans return _options } +// SetGreEnhancedRoutePropagation : Allow user to set GreEnhancedRoutePropagation +func (_options *UpdateTransitGatewayOptions) SetGreEnhancedRoutePropagation(greEnhancedRoutePropagation bool) *UpdateTransitGatewayOptions { + _options.GreEnhancedRoutePropagation = core.BoolPtr(greEnhancedRoutePropagation) + return _options +} + // SetName : Allow user to set Name func (_options *UpdateTransitGatewayOptions) SetName(name string) *UpdateTransitGatewayOptions { _options.Name = core.StringPtr(name) @@ -5807,23 +5775,6 @@ func UnmarshalZoneReference(m map[string]json.RawMessage, result interface{}) (e return } -// ZoneReferenceCollection : Collection of availability zones. -type ZoneReferenceCollection struct { - // Array of valid zones for GRE tunnels. - Zones []ZoneReference `json:"zones" validate:"required"` -} - -// UnmarshalZoneReferenceCollection unmarshals an instance of ZoneReferenceCollection from the specified map of raw messages. -func UnmarshalZoneReferenceCollection(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(ZoneReferenceCollection) - err = core.UnmarshalModel(m, "zones", &obj.Zones, UnmarshalZoneReference) - if err != nil { - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - // ZoneIdentityByName : Availability zone. // This model "extends" ZoneIdentity type ZoneIdentityByName struct { diff --git a/vendor/github.com/IBM/platform-services-go-sdk/common/version.go b/vendor/github.com/IBM/platform-services-go-sdk/common/version.go index 8b232fcc21db..960e31915135 100644 --- a/vendor/github.com/IBM/platform-services-go-sdk/common/version.go +++ b/vendor/github.com/IBM/platform-services-go-sdk/common/version.go @@ -17,4 +17,4 @@ package common // Version of the SDK -const Version = "0.81.0" +const Version = "0.86.1" diff --git a/vendor/github.com/IBM/platform-services-go-sdk/globalcatalogv1/global_catalog_v1.go b/vendor/github.com/IBM/platform-services-go-sdk/globalcatalogv1/global_catalog_v1.go index 09ed833852b5..a5a8a9ccb19c 100644 --- a/vendor/github.com/IBM/platform-services-go-sdk/globalcatalogv1/global_catalog_v1.go +++ b/vendor/github.com/IBM/platform-services-go-sdk/globalcatalogv1/global_catalog_v1.go @@ -15,7 +15,7 @@ */ /* - * IBM OpenAPI SDK Code Generator Version: 3.102.0-615ec964-20250307-203034 + * IBM OpenAPI SDK Code Generator Version: 3.106.0-09823488-20250707-071701 */ // Package globalcatalogv1 : Operations and models for the GlobalCatalogV1 service @@ -201,12 +201,12 @@ func (globalCatalog *GlobalCatalogV1) ListCatalogEntriesWithContext(ctx context. return } - for headerName, headerValue := range listCatalogEntriesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "ListCatalogEntries") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "ListCatalogEntries") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listCatalogEntriesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -299,12 +299,12 @@ func (globalCatalog *GlobalCatalogV1) CreateCatalogEntryWithContext(ctx context. return } - for headerName, headerValue := range createCatalogEntryOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "CreateCatalogEntry") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "CreateCatalogEntry") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createCatalogEntryOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -421,12 +421,12 @@ func (globalCatalog *GlobalCatalogV1) GetCatalogEntryWithContext(ctx context.Con return } - for headerName, headerValue := range getCatalogEntryOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetCatalogEntry") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetCatalogEntry") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getCatalogEntryOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -507,12 +507,12 @@ func (globalCatalog *GlobalCatalogV1) UpdateCatalogEntryWithContext(ctx context. return } - for headerName, headerValue := range updateCatalogEntryOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "UpdateCatalogEntry") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "UpdateCatalogEntry") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateCatalogEntryOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -629,12 +629,12 @@ func (globalCatalog *GlobalCatalogV1) DeleteCatalogEntryWithContext(ctx context. return } - for headerName, headerValue := range deleteCatalogEntryOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "DeleteCatalogEntry") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "DeleteCatalogEntry") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteCatalogEntryOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -697,12 +697,12 @@ func (globalCatalog *GlobalCatalogV1) GetChildObjectsWithContext(ctx context.Con return } - for headerName, headerValue := range getChildObjectsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetChildObjects") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetChildObjects") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getChildObjectsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -794,12 +794,12 @@ func (globalCatalog *GlobalCatalogV1) RestoreCatalogEntryWithContext(ctx context return } - for headerName, headerValue := range restoreCatalogEntryOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "RestoreCatalogEntry") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "RestoreCatalogEntry") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range restoreCatalogEntryOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -859,12 +859,12 @@ func (globalCatalog *GlobalCatalogV1) GetVisibilityWithContext(ctx context.Conte return } - for headerName, headerValue := range getVisibilityOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetVisibility") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetVisibility") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVisibilityOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -933,12 +933,12 @@ func (globalCatalog *GlobalCatalogV1) UpdateVisibilityWithContext(ctx context.Co return } - for headerName, headerValue := range updateVisibilityOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "UpdateVisibility") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "UpdateVisibility") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVisibilityOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Content-Type", "application/json") @@ -948,6 +948,9 @@ func (globalCatalog *GlobalCatalogV1) UpdateVisibilityWithContext(ctx context.Co } body := make(map[string]interface{}) + if updateVisibilityOptions.Restrictions != nil { + body["restrictions"] = updateVisibilityOptions.Restrictions + } if updateVisibilityOptions.Extendable != nil { body["extendable"] = updateVisibilityOptions.Extendable } @@ -1014,12 +1017,12 @@ func (globalCatalog *GlobalCatalogV1) GetPricingWithContext(ctx context.Context, return } - for headerName, headerValue := range getPricingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetPricing") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetPricing") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPricingOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1092,12 +1095,12 @@ func (globalCatalog *GlobalCatalogV1) GetPricingDeploymentsWithContext(ctx conte return } - for headerName, headerValue := range getPricingDeploymentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetPricingDeployments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetPricingDeployments") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPricingDeploymentsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1165,12 +1168,12 @@ func (globalCatalog *GlobalCatalogV1) GetAuditLogsWithContext(ctx context.Contex return } - for headerName, headerValue := range getAuditLogsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetAuditLogs") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetAuditLogs") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getAuditLogsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1250,12 +1253,12 @@ func (globalCatalog *GlobalCatalogV1) ListArtifactsWithContext(ctx context.Conte return } - for headerName, headerValue := range listArtifactsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "ListArtifacts") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "ListArtifacts") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listArtifactsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1324,12 +1327,12 @@ func (globalCatalog *GlobalCatalogV1) GetArtifactWithContext(ctx context.Context return } - for headerName, headerValue := range getArtifactOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetArtifact") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "GetArtifact") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getArtifactOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "*/*") @@ -1392,12 +1395,12 @@ func (globalCatalog *GlobalCatalogV1) UploadArtifactWithContext(ctx context.Cont return } - for headerName, headerValue := range uploadArtifactOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "UploadArtifact") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "UploadArtifact") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range uploadArtifactOptions.Headers { builder.AddHeader(headerName, headerValue) } if uploadArtifactOptions.ContentType != nil { @@ -1465,12 +1468,12 @@ func (globalCatalog *GlobalCatalogV1) DeleteArtifactWithContext(ctx context.Cont return } - for headerName, headerValue := range deleteArtifactOptions.Headers { + sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "DeleteArtifact") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("global_catalog", "V1", "DeleteArtifact") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteArtifactOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -1785,49 +1788,75 @@ func UnmarshalBullets(m map[string]json.RawMessage, result interface{}) (err err // CfMetaData : Service-related metadata. type CfMetaData struct { - // Type of service. + // The type of service (public, cfaas, personal_catalog, kms, toolchain, etc.). + // Deprecated: this field is deprecated and may be removed in a future release. Type *string `json:"type,omitempty"` - // Boolean value that describes whether the service is compatible with Identity and Access Management. + // Boolean value that describes whether the service is compatible with Identity and Access Management for + // authentication and authorization. IamCompatible *bool `json:"iam_compatible,omitempty"` - // Boolean value that describes whether the service has a unique API key. + // Boolean value that describes whether the service has a unique API key. Only settable on services, should be set via + // partnercenter. + // Deprecated: this field is deprecated and may be removed in a future release. UniqueAPIKey *bool `json:"unique_api_key,omitempty"` - // Boolean value that describes whether the service is provisionable or not. You may need sales or support to create - // this service. + // Boolean value that, if true, the service is provisionable via resource controller (RC) or, if false, via a service + // control point API. If false, you may need sales or support to create this service. Provisionable *bool `json:"provisionable,omitempty"` - // Boolean value that describes whether you can create bindings for this service. + // Boolean value that describes whether the service can be bound to an application. If true then this will create and + // use resource keys. Bindable *bool `json:"bindable,omitempty"` - // Boolean value that describes whether the service supports asynchronous provisioning. + // Boolean value that describes whether the service supports asynchronous provisioning. Now handled by a 202 response + // indicating support from the broker on provisioning. + // Deprecated: this field is deprecated and may be removed in a future release. AsyncProvisioningSupported *bool `json:"async_provisioning_supported,omitempty"` - // Boolean value that describes whether the service supports asynchronous unprovisioning. + // Boolean value that describes whether the service supports asynchronous unprovisioning. Now handled by a 202 response + // indicating support from the broker on unprovisioning. + // Deprecated: this field is deprecated and may be removed in a future release. AsyncUnprovisioningSupported *bool `json:"async_unprovisioning_supported,omitempty"` - // Service dependencies. + // Dependencies needed to use this service. + // Deprecated: this field is deprecated and may be removed in a future release. Requires []string `json:"requires,omitempty"` - // Boolean value that describes whether the service supports upgrade or downgrade for some plans. + // Boolean value that describes whether the service supports changing plans within the service. Only settable on + // services, read only on plans and deployments. PlanUpdateable *bool `json:"plan_updateable,omitempty"` // String that describes whether the service is active or inactive. + // Deprecated: this field is deprecated and may be removed in a future release. State *string `json:"state,omitempty"` - // Boolean value that describes whether the service check is enabled. + // Boolean value that describes whether the Estado testing service will perform uptime tests for this service. + // Deprecated: this field is deprecated and may be removed in a future release. ServiceCheckEnabled *bool `json:"service_check_enabled,omitempty"` - // Test check interval. + // A unit of time that determines the time in between uptime checks performed by Estado. + // Deprecated: this field is deprecated and may be removed in a future release. TestCheckInterval *int64 `json:"test_check_interval,omitempty"` - // Boolean value that describes whether the service supports service keys. + // Boolean value that describes whether the service supports the creation of service credentials. Without service key + // support, a service cannot be bound to a cluster. ServiceKeySupported *bool `json:"service_key_supported,omitempty"` // If the field is imported from Cloud Foundry, the Cloud Foundry region's GUID. This is a required field. For example, // `us-south=123`. + // Deprecated: this field is deprecated and may be removed in a future release. CfGUID map[string]string `json:"cf_guid,omitempty"` + + // Cloud resource name identifying the environment containing this service. + CRNMask *string `json:"crn_mask,omitempty"` + + // Boolean flag indicating if this service only offers paid pricing plans rather than the default paygo. + // Deprecated: this field is deprecated and may be removed in a future release. + PaidOnly *bool `json:"paid_only,omitempty"` + + // Boolean flag that determines if the hybrid page is accessible from the main catalog provisioning page. + CustomCreatePageHybridEnabled *bool `json:"custom_create_page_hybrid_enabled,omitempty"` } // UnmarshalCfMetaData unmarshals an instance of CfMetaData from the specified map of raw messages. @@ -1903,6 +1932,21 @@ func UnmarshalCfMetaData(m map[string]json.RawMessage, result interface{}) (err err = core.SDKErrorf(err, "", "cf_guid-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "crn_mask", &obj.CRNMask) + if err != nil { + err = core.SDKErrorf(err, "", "crn_mask-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "paid_only", &obj.PaidOnly) + if err != nil { + err = core.SDKErrorf(err, "", "paid_only-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "custom_create_page_hybrid_enabled", &obj.CustomCreatePageHybridEnabled) + if err != nil { + err = core.SDKErrorf(err, "", "custom_create_page_hybrid_enabled-error", common.GetComponentInfo()) + return + } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } @@ -1916,6 +1960,7 @@ type Callbacks struct { BrokerURL *string `json:"broker_url,omitempty"` // The URL of the deployment broker SC proxy. + // Deprecated: this field is deprecated and may be removed in a future release. BrokerProxyURL *string `json:"broker_proxy_url,omitempty"` // The URL of dashboard callback. @@ -2003,8 +2048,8 @@ type CatalogEntry struct { // OverviewUI for a user-readable name. Name *string `json:"name" validate:"required"` - // The type of catalog entry, **service**, **template**, **dashboard**, which determines the type and shape of the - // object. + // The type of catalog entry which determines the type and shape of the object. Valid GC types are buildpack, cname, + // dataset, geography, iaas, platform_service, runtime, service, template, ui-dashboard. Kind *string `json:"kind" validate:"required"` // Overview is nested in the top level. The key value pair is `[_language_]overview_ui`. @@ -2020,7 +2065,8 @@ type CatalogEntry struct { // all plans are disabled. Disabled *bool `json:"disabled" validate:"required"` - // A list of tags. For example, IBM, 3rd Party, Beta, GA, and Single Tenant. + // A searchable list of tags. For example, IBM, 3rd Party, Beta, GA, and Single Tenant. Valid values found at + // https://globalcatalog.test.cloud.ibm.com/search. Tags []string `json:"tags" validate:"required"` // Boolean value that determines whether the catalog entry is a group. @@ -2050,7 +2096,8 @@ type CatalogEntry struct { // tags to indicate the locations this service is deployable to. GeoTags []string `json:"geo_tags,omitempty"` - // tags to indicate the type of pricing plans this service supports. + // tags to indicate the type of pricing plans this service supports. Plans tagged with paid_only will not be shown for + // trial accounts. PricingTags []string `json:"pricing_tags,omitempty"` // Date created. @@ -2061,8 +2108,8 @@ type CatalogEntry struct { } // Constants associated with the CatalogEntry.Kind property. -// The type of catalog entry, **service**, **template**, **dashboard**, which determines the type and shape of the -// object. +// The type of catalog entry which determines the type and shape of the object. Valid GC types are buildpack, cname, +// dataset, geography, iaas, platform_service, runtime, service, template, ui-dashboard. const ( CatalogEntryKindDashboardConst = "dashboard" CatalogEntryKindServiceConst = "service" @@ -2173,7 +2220,8 @@ func UnmarshalCatalogEntry(m map[string]json.RawMessage, result interface{}) (er // CatalogEntryMetadata : Model used to describe metadata object returned. type CatalogEntryMetadata struct { - // Boolean value that describes whether the service is compatible with the Resource Controller. + // Boolean value that describes whether the service is compatible with the Resource Controller. Only settable for + // deployments, propogated upward. RcCompatible *bool `json:"rc_compatible,omitempty"` // Service-related metadata. @@ -2203,7 +2251,8 @@ type CatalogEntryMetadata struct { // The original name of the object. OriginalName *string `json:"original_name,omitempty"` - // Optional version of the object. + // Optional version of the object. Only valid for templates. + // Deprecated: this field is deprecated and may be removed in a future release. Version *string `json:"version,omitempty"` // Additional information. @@ -2301,25 +2350,28 @@ type CatalogEntryMetadataDeployment struct { // Pointer to the location resource in the catalog. LocationURL *string `json:"location_url,omitempty"` - // Original service location. + // The original region in which this deployment existed. OriginalLocation *string `json:"original_location,omitempty"` // A CRN that describes the deployment. crn:v1:[cname]:[ctype]:[location]:[scope]::[resource-type]:[resource]. TargetCRN *string `json:"target_crn,omitempty"` - // CRN for the service. + // Cloud resource name for this deployment. ServiceCRN *string `json:"service_crn,omitempty"` - // ID for MCCP. + // ID of the multi cloud connectivity platform. + // Deprecated: this field is deprecated and may be removed in a future release. MccpID *string `json:"mccp_id,omitempty"` // The broker associated with a catalog entry. Broker *Broker `json:"broker,omitempty"` // This deployment not only supports RC but is ready to migrate and support the RC broker for a location. + // Deprecated: this field is deprecated and may be removed in a future release. SupportsRcMigration *bool `json:"supports_rc_migration,omitempty"` - // network to use during deployment. + // When using the service_endpoint_supported tag for a deployment, this optional field can be set on a deployment to + // denote the supported service endpoint type (cse_private, public, or cse_private+public). TargetNetwork *string `json:"target_network,omitempty"` } @@ -2377,7 +2429,7 @@ func UnmarshalCatalogEntryMetadataDeployment(m map[string]json.RawMessage, resul // CatalogEntryMetadataPricing : Pricing-related information. type CatalogEntryMetadataPricing struct { - // Type of plan. Valid values are `free`, `trial`, `paygo`, `bluemix-subscription`, and `ibm-subscription`. + // Type of plan. Valid values are `free`, `trial`, `paygo`, `paid`, `subscription`. Type *string `json:"type,omitempty"` // Defines where the pricing originates. @@ -2392,6 +2444,10 @@ type CatalogEntryMetadataPricing struct { // The deployment location this pricing is from. Only set if object kind is deployment. DeploymentLocation *string `json:"deployment_location,omitempty"` + // If price is for a deployment object then the region in the pricing catalog of the deployment object will be here. To + // be valid, this value must be contained within deployment_regions. + DeploymentRegion *string `json:"deployment_region,omitempty"` + // Is the location price not available. Only set in api /pricing/deployment and only set if true. This means for the // given deployment object there was no pricing set in pricing catalog. DeploymentLocationNoPriceAvailable *bool `json:"deployment_location_no_price_available,omitempty"` @@ -2401,6 +2457,22 @@ type CatalogEntryMetadataPricing struct { // List of regions where region pricing is available. Only set on global deployments if enabled by owner. DeploymentRegions []string `json:"deployment_regions,omitempty"` + + // The start date-time indicating when this pricing plan takes effect. + EffectiveFrom *strfmt.DateTime `json:"effective_from,omitempty"` + + // The end date-time indicating when this pricing plan is no longer in effect. + EffectiveUntil *strfmt.DateTime `json:"effective_until,omitempty"` + + // Boolean value indicating whether or not this pricing plan requires login to get pricing data. + RequireLogin *bool `json:"require_login,omitempty"` + + // URL to the entry for this plan on the pricing catalog. + PricingCatalogURL *string `json:"pricing_catalog_url,omitempty"` + + // Tags describing how this plan was purchased (catalog [default], seller, private offer). Currently only settable on + // MCSP subscription plans. + SalesAvenue []string `json:"sales_avenue,omitempty"` } // UnmarshalCatalogEntryMetadataPricing unmarshals an instance of CatalogEntryMetadataPricing from the specified map of raw messages. @@ -2431,6 +2503,11 @@ func UnmarshalCatalogEntryMetadataPricing(m map[string]json.RawMessage, result i err = core.SDKErrorf(err, "", "deployment_location-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "deployment_region", &obj.DeploymentRegion) + if err != nil { + err = core.SDKErrorf(err, "", "deployment_region-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "deployment_location_no_price_available", &obj.DeploymentLocationNoPriceAvailable) if err != nil { err = core.SDKErrorf(err, "", "deployment_location_no_price_available-error", common.GetComponentInfo()) @@ -2446,6 +2523,31 @@ func UnmarshalCatalogEntryMetadataPricing(m map[string]json.RawMessage, result i err = core.SDKErrorf(err, "", "deployment_regions-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "effective_from", &obj.EffectiveFrom) + if err != nil { + err = core.SDKErrorf(err, "", "effective_from-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "effective_until", &obj.EffectiveUntil) + if err != nil { + err = core.SDKErrorf(err, "", "effective_until-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "require_login", &obj.RequireLogin) + if err != nil { + err = core.SDKErrorf(err, "", "require_login-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "pricing_catalog_url", &obj.PricingCatalogURL) + if err != nil { + err = core.SDKErrorf(err, "", "pricing_catalog_url-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "sales_avenue", &obj.SalesAvenue) + if err != nil { + err = core.SDKErrorf(err, "", "sales_avenue-error", common.GetComponentInfo()) + return + } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } @@ -2456,8 +2558,8 @@ type CreateCatalogEntryOptions struct { // OverviewUI for a user-readable name. Name *string `json:"name" validate:"required"` - // The type of catalog entry, **service**, **template**, **dashboard**, which determines the type and shape of the - // object. + // The type of catalog entry which determines the type and shape of the object. Valid GC types are buildpack, cname, + // dataset, geography, iaas, platform_service, runtime, service, template, ui-dashboard. Kind *string `json:"kind" validate:"required"` // Overview is nested in the top level. The key value pair is `[_language_]overview_ui`. @@ -2470,7 +2572,8 @@ type CreateCatalogEntryOptions struct { // all plans are disabled. Disabled *bool `json:"disabled" validate:"required"` - // A list of tags. For example, IBM, 3rd Party, Beta, GA, and Single Tenant. + // A searchable list of tags. For example, IBM, 3rd Party, Beta, GA, and Single Tenant. Valid values found at + // https://globalcatalog.test.cloud.ibm.com/search. Tags []string `json:"tags" validate:"required"` // Information related to the provider associated with a catalog entry. @@ -2504,8 +2607,8 @@ type CreateCatalogEntryOptions struct { } // Constants associated with the CreateCatalogEntryOptions.Kind property. -// The type of catalog entry, **service**, **template**, **dashboard**, which determines the type and shape of the -// object. +// The type of catalog entry which determines the type and shape of the object. Valid GC types are buildpack, cname, +// dataset, geography, iaas, platform_service, runtime, service, template, ui-dashboard. const ( CreateCatalogEntryOptionsKindDashboardConst = "dashboard" CreateCatalogEntryOptionsKindServiceConst = "service" @@ -2748,25 +2851,28 @@ type DeploymentBase struct { // URL of deployment. LocationURL *string `json:"location_url,omitempty"` - // Original service location. + // The original region in which this deployment existed. OriginalLocation *string `json:"original_location,omitempty"` // A CRN that describes the deployment. crn:v1:[cname]:[ctype]:[location]:[scope]::[resource-type]:[resource]. TargetCRN *string `json:"target_crn,omitempty"` - // CRN for the service. + // Cloud resource name for this deployment. ServiceCRN *string `json:"service_crn,omitempty"` - // ID for MCCP. + // ID of the multi cloud connectivity platform. + // Deprecated: this field is deprecated and may be removed in a future release. MccpID *string `json:"mccp_id,omitempty"` // The broker associated with a catalog entry. Broker *Broker `json:"broker,omitempty"` // This deployment not only supports RC but is ready to migrate and support the RC broker for a location. + // Deprecated: this field is deprecated and may be removed in a future release. SupportsRcMigration *bool `json:"supports_rc_migration,omitempty"` - // network to use during deployment. + // When using the service_endpoint_supported tag for a deployment, this optional field can be set on a deployment to + // denote the supported service endpoint type (cse_private, public, or cse_private+public). TargetNetwork *string `json:"target_network,omitempty"` } @@ -3692,44 +3798,47 @@ func UnmarshalMessage(m map[string]json.RawMessage, result interface{}) (err err // Metrics : Plan-specific cost metrics information. type Metrics struct { - // The part reference. + // The reference guid for the part. PartRef *string `json:"part_ref,omitempty"` // The metric ID or part number. MetricID *string `json:"metric_id,omitempty"` - // The tier model. + // The pricing tier type used to calculate the marginal unit price. Follows simple, graduated or block tier styles. TierModel *string `json:"tier_model,omitempty"` - // The unit to charge. + // The unit to be charged under this metric. ChargeUnit *string `json:"charge_unit,omitempty"` - // The charge unit name. + // The name associated with a charge unit to provide context. ChargeUnitName *string `json:"charge_unit_name,omitempty"` - // The charge unit quantity. + // The quantity associated with the charge unit to determine price change intervals. ChargeUnitQuantity *int64 `json:"charge_unit_quantity,omitempty"` - // Display name of the resource. + // The display name of the resource tied to the charge unit of this metric. ResourceDisplayName *string `json:"resource_display_name,omitempty"` - // Display name of the charge unit. + // Display name of the charge unit to be rendered human readable by the UI. ChargeUnitDisplayName *string `json:"charge_unit_display_name,omitempty"` - // Usage limit for the metric. + // Upper bound for the usage under the parent metric. UsageCapQty *int64 `json:"usage_cap_qty,omitempty"` - // Display capacity. + // The display capacity for the UI. DisplayCap *int64 `json:"display_cap,omitempty"` - // Effective from time. + // The end date-time indicating when this metric is no longer in effect. EffectiveFrom *strfmt.DateTime `json:"effective_from,omitempty"` - // Effective until time. + // The start date-time indicating when this metric takes effect. EffectiveUntil *strfmt.DateTime `json:"effective_until,omitempty"` // The pricing per metric by country and currency. Amounts []Amount `json:"amounts,omitempty"` + + // A property-bag like extension to metric metadata. + AdditionalProperties map[string]interface{} `json:"additional_properties,omitempty"` } // UnmarshalMetrics unmarshals an instance of Metrics from the specified map of raw messages. @@ -3800,13 +3909,19 @@ func UnmarshalMetrics(m map[string]json.RawMessage, result interface{}) (err err err = core.SDKErrorf(err, "", "amounts-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "additional_properties", &obj.AdditionalProperties) + if err != nil { + err = core.SDKErrorf(err, "", "additional_properties-error", common.GetComponentInfo()) + return + } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ObjectMetadataSet : Model used to describe metadata object that can be set. type ObjectMetadataSet struct { - // Boolean value that describes whether the service is compatible with the Resource Controller. + // Boolean value that describes whether the service is compatible with the Resource Controller. Only settable for + // deployments, propogated upward. RcCompatible *bool `json:"rc_compatible,omitempty"` // Service-related metadata. @@ -3836,7 +3951,8 @@ type ObjectMetadataSet struct { // The original name of the object. OriginalName *string `json:"original_name,omitempty"` - // Optional version of the object. + // Optional version of the object. Only valid for templates. + // Deprecated: this field is deprecated and may be removed in a future release. Version *string `json:"version,omitempty"` // Additional information. @@ -3984,32 +4100,45 @@ func UnmarshalOverview(m map[string]json.RawMessage, result interface{}) (err er // PlanMetaData : Plan-related metadata. type PlanMetaData struct { - // Boolean value that describes whether the service can be bound to an application. + // Boolean value that describes whether the service can be bound to an application. If true then this will create and + // use resource keys. Bindable *bool `json:"bindable,omitempty"` - // Boolean value that describes whether the service can be reserved. + // Boolean value that describes whether the service can be reserved for pricing subscriptions. Reservable *bool `json:"reservable,omitempty"` - // Boolean value that describes whether the service can be used internally. + // Boolean value that describes whether the service can be used on IBM accounts. If false this cannot be onboarded by + // an IBM account. AllowInternalUsers *bool `json:"allow_internal_users,omitempty"` - // Boolean value that describes whether the service can be provisioned asynchronously. + // Boolean value that describes whether the service supports asynchronous provisioning. Now handled by a 202 response + // indicating support from the broker on provisioning. + // Deprecated: this field is deprecated and may be removed in a future release. AsyncProvisioningSupported *bool `json:"async_provisioning_supported,omitempty"` - // Boolean value that describes whether the service can be unprovisioned asynchronously. + // Boolean value that describes whether the service supports asynchronous unprovisioning. Now handled by a 202 response + // indicating support from the broker on unprovisioning. + // Deprecated: this field is deprecated and may be removed in a future release. AsyncUnprovisioningSupported *bool `json:"async_unprovisioning_supported,omitempty"` - // Test check interval. + // How the subscription is provisioned (managed cloud service provider (mcsp), IBM_cloud, legacy). + ProvisionType *string `json:"provision_type,omitempty"` + + // A unit of time that determines the time in between uptime checks to be performed by the Estado testing service. + // Deprecated: this field is deprecated and may be removed in a future release. TestCheckInterval *int64 `json:"test_check_interval,omitempty"` - // Single scope instance. + // String denoting if a single instance is shared among a group of users. E.g. org. + // Deprecated: this field is deprecated and may be removed in a future release. SingleScopeInstance *string `json:"single_scope_instance,omitempty"` - // Boolean value that describes whether the service check is enabled. + // Boolean value that describes whether the Estado testing service will perform uptime tests for this service. + // Deprecated: this field is deprecated and may be removed in a future release. ServiceCheckEnabled *bool `json:"service_check_enabled,omitempty"` // If the field is imported from Cloud Foundry, the Cloud Foundry region's GUID. This is a required field. For example, // `us-south=123`. + // Deprecated: this field is deprecated and may be removed in a future release. CfGUID map[string]string `json:"cf_guid,omitempty"` } @@ -4041,6 +4170,11 @@ func UnmarshalPlanMetaData(m map[string]json.RawMessage, result interface{}) (er err = core.SDKErrorf(err, "", "async_unprovisioning_supported-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "provision_type", &obj.ProvisionType) + if err != nil { + err = core.SDKErrorf(err, "", "provision_type-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "test_check_interval", &obj.TestCheckInterval) if err != nil { err = core.SDKErrorf(err, "", "test_check_interval-error", common.GetComponentInfo()) @@ -4067,7 +4201,7 @@ func UnmarshalPlanMetaData(m map[string]json.RawMessage, result interface{}) (er // Price : Pricing-related information. type Price struct { - // Pricing tier. + // The quantity of _metric_ associated with the current price point. QuantityTier *int64 `json:"quantity_tier,omitempty"` // Price in the selected currency. @@ -4099,11 +4233,15 @@ type PricingGet struct { // The deployment location this pricing is from. Only set if object kind is deployment. DeploymentLocation *string `json:"deployment_location,omitempty"` + // If price is for a deployment object then the region in the pricing catalog of the deployment object will be here. To + // be valid, this value must be contained within deployment_regions. + DeploymentRegion *string `json:"deployment_region,omitempty"` + // Is the location price not available. Only set in api /pricing/deployment and only set if true. This means for the // given deployment object there was no pricing set in pricing catalog. DeploymentLocationNoPriceAvailable *bool `json:"deployment_location_no_price_available,omitempty"` - // Type of plan. Valid values are `free`, `trial`, `paygo`, `bluemix-subscription`, and `ibm-subscription`. + // Type of plan. Valid values are `free`, `trial`, `paygo`, `paid`, `subscription`. Type *string `json:"type,omitempty"` // Defines where the pricing originates. @@ -4117,6 +4255,22 @@ type PricingGet struct { // List of regions where region pricing is available. Only set on global deployments if enabled by owner. DeploymentRegions []string `json:"deployment_regions,omitempty"` + + // The start date-time indicating when this pricing plan takes effect. + EffectiveFrom *strfmt.DateTime `json:"effective_from,omitempty"` + + // The end date-time indicating when this pricing plan is no longer in effect. + EffectiveUntil *strfmt.DateTime `json:"effective_until,omitempty"` + + // Boolean value indicating whether or not this pricing plan requires login to get pricing data. + RequireLogin *bool `json:"require_login,omitempty"` + + // URL to the entry for this plan on the pricing catalog. + PricingCatalogURL *string `json:"pricing_catalog_url,omitempty"` + + // Tags describing how this plan was purchased (catalog [default], seller, private offer). Currently only settable on + // MCSP subscription plans. + SalesAvenue []string `json:"sales_avenue,omitempty"` } // UnmarshalPricingGet unmarshals an instance of PricingGet from the specified map of raw messages. @@ -4132,6 +4286,11 @@ func UnmarshalPricingGet(m map[string]json.RawMessage, result interface{}) (err err = core.SDKErrorf(err, "", "deployment_location-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "deployment_region", &obj.DeploymentRegion) + if err != nil { + err = core.SDKErrorf(err, "", "deployment_region-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "deployment_location_no_price_available", &obj.DeploymentLocationNoPriceAvailable) if err != nil { err = core.SDKErrorf(err, "", "deployment_location_no_price_available-error", common.GetComponentInfo()) @@ -4162,6 +4321,31 @@ func UnmarshalPricingGet(m map[string]json.RawMessage, result interface{}) (err err = core.SDKErrorf(err, "", "deployment_regions-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "effective_from", &obj.EffectiveFrom) + if err != nil { + err = core.SDKErrorf(err, "", "effective_from-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "effective_until", &obj.EffectiveUntil) + if err != nil { + err = core.SDKErrorf(err, "", "effective_until-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "require_login", &obj.RequireLogin) + if err != nil { + err = core.SDKErrorf(err, "", "require_login-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "pricing_catalog_url", &obj.PricingCatalogURL) + if err != nil { + err = core.SDKErrorf(err, "", "pricing_catalog_url-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "sales_avenue", &obj.SalesAvenue) + if err != nil { + err = core.SDKErrorf(err, "", "sales_avenue-error", common.GetComponentInfo()) + return + } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } @@ -4250,10 +4434,10 @@ func UnmarshalPricingSearchResult(m map[string]json.RawMessage, result interface // PricingSet : Pricing-related information. type PricingSet struct { - // Type of plan. Valid values are `free`, `trial`, `paygo`, `bluemix-subscription`, and `ibm-subscription`. + // Type of plan. Valid values are `free`, `trial`, `paygo`, `paid`, `subscription`. Type *string `json:"type,omitempty"` - // Defines where the pricing originates. + // Defines where the pricing originates, either the pricing catalog or the global catalog. Origin *string `json:"origin,omitempty"` // Plan-specific starting price information. @@ -4585,7 +4769,7 @@ type TemplateMetaData struct { // Cloud Foundry instance memory value. DefaultMemory *int64 `json:"default_memory,omitempty"` - // Start Command. + // Command used to start a service. StartCmd *string `json:"start_cmd,omitempty"` // Location of your applications source files. @@ -4725,7 +4909,7 @@ type UIMetaData struct { // Date and time the service will no longer be available. EndOfServiceTime *strfmt.DateTime `json:"end_of_service_time,omitempty"` - // Denotes visibility. + // Denotes visibility. Can be set on a service/plan/deployment only by an account with bluemix admin privileges. Hidden *bool `json:"hidden,omitempty"` // Denotes lite metering visibility. @@ -4877,10 +5061,10 @@ type Urls struct { // URL to the terms of use for your service. TermsURL *string `json:"terms_url,omitempty"` - // URL to the custom create page for your serivce. + // URL to the custom create page for your service. CustomCreatePageURL *string `json:"custom_create_page_url,omitempty"` - // URL to the catalog details page for your serivce. + // URL to the catalog details page for your service. CatalogDetailsURL *string `json:"catalog_details_url,omitempty"` // URL for deprecation documentation. @@ -4972,8 +5156,8 @@ type UpdateCatalogEntryOptions struct { // OverviewUI for a user-readable name. Name *string `json:"name" validate:"required"` - // The type of catalog entry, **service**, **template**, **dashboard**, which determines the type and shape of the - // object. + // The type of catalog entry which determines the type and shape of the object. Valid GC types are buildpack, cname, + // dataset, geography, iaas, platform_service, runtime, service, template, ui-dashboard. Kind *string `json:"kind" validate:"required"` // Overview is nested in the top level. The key value pair is `[_language_]overview_ui`. @@ -4986,7 +5170,8 @@ type UpdateCatalogEntryOptions struct { // all plans are disabled. Disabled *bool `json:"disabled" validate:"required"` - // A list of tags. For example, IBM, 3rd Party, Beta, GA, and Single Tenant. + // A searchable list of tags. For example, IBM, 3rd Party, Beta, GA, and Single Tenant. Valid values found at + // https://globalcatalog.test.cloud.ibm.com/search. Tags []string `json:"tags" validate:"required"` // Information related to the provider associated with a catalog entry. @@ -5023,8 +5208,8 @@ type UpdateCatalogEntryOptions struct { } // Constants associated with the UpdateCatalogEntryOptions.Kind property. -// The type of catalog entry, **service**, **template**, **dashboard**, which determines the type and shape of the -// object. +// The type of catalog entry which determines the type and shape of the object. Valid GC types are buildpack, cname, +// dataset, geography, iaas, platform_service, runtime, service, template, ui-dashboard. const ( UpdateCatalogEntryOptionsKindDashboardConst = "dashboard" UpdateCatalogEntryOptionsKindServiceConst = "service" @@ -5146,7 +5331,13 @@ type UpdateVisibilityOptions struct { // The object's unique ID. ID *string `json:"id" validate:"required,ne="` - // Allows the visibility to be extenable. + // This controls the overall visibility. It is an enum of *public*, *nonibm_only*, *ibm_only*, and *private*. public + // means it is visible to all. nonibm_only means it is visible to all except IBM unless their account is explicitly + // included, ibm_only means it is visible to all IBM unless their account is explicitly excluded. private means it is + // visible only to the included accounts. + Restrictions *string `json:"restrictions,omitempty"` + + // Allows the visibility to be extendable. Extendable *bool `json:"extendable,omitempty"` // Visibility details related to a catalog entry. @@ -5177,6 +5368,12 @@ func (_options *UpdateVisibilityOptions) SetID(id string) *UpdateVisibilityOptio return _options } +// SetRestrictions : Allow user to set Restrictions +func (_options *UpdateVisibilityOptions) SetRestrictions(restrictions string) *UpdateVisibilityOptions { + _options.Restrictions = core.StringPtr(restrictions) + return _options +} + // SetExtendable : Allow user to set Extendable func (_options *UpdateVisibilityOptions) SetExtendable(extendable bool) *UpdateVisibilityOptions { _options.Extendable = core.BoolPtr(extendable) @@ -5275,15 +5472,16 @@ func (options *UploadArtifactOptions) SetHeaders(param map[string]string) *Uploa // Visibility : Information related to the visibility of a catalog entry. type Visibility struct { - // This controls the overall visibility. It is an enum of *public*, *ibm_only*, and *private*. public means it is - // visible to all. ibm_only means it is visible to all IBM unless their account is explicitly excluded. private means - // it is visible only to the included accounts. + // This controls the overall visibility. It is an enum of *public*, *nonibm_only*, *ibm_only*, and *private*. public + // means it is visible to all. nonibm_only means it is visible to all except IBM unless their account is explicitly + // included, ibm_only means it is visible to all IBM unless their account is explicitly excluded. private means it is + // visible only to the included accounts. Restrictions *string `json:"restrictions,omitempty"` // IAM Scope-related information associated with a catalog entry. Owner *string `json:"owner,omitempty"` - // Allows the visibility to be extenable. + // Allows the visibility to be extendable. Extendable *bool `json:"extendable,omitempty"` // Visibility details related to a catalog entry. @@ -5293,7 +5491,7 @@ type Visibility struct { Exclude *VisibilityDetail `json:"exclude,omitempty"` // Determines whether the owning account has full control over the visibility of the entry such as adding non-IBM - // accounts to the whitelist and making entries `private`, `ibm_only` or `public`. + // accounts to the whitelist and making entries `private`, `nonibm_only`, `ibm_only` or `public`. Approved *bool `json:"approved,omitempty"` } diff --git a/vendor/github.com/IBM/platform-services-go-sdk/globaltaggingv1/global_tagging_v1.go b/vendor/github.com/IBM/platform-services-go-sdk/globaltaggingv1/global_tagging_v1.go index e89302f99d4f..01bd969b0212 100644 --- a/vendor/github.com/IBM/platform-services-go-sdk/globaltaggingv1/global_tagging_v1.go +++ b/vendor/github.com/IBM/platform-services-go-sdk/globaltaggingv1/global_tagging_v1.go @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2024. + * (C) Copyright IBM Corp. 2025. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ /* - * IBM OpenAPI SDK Code Generator Version: 3.87.0-91c7c775-20240320-213027 + * IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 */ // Package globaltaggingv1 : Operations and models for the GlobalTaggingV1 service @@ -39,9 +39,9 @@ import ( // create tags in two formats: `key:value` or `label`. The tagging API supports three types of tag: `user` `service`, // and `access` tags. `service` tags cannot be attached to IMS resources. `service` tags must be in the form // `service_prefix:tag_label` where `service_prefix` identifies the Service owning the tag. `access` tags cannot be -// attached to IMS and Cloud Foundry resources. They must be in the form `key:value`. You can replace all resource's -// tags using the `replace` query parameter in the attach operation. You can update the `value` of a resource's tag in -// the format `key:value`, using the `update` query parameter in the attach operation. +// attached to IMS resources. They must be in the form `key:value`. You can replace all resource's tags using the +// `replace` query parameter in the attach operation. You can update the `value` of a resource's tag in the format +// `key:value`, using the `update` query parameter in the attach operation. // // API Version: 1.2.0 type GlobalTaggingV1 struct { @@ -589,15 +589,18 @@ func (globalTagging *GlobalTaggingV1) AttachTagWithContext(ctx context.Context, } body := make(map[string]interface{}) - if attachTagOptions.Resources != nil { - body["resources"] = attachTagOptions.Resources - } if attachTagOptions.TagName != nil { body["tag_name"] = attachTagOptions.TagName } if attachTagOptions.TagNames != nil { body["tag_names"] = attachTagOptions.TagNames } + if attachTagOptions.Resources != nil { + body["resources"] = attachTagOptions.Resources + } + if attachTagOptions.Query != nil { + body["query"] = attachTagOptions.Query + } _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) @@ -684,15 +687,18 @@ func (globalTagging *GlobalTaggingV1) DetachTagWithContext(ctx context.Context, } body := make(map[string]interface{}) - if detachTagOptions.Resources != nil { - body["resources"] = detachTagOptions.Resources - } if detachTagOptions.TagName != nil { body["tag_name"] = detachTagOptions.TagName } if detachTagOptions.TagNames != nil { body["tag_names"] = detachTagOptions.TagNames } + if detachTagOptions.Resources != nil { + body["resources"] = detachTagOptions.Resources + } + if detachTagOptions.Query != nil { + body["query"] = detachTagOptions.Query + } _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) @@ -729,15 +735,18 @@ func getServiceComponentInfo() *core.ProblemComponent { // AttachTagOptions : The AttachTag options. type AttachTagOptions struct { - // List of resources on which the tag or tags are attached. - Resources []Resource `json:"resources" validate:"required"` - // The name of the tag to attach. TagName *string `json:"tag_name,omitempty"` // An array of tag names to attach. TagNames []string `json:"tag_names,omitempty"` + // List of resources on which the tagging operation operates on. + Resources []Resource `json:"resources,omitempty"` + + // A valid Global Search string. + Query *QueryString `json:"query,omitempty"` + // An alphanumeric string that is used to trace the request. The value may include ASCII alphanumerics and any of // following segment separators: space ( ), comma (,), hyphen, (-), and underscore (_) and may have a length up to 1024 // bytes. The value is considered invalid and must be ignored if that value includes any other character or is longer @@ -772,7 +781,7 @@ type AttachTagOptions struct { // usual. The update query parameter is available for user and access management tags, but not for service tags. Update *bool `json:"update,omitempty"` - // Allows users to set headers on API requests + // Allows users to set headers on API requests. Headers map[string]string } @@ -780,22 +789,14 @@ type AttachTagOptions struct { // The type of the tag. Supported values are `user`, `service` and `access`. `service` and `access` are not supported // for IMS resources. const ( - AttachTagOptionsTagTypeAccessConst = "access" + AttachTagOptionsTagTypeAccessConst = "access" AttachTagOptionsTagTypeServiceConst = "service" - AttachTagOptionsTagTypeUserConst = "user" + AttachTagOptionsTagTypeUserConst = "user" ) // NewAttachTagOptions : Instantiate AttachTagOptions -func (*GlobalTaggingV1) NewAttachTagOptions(resources []Resource) *AttachTagOptions { - return &AttachTagOptions{ - Resources: resources, - } -} - -// SetResources : Allow user to set Resources -func (_options *AttachTagOptions) SetResources(resources []Resource) *AttachTagOptions { - _options.Resources = resources - return _options +func (*GlobalTaggingV1) NewAttachTagOptions() *AttachTagOptions { + return &AttachTagOptions{} } // SetTagName : Allow user to set TagName @@ -810,6 +811,18 @@ func (_options *AttachTagOptions) SetTagNames(tagNames []string) *AttachTagOptio return _options } +// SetResources : Allow user to set Resources +func (_options *AttachTagOptions) SetResources(resources []Resource) *AttachTagOptions { + _options.Resources = resources + return _options +} + +// SetQuery : Allow user to set Query +func (_options *AttachTagOptions) SetQuery(query *QueryString) *AttachTagOptions { + _options.Query = query + return _options +} + // SetXRequestID : Allow user to set XRequestID func (_options *AttachTagOptions) SetXRequestID(xRequestID string) *AttachTagOptions { _options.XRequestID = core.StringPtr(xRequestID) @@ -878,7 +891,7 @@ type CreateTagOptions struct { // The type of the tags you want to create. The only allowed value is `access`. TagType *string `json:"tag_type,omitempty"` - // Allows users to set headers on API requests + // Allows users to set headers on API requests. Headers map[string]string } @@ -1003,7 +1016,7 @@ type DeleteTagAllOptions struct { // for IMS resources (`providers` parameter set to `ims`). TagType *string `json:"tag_type,omitempty"` - // Allows users to set headers on API requests + // Allows users to set headers on API requests. Headers map[string]string } @@ -1011,16 +1024,16 @@ type DeleteTagAllOptions struct { // Select a provider. Supported values are `ghost` and `ims`. const ( DeleteTagAllOptionsProvidersGhostConst = "ghost" - DeleteTagAllOptionsProvidersImsConst = "ims" + DeleteTagAllOptionsProvidersImsConst = "ims" ) // Constants associated with the DeleteTagAllOptions.TagType property. // The type of the tag. Supported values are `user`, `service` and `access`. `service` and `access` are not supported // for IMS resources (`providers` parameter set to `ims`). const ( - DeleteTagAllOptionsTagTypeAccessConst = "access" + DeleteTagAllOptionsTagTypeAccessConst = "access" DeleteTagAllOptionsTagTypeServiceConst = "service" - DeleteTagAllOptionsTagTypeUserConst = "user" + DeleteTagAllOptionsTagTypeUserConst = "user" ) // NewDeleteTagAllOptions : Instantiate DeleteTagAllOptions @@ -1096,23 +1109,23 @@ type DeleteTagOptions struct { // for IMS resources (`providers` parameter set to `ims`). TagType *string `json:"tag_type,omitempty"` - // Allows users to set headers on API requests + // Allows users to set headers on API requests. Headers map[string]string } // Constants associated with the DeleteTagOptions.Providers property. const ( DeleteTagOptionsProvidersGhostConst = "ghost" - DeleteTagOptionsProvidersImsConst = "ims" + DeleteTagOptionsProvidersImsConst = "ims" ) // Constants associated with the DeleteTagOptions.TagType property. // The type of the tag. Supported values are `user`, `service` and `access`. `service` and `access` are not supported // for IMS resources (`providers` parameter set to `ims`). const ( - DeleteTagOptionsTagTypeAccessConst = "access" + DeleteTagOptionsTagTypeAccessConst = "access" DeleteTagOptionsTagTypeServiceConst = "service" - DeleteTagOptionsTagTypeUserConst = "user" + DeleteTagOptionsTagTypeUserConst = "user" ) // NewDeleteTagOptions : Instantiate DeleteTagOptions @@ -1183,6 +1196,7 @@ func UnmarshalDeleteTagResults(m map[string]json.RawMessage, result interface{}) } // DeleteTagResultsItem : Result of a delete_tag request. +// This type supports additional properties of type interface{}. type DeleteTagResultsItem struct { // The provider of the tag. Provider *string `json:"provider,omitempty"` @@ -1190,7 +1204,7 @@ type DeleteTagResultsItem struct { // It is `true` if the operation exits with an error (for example, the tag does not exist). IsError *bool `json:"is_error,omitempty"` - // Allows users to set arbitrary properties + // Allows users to set arbitrary properties of type interface{}. additionalProperties map[string]interface{} } @@ -1198,10 +1212,10 @@ type DeleteTagResultsItem struct { // The provider of the tag. const ( DeleteTagResultsItemProviderGhostConst = "ghost" - DeleteTagResultsItemProviderImsConst = "ims" + DeleteTagResultsItemProviderImsConst = "ims" ) -// SetProperty allows the user to set an arbitrary property on an instance of DeleteTagResultsItem +// SetProperty allows the user to set an arbitrary property on an instance of DeleteTagResultsItem. func (o *DeleteTagResultsItem) SetProperty(key string, value interface{}) { if o.additionalProperties == nil { o.additionalProperties = make(map[string]interface{}) @@ -1209,7 +1223,7 @@ func (o *DeleteTagResultsItem) SetProperty(key string, value interface{}) { o.additionalProperties[key] = value } -// SetProperties allows the user to set a map of arbitrary properties on an instance of DeleteTagResultsItem +// SetProperties allows the user to set a map of arbitrary properties on an instance of DeleteTagResultsItem. func (o *DeleteTagResultsItem) SetProperties(m map[string]interface{}) { o.additionalProperties = make(map[string]interface{}) for k, v := range m { @@ -1217,12 +1231,12 @@ func (o *DeleteTagResultsItem) SetProperties(m map[string]interface{}) { } } -// GetProperty allows the user to retrieve an arbitrary property from an instance of DeleteTagResultsItem +// GetProperty allows the user to retrieve an arbitrary property from an instance of DeleteTagResultsItem. func (o *DeleteTagResultsItem) GetProperty(key string) interface{} { return o.additionalProperties[key] } -// GetProperties allows the user to retrieve the map of arbitrary properties from an instance of DeleteTagResultsItem +// GetProperties allows the user to retrieve the map of arbitrary properties from an instance of DeleteTagResultsItem. func (o *DeleteTagResultsItem) GetProperties() map[string]interface{} { return o.additionalProperties } @@ -1338,15 +1352,18 @@ func UnmarshalDeleteTagsResultItem(m map[string]json.RawMessage, result interfac // DetachTagOptions : The DetachTag options. type DetachTagOptions struct { - // List of resources on which the tag or tags are detached. - Resources []Resource `json:"resources" validate:"required"` - // The name of the tag to detach. TagName *string `json:"tag_name,omitempty"` // An array of tag names to detach. TagNames []string `json:"tag_names,omitempty"` + // List of resources on which the tagging operation operates on. + Resources []Resource `json:"resources,omitempty"` + + // A valid Global Search string. + Query *QueryString `json:"query,omitempty"` + // An alphanumeric string that is used to trace the request. The value may include ASCII alphanumerics and any of // following segment separators: space ( ), comma (,), hyphen, (-), and underscore (_) and may have a length up to 1024 // bytes. The value is considered invalid and must be ignored if that value includes any other character or is longer @@ -1370,7 +1387,7 @@ type DetachTagOptions struct { // for IMS resources. TagType *string `json:"tag_type,omitempty"` - // Allows users to set headers on API requests + // Allows users to set headers on API requests. Headers map[string]string } @@ -1378,22 +1395,14 @@ type DetachTagOptions struct { // The type of the tag. Supported values are `user`, `service` and `access`. `service` and `access` are not supported // for IMS resources. const ( - DetachTagOptionsTagTypeAccessConst = "access" + DetachTagOptionsTagTypeAccessConst = "access" DetachTagOptionsTagTypeServiceConst = "service" - DetachTagOptionsTagTypeUserConst = "user" + DetachTagOptionsTagTypeUserConst = "user" ) // NewDetachTagOptions : Instantiate DetachTagOptions -func (*GlobalTaggingV1) NewDetachTagOptions(resources []Resource) *DetachTagOptions { - return &DetachTagOptions{ - Resources: resources, - } -} - -// SetResources : Allow user to set Resources -func (_options *DetachTagOptions) SetResources(resources []Resource) *DetachTagOptions { - _options.Resources = resources - return _options +func (*GlobalTaggingV1) NewDetachTagOptions() *DetachTagOptions { + return &DetachTagOptions{} } // SetTagName : Allow user to set TagName @@ -1408,6 +1417,18 @@ func (_options *DetachTagOptions) SetTagNames(tagNames []string) *DetachTagOptio return _options } +// SetResources : Allow user to set Resources +func (_options *DetachTagOptions) SetResources(resources []Resource) *DetachTagOptions { + _options.Resources = resources + return _options +} + +// SetQuery : Allow user to set Query +func (_options *DetachTagOptions) SetQuery(query *QueryString) *DetachTagOptions { + _options.Query = query + return _options +} + // SetXRequestID : Allow user to set XRequestID func (_options *DetachTagOptions) SetXRequestID(xRequestID string) *DetachTagOptions { _options.XRequestID = core.StringPtr(xRequestID) @@ -1494,28 +1515,28 @@ type ListTagsOptions struct { // returns all tags. AttachedOnly *bool `json:"attached_only,omitempty"` - // Allows users to set headers on API requests + // Allows users to set headers on API requests. Headers map[string]string } // Constants associated with the ListTagsOptions.TagType property. // The type of the tag you want to list. Supported values are `user`, `service` and `access`. const ( - ListTagsOptionsTagTypeAccessConst = "access" + ListTagsOptionsTagTypeAccessConst = "access" ListTagsOptionsTagTypeServiceConst = "service" - ListTagsOptionsTagTypeUserConst = "user" + ListTagsOptionsTagTypeUserConst = "user" ) // Constants associated with the ListTagsOptions.Providers property. const ( ListTagsOptionsProvidersGhostConst = "ghost" - ListTagsOptionsProvidersImsConst = "ims" + ListTagsOptionsProvidersImsConst = "ims" ) // Constants associated with the ListTagsOptions.OrderByName property. // Order the output by tag name. const ( - ListTagsOptionsOrderByNameAscConst = "asc" + ListTagsOptionsOrderByNameAscConst = "asc" ListTagsOptionsOrderByNameDescConst = "desc" ) @@ -1602,12 +1623,45 @@ func (options *ListTagsOptions) SetHeaders(param map[string]string) *ListTagsOpt return options } +// QueryString : A valid Global Search string. +type QueryString struct { + // The Lucene-formatted query string. + QueryString *string `json:"query_string" validate:"required"` +} + +// NewQueryString : Instantiate QueryString (Generic Model Constructor) +func (*GlobalTaggingV1) NewQueryString(queryString string) (_model *QueryString, err error) { + _model = &QueryString{ + QueryString: core.StringPtr(queryString), + } + err = core.ValidateStruct(_model, "required parameters") + if err != nil { + err = core.SDKErrorf(err, "", "model-missing-required", common.GetComponentInfo()) + } + return +} + +// UnmarshalQueryString unmarshals an instance of QueryString from the specified map of raw messages. +func UnmarshalQueryString(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(QueryString) + err = core.UnmarshalPrimitive(m, "query_string", &obj.QueryString) + if err != nil { + err = core.SDKErrorf(err, "", "query_string-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // Resource : A resource that might have tags that are attached. type Resource struct { // The CRN or IMS ID of the resource. ResourceID *string `json:"resource_id" validate:"required"` - // The IMS resource type of the resource. + // The IMS resource type of the resource. It can be one of SoftLayer_Virtual_DedicatedHost, SoftLayer_Hardware, + // SoftLayer_Hardware_Server, SoftLayer_Network_Application_Delivery_Controller, SoftLayer_Network_Vlan, + // SoftLayer_Network_Vlan_Firewall, SoftLayer_Network_Component_Firewall, SoftLayer_Network_Firewall_Module_Context, + // SoftLayer_Virtual_Guest. ResourceType *string `json:"resource_type,omitempty"` } diff --git a/vendor/github.com/IBM/platform-services-go-sdk/iamidentityv1/iam_identity_v1.go b/vendor/github.com/IBM/platform-services-go-sdk/iamidentityv1/iam_identity_v1.go index 35a757193bc3..7a0cfc7f283b 100644 --- a/vendor/github.com/IBM/platform-services-go-sdk/iamidentityv1/iam_identity_v1.go +++ b/vendor/github.com/IBM/platform-services-go-sdk/iamidentityv1/iam_identity_v1.go @@ -15,7 +15,7 @@ */ /* - * IBM OpenAPI SDK Code Generator Version: 3.103.0-e8b84313-20250402-201816 + * IBM OpenAPI SDK Code Generator Version: 3.106.0-09823488-20250707-071701 */ // Package iamidentityv1 : Operations and models for the IamIdentityV1 service @@ -171,18 +171,19 @@ func (iamIdentity *IamIdentityV1) DisableRetries() { iamIdentity.Service.DisableRetries() } -// ListAPIKeys : Get API keys for a given service or user IAM ID and account ID -// Returns the list of API key details for a given service or user IAM ID and account ID. Users can manage user API keys -// for themself, or service ID API keys for service IDs they have access to. -func (iamIdentity *IamIdentityV1) ListAPIKeys(listAPIKeysOptions *ListAPIKeysOptions) (result *APIKeyList, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.ListAPIKeysWithContext(context.Background(), listAPIKeysOptions) +// ListServiceIds : List service IDs +// Returns a list of service IDs. Users can manage user API keys for themself, or service ID API keys for service IDs +// they have access to. Note: apikey details are only included in the response when creating a Service ID with an api +// key. +func (iamIdentity *IamIdentityV1) ListServiceIds(listServiceIdsOptions *ListServiceIdsOptions) (result *ServiceIDList, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListServiceIdsWithContext(context.Background(), listServiceIdsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListAPIKeysWithContext is an alternate form of the ListAPIKeys method which supports a Context parameter -func (iamIdentity *IamIdentityV1) ListAPIKeysWithContext(ctx context.Context, listAPIKeysOptions *ListAPIKeysOptions) (result *APIKeyList, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listAPIKeysOptions, "listAPIKeysOptions") +// ListServiceIdsWithContext is an alternate form of the ListServiceIds method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListServiceIdsWithContext(ctx context.Context, listServiceIdsOptions *ListServiceIdsOptions) (result *ServiceIDList, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listServiceIdsOptions, "listServiceIdsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -191,51 +192,51 @@ func (iamIdentity *IamIdentityV1) ListAPIKeysWithContext(ctx context.Context, li builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listAPIKeysOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListServiceIds") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListAPIKeys") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listServiceIdsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if listAPIKeysOptions.AccountID != nil { - builder.AddQuery("account_id", fmt.Sprint(*listAPIKeysOptions.AccountID)) + if listServiceIdsOptions.AccountID != nil { + builder.AddQuery("account_id", fmt.Sprint(*listServiceIdsOptions.AccountID)) } - if listAPIKeysOptions.IamID != nil { - builder.AddQuery("iam_id", fmt.Sprint(*listAPIKeysOptions.IamID)) + if listServiceIdsOptions.GroupID != nil { + builder.AddQuery("group_id", fmt.Sprint(*listServiceIdsOptions.GroupID)) } - if listAPIKeysOptions.Pagesize != nil { - builder.AddQuery("pagesize", fmt.Sprint(*listAPIKeysOptions.Pagesize)) + if listServiceIdsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listServiceIdsOptions.Name)) } - if listAPIKeysOptions.Pagetoken != nil { - builder.AddQuery("pagetoken", fmt.Sprint(*listAPIKeysOptions.Pagetoken)) + if listServiceIdsOptions.Pagesize != nil { + builder.AddQuery("pagesize", fmt.Sprint(*listServiceIdsOptions.Pagesize)) } - if listAPIKeysOptions.Scope != nil { - builder.AddQuery("scope", fmt.Sprint(*listAPIKeysOptions.Scope)) + if listServiceIdsOptions.Pagetoken != nil { + builder.AddQuery("pagetoken", fmt.Sprint(*listServiceIdsOptions.Pagetoken)) } - if listAPIKeysOptions.Type != nil { - builder.AddQuery("type", fmt.Sprint(*listAPIKeysOptions.Type)) + if listServiceIdsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listServiceIdsOptions.Sort)) } - if listAPIKeysOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listAPIKeysOptions.Sort)) + if listServiceIdsOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listServiceIdsOptions.Order)) } - if listAPIKeysOptions.Order != nil { - builder.AddQuery("order", fmt.Sprint(*listAPIKeysOptions.Order)) + if listServiceIdsOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*listServiceIdsOptions.IncludeHistory)) } - if listAPIKeysOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*listAPIKeysOptions.IncludeHistory)) + if listServiceIdsOptions.Filter != nil { + builder.AddQuery("filter", fmt.Sprint(*listServiceIdsOptions.Filter)) } - if listAPIKeysOptions.Filter != nil { - builder.AddQuery("filter", fmt.Sprint(*listAPIKeysOptions.Filter)) + if listServiceIdsOptions.ShowGroupID != nil { + builder.AddQuery("show_group_id", fmt.Sprint(*listServiceIdsOptions.ShowGroupID)) } request, err := builder.Build() @@ -247,12 +248,12 @@ func (iamIdentity *IamIdentityV1) ListAPIKeysWithContext(ctx context.Context, li var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_api_keys", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_service_ids", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKeyList) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceIDList) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -263,23 +264,23 @@ func (iamIdentity *IamIdentityV1) ListAPIKeysWithContext(ctx context.Context, li return } -// CreateAPIKey : Create an API key -// Creates an API key for a UserID or service ID. Users can manage user API keys for themself, or service ID API keys +// CreateServiceID : Create a service ID +// Creates a service ID for an IBM Cloud account. Users can manage user API keys for themself, or service ID API keys // for service IDs they have access to. -func (iamIdentity *IamIdentityV1) CreateAPIKey(createAPIKeyOptions *CreateAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateAPIKeyWithContext(context.Background(), createAPIKeyOptions) +func (iamIdentity *IamIdentityV1) CreateServiceID(createServiceIDOptions *CreateServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateServiceIDWithContext(context.Background(), createServiceIDOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateAPIKeyWithContext is an alternate form of the CreateAPIKey method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateAPIKeyWithContext(ctx context.Context, createAPIKeyOptions *CreateAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createAPIKeyOptions, "createAPIKeyOptions cannot be nil") +// CreateServiceIDWithContext is an alternate form of the CreateServiceID method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateServiceIDWithContext(ctx context.Context, createServiceIDOptions *CreateServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createServiceIDOptions, "createServiceIDOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createAPIKeyOptions, "createAPIKeyOptions") + err = core.ValidateStruct(createServiceIDOptions, "createServiceIDOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -288,53 +289,48 @@ func (iamIdentity *IamIdentityV1) CreateAPIKeyWithContext(ctx context.Context, c builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createAPIKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateServiceID") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateAPIKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createServiceIDOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") - if createAPIKeyOptions.EntityLock != nil { - builder.AddHeader("Entity-Lock", fmt.Sprint(*createAPIKeyOptions.EntityLock)) + if createServiceIDOptions.EntityLock != nil { + builder.AddHeader("Entity-Lock", fmt.Sprint(*createServiceIDOptions.EntityLock)) } - if createAPIKeyOptions.EntityDisable != nil { - builder.AddHeader("Entity-Disable", fmt.Sprint(*createAPIKeyOptions.EntityDisable)) + + if createServiceIDOptions.ShowGroupID != nil { + builder.AddQuery("show_group_id", fmt.Sprint(*createServiceIDOptions.ShowGroupID)) } body := make(map[string]interface{}) - if createAPIKeyOptions.Name != nil { - body["name"] = createAPIKeyOptions.Name - } - if createAPIKeyOptions.IamID != nil { - body["iam_id"] = createAPIKeyOptions.IamID - } - if createAPIKeyOptions.Description != nil { - body["description"] = createAPIKeyOptions.Description + if createServiceIDOptions.AccountID != nil { + body["account_id"] = createServiceIDOptions.AccountID } - if createAPIKeyOptions.AccountID != nil { - body["account_id"] = createAPIKeyOptions.AccountID + if createServiceIDOptions.Name != nil { + body["name"] = createServiceIDOptions.Name } - if createAPIKeyOptions.Apikey != nil { - body["apikey"] = createAPIKeyOptions.Apikey + if createServiceIDOptions.GroupID != nil { + body["group_id"] = createServiceIDOptions.GroupID } - if createAPIKeyOptions.StoreValue != nil { - body["store_value"] = createAPIKeyOptions.StoreValue + if createServiceIDOptions.Description != nil { + body["description"] = createServiceIDOptions.Description } - if createAPIKeyOptions.SupportSessions != nil { - body["support_sessions"] = createAPIKeyOptions.SupportSessions + if createServiceIDOptions.UniqueInstanceCrns != nil { + body["unique_instance_crns"] = createServiceIDOptions.UniqueInstanceCrns } - if createAPIKeyOptions.ActionWhenLeaked != nil { - body["action_when_leaked"] = createAPIKeyOptions.ActionWhenLeaked + if createServiceIDOptions.Apikey != nil { + body["apikey"] = createServiceIDOptions.Apikey } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -351,12 +347,12 @@ func (iamIdentity *IamIdentityV1) CreateAPIKeyWithContext(ctx context.Context, c var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_api_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_service_id", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKey) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceID) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -367,47 +363,60 @@ func (iamIdentity *IamIdentityV1) CreateAPIKeyWithContext(ctx context.Context, c return } -// GetAPIKeysDetails : Get details of an API key by its value -// Returns the details of an API key by its value. Users can manage user API keys for themself, or service ID API keys -// for service IDs they have access to. -func (iamIdentity *IamIdentityV1) GetAPIKeysDetails(getAPIKeysDetailsOptions *GetAPIKeysDetailsOptions) (result *APIKey, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetAPIKeysDetailsWithContext(context.Background(), getAPIKeysDetailsOptions) +// GetServiceID : Get details of a service ID +// Returns the details of a service ID. Users can manage user API keys for themself, or service ID API keys for service +// IDs they have access to. Note: apikey details are only included in the response when creating a Service ID with an +// api key. +func (iamIdentity *IamIdentityV1) GetServiceID(getServiceIDOptions *GetServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetServiceIDWithContext(context.Background(), getServiceIDOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetAPIKeysDetailsWithContext is an alternate form of the GetAPIKeysDetails method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetAPIKeysDetailsWithContext(ctx context.Context, getAPIKeysDetailsOptions *GetAPIKeysDetailsOptions) (result *APIKey, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(getAPIKeysDetailsOptions, "getAPIKeysDetailsOptions") +// GetServiceIDWithContext is an alternate form of the GetServiceID method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetServiceIDWithContext(ctx context.Context, getServiceIDOptions *GetServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getServiceIDOptions, "getServiceIDOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getServiceIDOptions, "getServiceIDOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "id": *getServiceIDOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/details`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getAPIKeysDetailsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetServiceID") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAPIKeysDetails") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getServiceIDOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if getAPIKeysDetailsOptions.IamAPIKey != nil { - builder.AddHeader("IAM-ApiKey", fmt.Sprint(*getAPIKeysDetailsOptions.IamAPIKey)) - } - if getAPIKeysDetailsOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getAPIKeysDetailsOptions.IncludeHistory)) + if getServiceIDOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getServiceIDOptions.IncludeHistory)) + } + if getServiceIDOptions.IncludeActivity != nil { + builder.AddQuery("include_activity", fmt.Sprint(*getServiceIDOptions.IncludeActivity)) + } + if getServiceIDOptions.ShowGroupID != nil { + builder.AddQuery("show_group_id", fmt.Sprint(*getServiceIDOptions.ShowGroupID)) } request, err := builder.Build() @@ -419,12 +428,12 @@ func (iamIdentity *IamIdentityV1) GetAPIKeysDetailsWithContext(ctx context.Conte var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_api_keys_details", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_service_id", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKey) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceID) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -435,56 +444,76 @@ func (iamIdentity *IamIdentityV1) GetAPIKeysDetailsWithContext(ctx context.Conte return } -// GetAPIKey : Get details of an API key -// Returns the details of an API key. Users can manage user API keys for themself, or service ID API keys for service -// IDs they have access to. -func (iamIdentity *IamIdentityV1) GetAPIKey(getAPIKeyOptions *GetAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetAPIKeyWithContext(context.Background(), getAPIKeyOptions) +// UpdateServiceID : Update service ID +// Updates properties of a service ID. This does NOT affect existing access tokens. Their token content will stay +// unchanged until the access token is refreshed. To update a service ID, pass the property to be modified. To delete +// one property's value, pass the property with an empty value "".Users can manage user API keys for themself, or +// service ID API keys for service IDs they have access to. Note: apikey details are only included in the response when +// creating a Service ID with an apikey. +func (iamIdentity *IamIdentityV1) UpdateServiceID(updateServiceIDOptions *UpdateServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdateServiceIDWithContext(context.Background(), updateServiceIDOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetAPIKeyWithContext is an alternate form of the GetAPIKey method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetAPIKeyWithContext(ctx context.Context, getAPIKeyOptions *GetAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getAPIKeyOptions, "getAPIKeyOptions cannot be nil") +// UpdateServiceIDWithContext is an alternate form of the UpdateServiceID method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdateServiceIDWithContext(ctx context.Context, updateServiceIDOptions *UpdateServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateServiceIDOptions, "updateServiceIDOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getAPIKeyOptions, "getAPIKeyOptions") + err = core.ValidateStruct(updateServiceIDOptions, "updateServiceIDOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getAPIKeyOptions.ID, + "id": *updateServiceIDOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getAPIKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateServiceID") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAPIKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateServiceIDOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + if updateServiceIDOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateServiceIDOptions.IfMatch)) + } - if getAPIKeyOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getAPIKeyOptions.IncludeHistory)) + if updateServiceIDOptions.ShowGroupID != nil { + builder.AddQuery("show_group_id", fmt.Sprint(*updateServiceIDOptions.ShowGroupID)) } - if getAPIKeyOptions.IncludeActivity != nil { - builder.AddQuery("include_activity", fmt.Sprint(*getAPIKeyOptions.IncludeActivity)) + + body := make(map[string]interface{}) + if updateServiceIDOptions.Name != nil { + body["name"] = updateServiceIDOptions.Name + } + if updateServiceIDOptions.Description != nil { + body["description"] = updateServiceIDOptions.Description + } + if updateServiceIDOptions.UniqueInstanceCrns != nil { + body["unique_instance_crns"] = updateServiceIDOptions.UniqueInstanceCrns + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -496,12 +525,12 @@ func (iamIdentity *IamIdentityV1) GetAPIKeyWithContext(ctx context.Context, getA var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_api_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_service_id", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKey) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceID) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -512,74 +541,50 @@ func (iamIdentity *IamIdentityV1) GetAPIKeyWithContext(ctx context.Context, getA return } -// UpdateAPIKey : Updates an API key -// Updates properties of an API key. This does NOT affect existing access tokens. Their token content will stay -// unchanged until the access token is refreshed. To update an API key, pass the property to be modified. To delete one -// property's value, pass the property with an empty value "". Users can manage user API keys for themself, or service -// ID API keys for service IDs they have access to. -func (iamIdentity *IamIdentityV1) UpdateAPIKey(updateAPIKeyOptions *UpdateAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.UpdateAPIKeyWithContext(context.Background(), updateAPIKeyOptions) +// DeleteServiceID : Deletes a service ID and associated API keys +// Deletes a service ID and all API keys associated to it. Before deleting the service ID, all associated API keys are +// deleted. In case a Delete Conflict (status code 409) a retry of the request may help as the service ID is only +// deleted if the associated API keys were successfully deleted before. Users can manage user API keys for themself, or +// service ID API keys for service IDs they have access to. +func (iamIdentity *IamIdentityV1) DeleteServiceID(deleteServiceIDOptions *DeleteServiceIDOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeleteServiceIDWithContext(context.Background(), deleteServiceIDOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateAPIKeyWithContext is an alternate form of the UpdateAPIKey method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UpdateAPIKeyWithContext(ctx context.Context, updateAPIKeyOptions *UpdateAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateAPIKeyOptions, "updateAPIKeyOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) +// DeleteServiceIDWithContext is an alternate form of the DeleteServiceID method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteServiceIDWithContext(ctx context.Context, deleteServiceIDOptions *DeleteServiceIDOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteServiceIDOptions, "deleteServiceIDOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateAPIKeyOptions, "updateAPIKeyOptions") + err = core.ValidateStruct(deleteServiceIDOptions, "deleteServiceIDOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateAPIKeyOptions.ID, + "id": *deleteServiceIDOptions.ID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateAPIKeyOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateAPIKey") + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteServiceID") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - if updateAPIKeyOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateAPIKeyOptions.IfMatch)) - } - body := make(map[string]interface{}) - if updateAPIKeyOptions.Name != nil { - body["name"] = updateAPIKeyOptions.Name - } - if updateAPIKeyOptions.Description != nil { - body["description"] = updateAPIKeyOptions.Description - } - if updateAPIKeyOptions.SupportSessions != nil { - body["support_sessions"] = updateAPIKeyOptions.SupportSessions - } - if updateAPIKeyOptions.ActionWhenLeaked != nil { - body["action_when_leaked"] = updateAPIKeyOptions.ActionWhenLeaked - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + for headerName, headerValue := range deleteServiceIDOptions.Headers { + builder.AddHeader(headerName, headerValue) } request, err := builder.Build() @@ -588,66 +593,57 @@ func (iamIdentity *IamIdentityV1) UpdateAPIKeyWithContext(ctx context.Context, u return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "update_api_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_service_id", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKey) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// DeleteAPIKey : Deletes an API key -// Deletes an API key. Existing tokens will remain valid until expired. Users can manage user API keys for themself, or -// service ID API keys for service IDs they have access to. -func (iamIdentity *IamIdentityV1) DeleteAPIKey(deleteAPIKeyOptions *DeleteAPIKeyOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.DeleteAPIKeyWithContext(context.Background(), deleteAPIKeyOptions) +// LockServiceID : Lock the service ID +// Locks a service ID by ID. Users can manage user API keys for themself, or service ID API keys for service IDs they +// have access to. +func (iamIdentity *IamIdentityV1) LockServiceID(lockServiceIDOptions *LockServiceIDOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.LockServiceIDWithContext(context.Background(), lockServiceIDOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteAPIKeyWithContext is an alternate form of the DeleteAPIKey method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeleteAPIKeyWithContext(ctx context.Context, deleteAPIKeyOptions *DeleteAPIKeyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteAPIKeyOptions, "deleteAPIKeyOptions cannot be nil") +// LockServiceIDWithContext is an alternate form of the LockServiceID method which supports a Context parameter +func (iamIdentity *IamIdentityV1) LockServiceIDWithContext(ctx context.Context, lockServiceIDOptions *LockServiceIDOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(lockServiceIDOptions, "lockServiceIDOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteAPIKeyOptions, "deleteAPIKeyOptions") + err = core.ValidateStruct(lockServiceIDOptions, "lockServiceIDOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteAPIKeyOptions.ID, + "id": *lockServiceIDOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}/lock`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteAPIKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "LockServiceID") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAPIKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range lockServiceIDOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -659,7 +655,7 @@ func (iamIdentity *IamIdentityV1) DeleteAPIKeyWithContext(ctx context.Context, d response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_api_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "lock_service_id", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -667,47 +663,47 @@ func (iamIdentity *IamIdentityV1) DeleteAPIKeyWithContext(ctx context.Context, d return } -// LockAPIKey : Lock the API key -// Locks an API key by ID. Users can manage user API keys for themself, or service ID API keys for service IDs they have -// access to. -func (iamIdentity *IamIdentityV1) LockAPIKey(lockAPIKeyOptions *LockAPIKeyOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.LockAPIKeyWithContext(context.Background(), lockAPIKeyOptions) +// UnlockServiceID : Unlock the service ID +// Unlocks a service ID by ID. Users can manage user API keys for themself, or service ID API keys for service IDs they +// have access to. +func (iamIdentity *IamIdentityV1) UnlockServiceID(unlockServiceIDOptions *UnlockServiceIDOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.UnlockServiceIDWithContext(context.Background(), unlockServiceIDOptions) err = core.RepurposeSDKProblem(err, "") return } -// LockAPIKeyWithContext is an alternate form of the LockAPIKey method which supports a Context parameter -func (iamIdentity *IamIdentityV1) LockAPIKeyWithContext(ctx context.Context, lockAPIKeyOptions *LockAPIKeyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(lockAPIKeyOptions, "lockAPIKeyOptions cannot be nil") +// UnlockServiceIDWithContext is an alternate form of the UnlockServiceID method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UnlockServiceIDWithContext(ctx context.Context, unlockServiceIDOptions *UnlockServiceIDOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(unlockServiceIDOptions, "unlockServiceIDOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(lockAPIKeyOptions, "lockAPIKeyOptions") + err = core.ValidateStruct(unlockServiceIDOptions, "unlockServiceIDOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *lockAPIKeyOptions.ID, + "id": *unlockServiceIDOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}/lock`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}/lock`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range lockAPIKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UnlockServiceID") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "LockAPIKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range unlockServiceIDOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -719,7 +715,7 @@ func (iamIdentity *IamIdentityV1) LockAPIKeyWithContext(ctx context.Context, loc response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "lock_api_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "unlock_service_id", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -727,49 +723,44 @@ func (iamIdentity *IamIdentityV1) LockAPIKeyWithContext(ctx context.Context, loc return } -// UnlockAPIKey : Unlock the API key -// Unlocks an API key by ID. Users can manage user API keys for themself, or service ID API keys for service IDs they -// have access to. -func (iamIdentity *IamIdentityV1) UnlockAPIKey(unlockAPIKeyOptions *UnlockAPIKeyOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.UnlockAPIKeyWithContext(context.Background(), unlockAPIKeyOptions) +// ListServiceIDGroup : List service ID groups +// Returns a list of all service ID groups for the given account ID. +func (iamIdentity *IamIdentityV1) ListServiceIDGroup(listServiceIDGroupOptions *ListServiceIDGroupOptions) (result *ServiceIDGroupList, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListServiceIDGroupWithContext(context.Background(), listServiceIDGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// UnlockAPIKeyWithContext is an alternate form of the UnlockAPIKey method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UnlockAPIKeyWithContext(ctx context.Context, unlockAPIKeyOptions *UnlockAPIKeyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(unlockAPIKeyOptions, "unlockAPIKeyOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(unlockAPIKeyOptions, "unlockAPIKeyOptions") +// ListServiceIDGroupWithContext is an alternate form of the ListServiceIDGroup method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListServiceIDGroupWithContext(ctx context.Context, listServiceIDGroupOptions *ListServiceIDGroupOptions) (result *ServiceIDGroupList, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listServiceIDGroupOptions, "listServiceIDGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *unlockAPIKeyOptions.ID, - } - - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}/lock`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceid_groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range unlockAPIKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListServiceIDGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UnlockAPIKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listServiceIDGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + + if listServiceIDGroupOptions.AccountID != nil { + builder.AddQuery("account_id", fmt.Sprint(*listServiceIDGroupOptions.AccountID)) + } request, err := builder.Build() if err != nil { @@ -777,59 +768,81 @@ func (iamIdentity *IamIdentityV1) UnlockAPIKeyWithContext(ctx context.Context, u return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "unlock_api_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_service_id_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceIDGroupList) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// DisableAPIKey : Disable the API key -// Disable an API key. Users can manage user API keys for themself, or service ID API keys for service IDs they have -// access to. -func (iamIdentity *IamIdentityV1) DisableAPIKey(disableAPIKeyOptions *DisableAPIKeyOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.DisableAPIKeyWithContext(context.Background(), disableAPIKeyOptions) +// CreateServiceIDGroup : Create a service ID group +// Creates a service ID group for the given account ID. +func (iamIdentity *IamIdentityV1) CreateServiceIDGroup(createServiceIDGroupOptions *CreateServiceIDGroupOptions) (result *ServiceIDGroup, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateServiceIDGroupWithContext(context.Background(), createServiceIDGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// DisableAPIKeyWithContext is an alternate form of the DisableAPIKey method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DisableAPIKeyWithContext(ctx context.Context, disableAPIKeyOptions *DisableAPIKeyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(disableAPIKeyOptions, "disableAPIKeyOptions cannot be nil") +// CreateServiceIDGroupWithContext is an alternate form of the CreateServiceIDGroup method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateServiceIDGroupWithContext(ctx context.Context, createServiceIDGroupOptions *CreateServiceIDGroupOptions) (result *ServiceIDGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createServiceIDGroupOptions, "createServiceIDGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(disableAPIKeyOptions, "disableAPIKeyOptions") + err = core.ValidateStruct(createServiceIDGroupOptions, "createServiceIDGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *disableAPIKeyOptions.ID, - } - builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}/disable`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceid_groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range disableAPIKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateServiceIDGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DisableAPIKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createServiceIDGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if createServiceIDGroupOptions.AccountID != nil { + body["account_id"] = createServiceIDGroupOptions.AccountID + } + if createServiceIDGroupOptions.Name != nil { + body["name"] = createServiceIDGroupOptions.Name + } + if createServiceIDGroupOptions.Description != nil { + body["description"] = createServiceIDGroupOptions.Description + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } request, err := builder.Build() if err != nil { @@ -837,59 +850,68 @@ func (iamIdentity *IamIdentityV1) DisableAPIKeyWithContext(ctx context.Context, return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "disable_api_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_service_id_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceIDGroup) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// EnableAPIKey : Enable the API key -// Enable an API key. Users can manage user API keys for themself, or service ID API keys for service IDs they have -// access to. -func (iamIdentity *IamIdentityV1) EnableAPIKey(enableAPIKeyOptions *EnableAPIKeyOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.EnableAPIKeyWithContext(context.Background(), enableAPIKeyOptions) +// GetServiceIDGroup : Get details of a service ID group +// Returns the details of a service ID group. +func (iamIdentity *IamIdentityV1) GetServiceIDGroup(getServiceIDGroupOptions *GetServiceIDGroupOptions) (result *ServiceIDGroup, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetServiceIDGroupWithContext(context.Background(), getServiceIDGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// EnableAPIKeyWithContext is an alternate form of the EnableAPIKey method which supports a Context parameter -func (iamIdentity *IamIdentityV1) EnableAPIKeyWithContext(ctx context.Context, enableAPIKeyOptions *EnableAPIKeyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(enableAPIKeyOptions, "enableAPIKeyOptions cannot be nil") +// GetServiceIDGroupWithContext is an alternate form of the GetServiceIDGroup method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetServiceIDGroupWithContext(ctx context.Context, getServiceIDGroupOptions *GetServiceIDGroupOptions) (result *ServiceIDGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getServiceIDGroupOptions, "getServiceIDGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(enableAPIKeyOptions, "enableAPIKeyOptions") + err = core.ValidateStruct(getServiceIDGroupOptions, "getServiceIDGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *enableAPIKeyOptions.ID, + "id": *getServiceIDGroupOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}/disable`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceid_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range enableAPIKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetServiceIDGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "EnableAPIKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getServiceIDGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { @@ -897,76 +919,238 @@ func (iamIdentity *IamIdentityV1) EnableAPIKeyWithContext(ctx context.Context, e return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "enable_api_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_service_id_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceIDGroup) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListServiceIds : List service IDs -// Returns a list of service IDs. Users can manage user API keys for themself, or service ID API keys for service IDs -// they have access to. Note: apikey details are only included in the response when creating a Service ID with an api -// key. -func (iamIdentity *IamIdentityV1) ListServiceIds(listServiceIdsOptions *ListServiceIdsOptions) (result *ServiceIDList, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.ListServiceIdsWithContext(context.Background(), listServiceIdsOptions) +// UpdateServiceIDGroup : Update a service ID group +// Update a service ID group. +func (iamIdentity *IamIdentityV1) UpdateServiceIDGroup(updateServiceIDGroupOptions *UpdateServiceIDGroupOptions) (result *ServiceIDGroup, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdateServiceIDGroupWithContext(context.Background(), updateServiceIDGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListServiceIdsWithContext is an alternate form of the ListServiceIds method which supports a Context parameter -func (iamIdentity *IamIdentityV1) ListServiceIdsWithContext(ctx context.Context, listServiceIdsOptions *ListServiceIdsOptions) (result *ServiceIDList, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listServiceIdsOptions, "listServiceIdsOptions") +// UpdateServiceIDGroupWithContext is an alternate form of the UpdateServiceIDGroup method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdateServiceIDGroupWithContext(ctx context.Context, updateServiceIDGroupOptions *UpdateServiceIDGroupOptions) (result *ServiceIDGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateServiceIDGroupOptions, "updateServiceIDGroupOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(updateServiceIDGroupOptions, "updateServiceIDGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "id": *updateServiceIDGroupOptions.ID, + } + + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceid_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listServiceIdsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateServiceIDGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListServiceIds") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateServiceIDGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + if updateServiceIDGroupOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateServiceIDGroupOptions.IfMatch)) + } - if listServiceIdsOptions.AccountID != nil { - builder.AddQuery("account_id", fmt.Sprint(*listServiceIdsOptions.AccountID)) + body := make(map[string]interface{}) + if updateServiceIDGroupOptions.Name != nil { + body["name"] = updateServiceIDGroupOptions.Name } - if listServiceIdsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listServiceIdsOptions.Name)) + if updateServiceIDGroupOptions.Description != nil { + body["description"] = updateServiceIDGroupOptions.Description } - if listServiceIdsOptions.Pagesize != nil { - builder.AddQuery("pagesize", fmt.Sprint(*listServiceIdsOptions.Pagesize)) + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } - if listServiceIdsOptions.Pagetoken != nil { - builder.AddQuery("pagetoken", fmt.Sprint(*listServiceIdsOptions.Pagetoken)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return } - if listServiceIdsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listServiceIdsOptions.Sort)) + + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "update_service_id_group", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return } - if listServiceIdsOptions.Order != nil { - builder.AddQuery("order", fmt.Sprint(*listServiceIdsOptions.Order)) + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceIDGroup) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result } - if listServiceIdsOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*listServiceIdsOptions.IncludeHistory)) + + return +} + +// DeleteServiceIDGroup : Delete a service ID group +// Delete a service ID group. +func (iamIdentity *IamIdentityV1) DeleteServiceIDGroup(deleteServiceIDGroupOptions *DeleteServiceIDGroupOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeleteServiceIDGroupWithContext(context.Background(), deleteServiceIDGroupOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// DeleteServiceIDGroupWithContext is an alternate form of the DeleteServiceIDGroup method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteServiceIDGroupWithContext(ctx context.Context, deleteServiceIDGroupOptions *DeleteServiceIDGroupOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteServiceIDGroupOptions, "deleteServiceIDGroupOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return } - if listServiceIdsOptions.Filter != nil { - builder.AddQuery("filter", fmt.Sprint(*listServiceIdsOptions.Filter)) + err = core.ValidateStruct(deleteServiceIDGroupOptions, "deleteServiceIDGroupOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "id": *deleteServiceIDGroupOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceid_groups/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteServiceIDGroup") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range deleteServiceIDGroupOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = iamIdentity.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "delete_service_id_group", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// ListAPIKeys : Get API keys for a given service or user IAM ID and account ID +// Returns the list of API key details for a given service or user IAM ID and account ID. Users can manage user API keys +// for themself, or service ID API keys for service IDs they have access to. +func (iamIdentity *IamIdentityV1) ListAPIKeys(listAPIKeysOptions *ListAPIKeysOptions) (result *APIKeyList, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListAPIKeysWithContext(context.Background(), listAPIKeysOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListAPIKeysWithContext is an alternate form of the ListAPIKeys method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListAPIKeysWithContext(ctx context.Context, listAPIKeysOptions *ListAPIKeysOptions) (result *APIKeyList, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listAPIKeysOptions, "listAPIKeysOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListAPIKeys") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range listAPIKeysOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + if listAPIKeysOptions.AccountID != nil { + builder.AddQuery("account_id", fmt.Sprint(*listAPIKeysOptions.AccountID)) + } + if listAPIKeysOptions.IamID != nil { + builder.AddQuery("iam_id", fmt.Sprint(*listAPIKeysOptions.IamID)) + } + if listAPIKeysOptions.Pagesize != nil { + builder.AddQuery("pagesize", fmt.Sprint(*listAPIKeysOptions.Pagesize)) + } + if listAPIKeysOptions.Pagetoken != nil { + builder.AddQuery("pagetoken", fmt.Sprint(*listAPIKeysOptions.Pagetoken)) + } + if listAPIKeysOptions.Scope != nil { + builder.AddQuery("scope", fmt.Sprint(*listAPIKeysOptions.Scope)) + } + if listAPIKeysOptions.Type != nil { + builder.AddQuery("type", fmt.Sprint(*listAPIKeysOptions.Type)) + } + if listAPIKeysOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listAPIKeysOptions.Sort)) + } + if listAPIKeysOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listAPIKeysOptions.Order)) + } + if listAPIKeysOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*listAPIKeysOptions.IncludeHistory)) + } + if listAPIKeysOptions.Filter != nil { + builder.AddQuery("filter", fmt.Sprint(*listAPIKeysOptions.Filter)) + } + if listAPIKeysOptions.GroupID != nil { + builder.AddQuery("group_id", fmt.Sprint(*listAPIKeysOptions.GroupID)) } request, err := builder.Build() @@ -978,12 +1162,12 @@ func (iamIdentity *IamIdentityV1) ListServiceIdsWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_service_ids", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_api_keys", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceIDList) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKeyList) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -994,23 +1178,23 @@ func (iamIdentity *IamIdentityV1) ListServiceIdsWithContext(ctx context.Context, return } -// CreateServiceID : Create a service ID -// Creates a service ID for an IBM Cloud account. Users can manage user API keys for themself, or service ID API keys +// CreateAPIKey : Create an API key +// Creates an API key for a UserID or service ID. Users can manage user API keys for themself, or service ID API keys // for service IDs they have access to. -func (iamIdentity *IamIdentityV1) CreateServiceID(createServiceIDOptions *CreateServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateServiceIDWithContext(context.Background(), createServiceIDOptions) +func (iamIdentity *IamIdentityV1) CreateAPIKey(createAPIKeyOptions *CreateAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateAPIKeyWithContext(context.Background(), createAPIKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateServiceIDWithContext is an alternate form of the CreateServiceID method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateServiceIDWithContext(ctx context.Context, createServiceIDOptions *CreateServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createServiceIDOptions, "createServiceIDOptions cannot be nil") +// CreateAPIKeyWithContext is an alternate form of the CreateAPIKey method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateAPIKeyWithContext(ctx context.Context, createAPIKeyOptions *CreateAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createAPIKeyOptions, "createAPIKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createServiceIDOptions, "createServiceIDOptions") + err = core.ValidateStruct(createAPIKeyOptions, "createAPIKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -1019,41 +1203,53 @@ func (iamIdentity *IamIdentityV1) CreateServiceIDWithContext(ctx context.Context builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createServiceIDOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateAPIKey") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateServiceID") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createAPIKeyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") - if createServiceIDOptions.EntityLock != nil { - builder.AddHeader("Entity-Lock", fmt.Sprint(*createServiceIDOptions.EntityLock)) + if createAPIKeyOptions.EntityLock != nil { + builder.AddHeader("Entity-Lock", fmt.Sprint(*createAPIKeyOptions.EntityLock)) + } + if createAPIKeyOptions.EntityDisable != nil { + builder.AddHeader("Entity-Disable", fmt.Sprint(*createAPIKeyOptions.EntityDisable)) } body := make(map[string]interface{}) - if createServiceIDOptions.AccountID != nil { - body["account_id"] = createServiceIDOptions.AccountID + if createAPIKeyOptions.Name != nil { + body["name"] = createAPIKeyOptions.Name } - if createServiceIDOptions.Name != nil { - body["name"] = createServiceIDOptions.Name + if createAPIKeyOptions.IamID != nil { + body["iam_id"] = createAPIKeyOptions.IamID } - if createServiceIDOptions.Description != nil { - body["description"] = createServiceIDOptions.Description + if createAPIKeyOptions.Description != nil { + body["description"] = createAPIKeyOptions.Description } - if createServiceIDOptions.UniqueInstanceCrns != nil { - body["unique_instance_crns"] = createServiceIDOptions.UniqueInstanceCrns + if createAPIKeyOptions.AccountID != nil { + body["account_id"] = createAPIKeyOptions.AccountID } - if createServiceIDOptions.Apikey != nil { - body["apikey"] = createServiceIDOptions.Apikey + if createAPIKeyOptions.Apikey != nil { + body["apikey"] = createAPIKeyOptions.Apikey + } + if createAPIKeyOptions.StoreValue != nil { + body["store_value"] = createAPIKeyOptions.StoreValue + } + if createAPIKeyOptions.SupportSessions != nil { + body["support_sessions"] = createAPIKeyOptions.SupportSessions + } + if createAPIKeyOptions.ActionWhenLeaked != nil { + body["action_when_leaked"] = createAPIKeyOptions.ActionWhenLeaked } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -1070,12 +1266,252 @@ func (iamIdentity *IamIdentityV1) CreateServiceIDWithContext(ctx context.Context var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_service_id", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_api_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceID) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKey) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// GetAPIKeysDetails : Get details of an API key by its value +// Returns the details of an API key by its value. Users can manage user API keys for themself, or service ID API keys +// for service IDs they have access to. +func (iamIdentity *IamIdentityV1) GetAPIKeysDetails(getAPIKeysDetailsOptions *GetAPIKeysDetailsOptions) (result *APIKey, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetAPIKeysDetailsWithContext(context.Background(), getAPIKeysDetailsOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAPIKeysDetailsWithContext is an alternate form of the GetAPIKeysDetails method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetAPIKeysDetailsWithContext(ctx context.Context, getAPIKeysDetailsOptions *GetAPIKeysDetailsOptions) (result *APIKey, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(getAPIKeysDetailsOptions, "getAPIKeysDetailsOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/details`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAPIKeysDetails") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range getAPIKeysDetailsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + if getAPIKeysDetailsOptions.IamAPIKey != nil { + builder.AddHeader("IAM-ApiKey", fmt.Sprint(*getAPIKeysDetailsOptions.IamAPIKey)) + } + + if getAPIKeysDetailsOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getAPIKeysDetailsOptions.IncludeHistory)) + } + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "get_api_keys_details", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKey) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// GetAPIKey : Get details of an API key +// Returns the details of an API key. Users can manage user API keys for themself, or service ID API keys for service +// IDs they have access to. +func (iamIdentity *IamIdentityV1) GetAPIKey(getAPIKeyOptions *GetAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetAPIKeyWithContext(context.Background(), getAPIKeyOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAPIKeyWithContext is an alternate form of the GetAPIKey method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetAPIKeyWithContext(ctx context.Context, getAPIKeyOptions *GetAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getAPIKeyOptions, "getAPIKeyOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getAPIKeyOptions, "getAPIKeyOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "id": *getAPIKeyOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAPIKey") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range getAPIKeyOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + if getAPIKeyOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getAPIKeyOptions.IncludeHistory)) + } + if getAPIKeyOptions.IncludeActivity != nil { + builder.AddQuery("include_activity", fmt.Sprint(*getAPIKeyOptions.IncludeActivity)) + } + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "get_api_key", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKey) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// UpdateAPIKey : Updates an API key +// Updates properties of an API key. This does NOT affect existing access tokens. Their token content will stay +// unchanged until the access token is refreshed. To update an API key, pass the property to be modified. To delete one +// property's value, pass the property with an empty value "". Users can manage user API keys for themself, or service +// ID API keys for service IDs they have access to. +func (iamIdentity *IamIdentityV1) UpdateAPIKey(updateAPIKeyOptions *UpdateAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdateAPIKeyWithContext(context.Background(), updateAPIKeyOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// UpdateAPIKeyWithContext is an alternate form of the UpdateAPIKey method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdateAPIKeyWithContext(ctx context.Context, updateAPIKeyOptions *UpdateAPIKeyOptions) (result *APIKey, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateAPIKeyOptions, "updateAPIKeyOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(updateAPIKeyOptions, "updateAPIKeyOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "id": *updateAPIKeyOptions.ID, + } + + builder := core.NewRequestBuilder(core.PUT) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateAPIKey") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range updateAPIKeyOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + if updateAPIKeyOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateAPIKeyOptions.IfMatch)) + } + + body := make(map[string]interface{}) + if updateAPIKeyOptions.Name != nil { + body["name"] = updateAPIKeyOptions.Name + } + if updateAPIKeyOptions.Description != nil { + body["description"] = updateAPIKeyOptions.Description + } + if updateAPIKeyOptions.SupportSessions != nil { + body["support_sessions"] = updateAPIKeyOptions.SupportSessions + } + if updateAPIKeyOptions.ActionWhenLeaked != nil { + body["action_when_leaked"] = updateAPIKeyOptions.ActionWhenLeaked + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "update_api_key", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAPIKey) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1086,57 +1522,48 @@ func (iamIdentity *IamIdentityV1) CreateServiceIDWithContext(ctx context.Context return } -// GetServiceID : Get details of a service ID -// Returns the details of a service ID. Users can manage user API keys for themself, or service ID API keys for service -// IDs they have access to. Note: apikey details are only included in the response when creating a Service ID with an -// api key. -func (iamIdentity *IamIdentityV1) GetServiceID(getServiceIDOptions *GetServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetServiceIDWithContext(context.Background(), getServiceIDOptions) +// DeleteAPIKey : Deletes an API key +// Deletes an API key. Existing tokens will remain valid until expired. Users can manage user API keys for themself, or +// service ID API keys for service IDs they have access to. +func (iamIdentity *IamIdentityV1) DeleteAPIKey(deleteAPIKeyOptions *DeleteAPIKeyOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeleteAPIKeyWithContext(context.Background(), deleteAPIKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetServiceIDWithContext is an alternate form of the GetServiceID method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetServiceIDWithContext(ctx context.Context, getServiceIDOptions *GetServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getServiceIDOptions, "getServiceIDOptions cannot be nil") +// DeleteAPIKeyWithContext is an alternate form of the DeleteAPIKey method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteAPIKeyWithContext(ctx context.Context, deleteAPIKeyOptions *DeleteAPIKeyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteAPIKeyOptions, "deleteAPIKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getServiceIDOptions, "getServiceIDOptions") + err = core.ValidateStruct(deleteAPIKeyOptions, "deleteAPIKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getServiceIDOptions.ID, + "id": *deleteAPIKeyOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getServiceIDOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetServiceID") + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAPIKey") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - if getServiceIDOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getServiceIDOptions.IncludeHistory)) - } - if getServiceIDOptions.IncludeActivity != nil { - builder.AddQuery("include_activity", fmt.Sprint(*getServiceIDOptions.IncludeActivity)) + for headerName, headerValue := range deleteAPIKeyOptions.Headers { + builder.AddHeader(headerName, headerValue) } request, err := builder.Build() @@ -1145,91 +1572,58 @@ func (iamIdentity *IamIdentityV1) GetServiceIDWithContext(ctx context.Context, g return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_service_id", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_api_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceID) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// UpdateServiceID : Update service ID -// Updates properties of a service ID. This does NOT affect existing access tokens. Their token content will stay -// unchanged until the access token is refreshed. To update a service ID, pass the property to be modified. To delete -// one property's value, pass the property with an empty value "".Users can manage user API keys for themself, or -// service ID API keys for service IDs they have access to. Note: apikey details are only included in the response when -// creating a Service ID with an apikey. -func (iamIdentity *IamIdentityV1) UpdateServiceID(updateServiceIDOptions *UpdateServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.UpdateServiceIDWithContext(context.Background(), updateServiceIDOptions) +// LockAPIKey : Lock the API key +// Locks an API key by ID. Users can manage user API keys for themself, or service ID API keys for service IDs they have +// access to. +func (iamIdentity *IamIdentityV1) LockAPIKey(lockAPIKeyOptions *LockAPIKeyOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.LockAPIKeyWithContext(context.Background(), lockAPIKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateServiceIDWithContext is an alternate form of the UpdateServiceID method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UpdateServiceIDWithContext(ctx context.Context, updateServiceIDOptions *UpdateServiceIDOptions) (result *ServiceID, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateServiceIDOptions, "updateServiceIDOptions cannot be nil") +// LockAPIKeyWithContext is an alternate form of the LockAPIKey method which supports a Context parameter +func (iamIdentity *IamIdentityV1) LockAPIKeyWithContext(ctx context.Context, lockAPIKeyOptions *LockAPIKeyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(lockAPIKeyOptions, "lockAPIKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateServiceIDOptions, "updateServiceIDOptions") + err = core.ValidateStruct(lockAPIKeyOptions, "lockAPIKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateServiceIDOptions.ID, + "id": *lockAPIKeyOptions.ID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}/lock`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateServiceIDOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateServiceID") + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "LockAPIKey") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - if updateServiceIDOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateServiceIDOptions.IfMatch)) - } - body := make(map[string]interface{}) - if updateServiceIDOptions.Name != nil { - body["name"] = updateServiceIDOptions.Name - } - if updateServiceIDOptions.Description != nil { - body["description"] = updateServiceIDOptions.Description - } - if updateServiceIDOptions.UniqueInstanceCrns != nil { - body["unique_instance_crns"] = updateServiceIDOptions.UniqueInstanceCrns - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + for headerName, headerValue := range lockAPIKeyOptions.Headers { + builder.AddHeader(headerName, headerValue) } request, err := builder.Build() @@ -1238,68 +1632,57 @@ func (iamIdentity *IamIdentityV1) UpdateServiceIDWithContext(ctx context.Context return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "update_service_id", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "lock_api_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalServiceID) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// DeleteServiceID : Deletes a service ID and associated API keys -// Deletes a service ID and all API keys associated to it. Before deleting the service ID, all associated API keys are -// deleted. In case a Delete Conflict (status code 409) a retry of the request may help as the service ID is only -// deleted if the associated API keys were successfully deleted before. Users can manage user API keys for themself, or -// service ID API keys for service IDs they have access to. -func (iamIdentity *IamIdentityV1) DeleteServiceID(deleteServiceIDOptions *DeleteServiceIDOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.DeleteServiceIDWithContext(context.Background(), deleteServiceIDOptions) +// UnlockAPIKey : Unlock the API key +// Unlocks an API key by ID. Users can manage user API keys for themself, or service ID API keys for service IDs they +// have access to. +func (iamIdentity *IamIdentityV1) UnlockAPIKey(unlockAPIKeyOptions *UnlockAPIKeyOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.UnlockAPIKeyWithContext(context.Background(), unlockAPIKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteServiceIDWithContext is an alternate form of the DeleteServiceID method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeleteServiceIDWithContext(ctx context.Context, deleteServiceIDOptions *DeleteServiceIDOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteServiceIDOptions, "deleteServiceIDOptions cannot be nil") +// UnlockAPIKeyWithContext is an alternate form of the UnlockAPIKey method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UnlockAPIKeyWithContext(ctx context.Context, unlockAPIKeyOptions *UnlockAPIKeyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(unlockAPIKeyOptions, "unlockAPIKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteServiceIDOptions, "deleteServiceIDOptions") + err = core.ValidateStruct(unlockAPIKeyOptions, "unlockAPIKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteServiceIDOptions.ID, + "id": *unlockAPIKeyOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}/lock`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteServiceIDOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UnlockAPIKey") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteServiceID") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range unlockAPIKeyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -1311,7 +1694,7 @@ func (iamIdentity *IamIdentityV1) DeleteServiceIDWithContext(ctx context.Context response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_service_id", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "unlock_api_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -1319,47 +1702,47 @@ func (iamIdentity *IamIdentityV1) DeleteServiceIDWithContext(ctx context.Context return } -// LockServiceID : Lock the service ID -// Locks a service ID by ID. Users can manage user API keys for themself, or service ID API keys for service IDs they -// have access to. -func (iamIdentity *IamIdentityV1) LockServiceID(lockServiceIDOptions *LockServiceIDOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.LockServiceIDWithContext(context.Background(), lockServiceIDOptions) +// DisableAPIKey : Disable the API key +// Disable an API key. Users can manage user API keys for themself, or service ID API keys for service IDs they have +// access to. +func (iamIdentity *IamIdentityV1) DisableAPIKey(disableAPIKeyOptions *DisableAPIKeyOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DisableAPIKeyWithContext(context.Background(), disableAPIKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// LockServiceIDWithContext is an alternate form of the LockServiceID method which supports a Context parameter -func (iamIdentity *IamIdentityV1) LockServiceIDWithContext(ctx context.Context, lockServiceIDOptions *LockServiceIDOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(lockServiceIDOptions, "lockServiceIDOptions cannot be nil") +// DisableAPIKeyWithContext is an alternate form of the DisableAPIKey method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DisableAPIKeyWithContext(ctx context.Context, disableAPIKeyOptions *DisableAPIKeyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(disableAPIKeyOptions, "disableAPIKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(lockServiceIDOptions, "lockServiceIDOptions") + err = core.ValidateStruct(disableAPIKeyOptions, "disableAPIKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *lockServiceIDOptions.ID, + "id": *disableAPIKeyOptions.ID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}/lock`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}/disable`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range lockServiceIDOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DisableAPIKey") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "LockServiceID") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range disableAPIKeyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -1371,7 +1754,7 @@ func (iamIdentity *IamIdentityV1) LockServiceIDWithContext(ctx context.Context, response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "lock_service_id", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "disable_api_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -1379,47 +1762,47 @@ func (iamIdentity *IamIdentityV1) LockServiceIDWithContext(ctx context.Context, return } -// UnlockServiceID : Unlock the service ID -// Unlocks a service ID by ID. Users can manage user API keys for themself, or service ID API keys for service IDs they -// have access to. -func (iamIdentity *IamIdentityV1) UnlockServiceID(unlockServiceIDOptions *UnlockServiceIDOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.UnlockServiceIDWithContext(context.Background(), unlockServiceIDOptions) +// EnableAPIKey : Enable the API key +// Enable an API key. Users can manage user API keys for themself, or service ID API keys for service IDs they have +// access to. +func (iamIdentity *IamIdentityV1) EnableAPIKey(enableAPIKeyOptions *EnableAPIKeyOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.EnableAPIKeyWithContext(context.Background(), enableAPIKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// UnlockServiceIDWithContext is an alternate form of the UnlockServiceID method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UnlockServiceIDWithContext(ctx context.Context, unlockServiceIDOptions *UnlockServiceIDOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(unlockServiceIDOptions, "unlockServiceIDOptions cannot be nil") +// EnableAPIKeyWithContext is an alternate form of the EnableAPIKey method which supports a Context parameter +func (iamIdentity *IamIdentityV1) EnableAPIKeyWithContext(ctx context.Context, enableAPIKeyOptions *EnableAPIKeyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(enableAPIKeyOptions, "enableAPIKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(unlockServiceIDOptions, "unlockServiceIDOptions") + err = core.ValidateStruct(enableAPIKeyOptions, "enableAPIKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *unlockServiceIDOptions.ID, + "id": *enableAPIKeyOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/serviceids/{id}/lock`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/apikeys/{id}/disable`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range unlockServiceIDOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "EnableAPIKey") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UnlockServiceID") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range enableAPIKeyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -1431,7 +1814,7 @@ func (iamIdentity *IamIdentityV1) UnlockServiceIDWithContext(ctx context.Context response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "unlock_service_id", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "enable_api_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -1469,12 +1852,12 @@ func (iamIdentity *IamIdentityV1) CreateProfileWithContext(ctx context.Context, return } - for headerName, headerValue := range createProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1490,6 +1873,9 @@ func (iamIdentity *IamIdentityV1) CreateProfileWithContext(ctx context.Context, if createProfileOptions.Description != nil { body["description"] = createProfileOptions.Description } + if createProfileOptions.Email != nil { + body["email"] = createProfileOptions.Email + } _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) @@ -1552,12 +1938,12 @@ func (iamIdentity *IamIdentityV1) ListProfilesWithContext(ctx context.Context, l return } - for headerName, headerValue := range listProfilesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListProfiles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1645,12 +2031,12 @@ func (iamIdentity *IamIdentityV1) GetProfileWithContext(ctx context.Context, get return } - for headerName, headerValue := range getProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1718,12 +2104,12 @@ func (iamIdentity *IamIdentityV1) UpdateProfileWithContext(ctx context.Context, return } - for headerName, headerValue := range updateProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1739,6 +2125,9 @@ func (iamIdentity *IamIdentityV1) UpdateProfileWithContext(ctx context.Context, if updateProfileOptions.Description != nil { body["description"] = updateProfileOptions.Description } + if updateProfileOptions.Email != nil { + body["email"] = updateProfileOptions.Email + } _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) @@ -1805,12 +2194,12 @@ func (iamIdentity *IamIdentityV1) DeleteProfileWithContext(ctx context.Context, return } - for headerName, headerValue := range deleteProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -1864,12 +2253,12 @@ func (iamIdentity *IamIdentityV1) CreateClaimRuleWithContext(ctx context.Context return } - for headerName, headerValue := range createClaimRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateClaimRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateClaimRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createClaimRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1963,14 +2352,14 @@ func (iamIdentity *IamIdentityV1) ListClaimRulesWithContext(ctx context.Context, return } - for headerName, headerValue := range listClaimRulesOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListClaimRules") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range listClaimRulesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") request, err := builder.Build() @@ -2021,7 +2410,7 @@ func (iamIdentity *IamIdentityV1) GetClaimRuleWithContext(ctx context.Context, g pathParamsMap := map[string]string{ "profile-id": *getClaimRuleOptions.ProfileID, - "rule-id": *getClaimRuleOptions.RuleID, + "rule-id": *getClaimRuleOptions.RuleID, } builder := core.NewRequestBuilder(core.GET) @@ -2033,12 +2422,12 @@ func (iamIdentity *IamIdentityV1) GetClaimRuleWithContext(ctx context.Context, g return } - for headerName, headerValue := range getClaimRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetClaimRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetClaimRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getClaimRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2091,7 +2480,7 @@ func (iamIdentity *IamIdentityV1) UpdateClaimRuleWithContext(ctx context.Context pathParamsMap := map[string]string{ "profile-id": *updateClaimRuleOptions.ProfileID, - "rule-id": *updateClaimRuleOptions.RuleID, + "rule-id": *updateClaimRuleOptions.RuleID, } builder := core.NewRequestBuilder(core.PUT) @@ -2103,12 +2492,12 @@ func (iamIdentity *IamIdentityV1) UpdateClaimRuleWithContext(ctx context.Context return } - for headerName, headerValue := range updateClaimRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateClaimRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateClaimRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateClaimRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2194,7 +2583,7 @@ func (iamIdentity *IamIdentityV1) DeleteClaimRuleWithContext(ctx context.Context pathParamsMap := map[string]string{ "profile-id": *deleteClaimRuleOptions.ProfileID, - "rule-id": *deleteClaimRuleOptions.RuleID, + "rule-id": *deleteClaimRuleOptions.RuleID, } builder := core.NewRequestBuilder(core.DELETE) @@ -2206,12 +2595,12 @@ func (iamIdentity *IamIdentityV1) DeleteClaimRuleWithContext(ctx context.Context return } - for headerName, headerValue := range deleteClaimRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteClaimRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteClaimRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteClaimRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -2266,12 +2655,12 @@ func (iamIdentity *IamIdentityV1) CreateLinkWithContext(ctx context.Context, cre return } - for headerName, headerValue := range createLinkOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateLink") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateLink") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createLinkOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2352,12 +2741,12 @@ func (iamIdentity *IamIdentityV1) ListLinksWithContext(ctx context.Context, list return } - for headerName, headerValue := range listLinksOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListLinks") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListLinks") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listLinksOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2387,6 +2776,82 @@ func (iamIdentity *IamIdentityV1) ListLinksWithContext(ctx context.Context, list return } +// DeleteLinkByParameters : Delete compute resource link to profile by given parameters +// Deletes compute resource link of a Trusted Profile matching the given parameters. +func (iamIdentity *IamIdentityV1) DeleteLinkByParameters(deleteLinkByParametersOptions *DeleteLinkByParametersOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeleteLinkByParametersWithContext(context.Background(), deleteLinkByParametersOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// DeleteLinkByParametersWithContext is an alternate form of the DeleteLinkByParameters method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteLinkByParametersWithContext(ctx context.Context, deleteLinkByParametersOptions *DeleteLinkByParametersOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteLinkByParametersOptions, "deleteLinkByParametersOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteLinkByParametersOptions, "deleteLinkByParametersOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "profile-id": *deleteLinkByParametersOptions.ProfileID, + } + + builder := core.NewRequestBuilder(core.DELETE) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profiles/{profile-id}/links`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteLinkByParameters") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range deleteLinkByParametersOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + builder.AddQuery("type", fmt.Sprint(*deleteLinkByParametersOptions.Type)) + if deleteLinkByParametersOptions.CRN != nil { + builder.AddQuery("crn", fmt.Sprint(*deleteLinkByParametersOptions.CRN)) + } + if deleteLinkByParametersOptions.Namespace != nil { + builder.AddQuery("namespace", fmt.Sprint(*deleteLinkByParametersOptions.Namespace)) + } + if deleteLinkByParametersOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*deleteLinkByParametersOptions.Name)) + } + if deleteLinkByParametersOptions.ComponentType != nil { + builder.AddQuery("component_type", fmt.Sprint(*deleteLinkByParametersOptions.ComponentType)) + } + if deleteLinkByParametersOptions.ComponentName != nil { + builder.AddQuery("component_name", fmt.Sprint(*deleteLinkByParametersOptions.ComponentName)) + } + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = iamIdentity.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "delete_link_by_parameters", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + // GetLink : Get link to a trusted profile // Get a specific link to a trusted profile by `link_id`. func (iamIdentity *IamIdentityV1) GetLink(getLinkOptions *GetLinkOptions) (result *ProfileLink, response *core.DetailedResponse, err error) { @@ -2410,7 +2875,7 @@ func (iamIdentity *IamIdentityV1) GetLinkWithContext(ctx context.Context, getLin pathParamsMap := map[string]string{ "profile-id": *getLinkOptions.ProfileID, - "link-id": *getLinkOptions.LinkID, + "link-id": *getLinkOptions.LinkID, } builder := core.NewRequestBuilder(core.GET) @@ -2422,12 +2887,12 @@ func (iamIdentity *IamIdentityV1) GetLinkWithContext(ctx context.Context, getLin return } - for headerName, headerValue := range getLinkOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetLink") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetLink") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLinkOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2480,7 +2945,7 @@ func (iamIdentity *IamIdentityV1) DeleteLinkWithContext(ctx context.Context, del pathParamsMap := map[string]string{ "profile-id": *deleteLinkOptions.ProfileID, - "link-id": *deleteLinkOptions.LinkID, + "link-id": *deleteLinkOptions.LinkID, } builder := core.NewRequestBuilder(core.DELETE) @@ -2492,12 +2957,12 @@ func (iamIdentity *IamIdentityV1) DeleteLinkWithContext(ctx context.Context, del return } - for headerName, headerValue := range deleteLinkOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteLink") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteLink") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteLinkOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -2551,12 +3016,12 @@ func (iamIdentity *IamIdentityV1) GetProfileIdentitiesWithContext(ctx context.Co return } - for headerName, headerValue := range getProfileIdentitiesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetProfileIdentities") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetProfileIdentities") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getProfileIdentitiesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2620,12 +3085,12 @@ func (iamIdentity *IamIdentityV1) SetProfileIdentitiesWithContext(ctx context.Co return } - for headerName, headerValue := range setProfileIdentitiesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "SetProfileIdentities") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "SetProfileIdentities") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range setProfileIdentitiesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2670,9 +3135,11 @@ func (iamIdentity *IamIdentityV1) SetProfileIdentitiesWithContext(ctx context.Co } // SetProfileIdentity : Add a specific identity that can assume the trusted profile -// Add a specific identity that can assume the trusted profile. This API will update the trusted profile itself, thus -// calling it repeatedly for the same profile can lead to conflicts responded with HTTP code 409. Make sure to call this -// API only once in a few seconds for the same trusted profile. +// Add a specific identity that can assume the trusted profile. +// +// **Note:** This API will update the trusted profile itself, thus calling it repeatedly for the same profile can lead +// to conflicts responded with HTTP code 409. Make sure to call this API only once in a few seconds for the same +// trusted profile. func (iamIdentity *IamIdentityV1) SetProfileIdentity(setProfileIdentityOptions *SetProfileIdentityOptions) (result *ProfileIdentityResponse, response *core.DetailedResponse, err error) { result, response, err = iamIdentity.SetProfileIdentityWithContext(context.Background(), setProfileIdentityOptions) err = core.RepurposeSDKProblem(err, "") @@ -2693,7 +3160,7 @@ func (iamIdentity *IamIdentityV1) SetProfileIdentityWithContext(ctx context.Cont } pathParamsMap := map[string]string{ - "profile-id": *setProfileIdentityOptions.ProfileID, + "profile-id": *setProfileIdentityOptions.ProfileID, "identity-type": *setProfileIdentityOptions.IdentityType, } @@ -2706,12 +3173,12 @@ func (iamIdentity *IamIdentityV1) SetProfileIdentityWithContext(ctx context.Cont return } - for headerName, headerValue := range setProfileIdentityOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "SetProfileIdentity") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "SetProfileIdentity") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range setProfileIdentityOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2783,7 +3250,7 @@ func (iamIdentity *IamIdentityV1) GetProfileIdentityWithContext(ctx context.Cont } pathParamsMap := map[string]string{ - "profile-id": *getProfileIdentityOptions.ProfileID, + "profile-id": *getProfileIdentityOptions.ProfileID, "identity-type": *getProfileIdentityOptions.IdentityType, "identifier-id": *getProfileIdentityOptions.IdentifierID, } @@ -2797,12 +3264,12 @@ func (iamIdentity *IamIdentityV1) GetProfileIdentityWithContext(ctx context.Cont return } - for headerName, headerValue := range getProfileIdentityOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetProfileIdentity") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetProfileIdentity") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getProfileIdentityOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2832,8 +3299,12 @@ func (iamIdentity *IamIdentityV1) GetProfileIdentityWithContext(ctx context.Cont return } -// DeleteProfileIdentity : Delete the identity that can assume the trusted profile. This API will update the trusted profile itself, thus calling it repeatedly for the same profile can lead to conflicts responded with HTTP code 409. Make sure to call this API only once in a few seconds for the same trusted profile +// DeleteProfileIdentity : Delete the identity that can assume the trusted profile // Delete the identity that can assume the trusted profile. +// +// **Note:** This API will update the trusted profile itself, thus calling it repeatedly for the same profile can lead +// to conflicts responded with HTTP code 409. Make sure to call this API only once in a few seconds for the same +// trusted profile. func (iamIdentity *IamIdentityV1) DeleteProfileIdentity(deleteProfileIdentityOptions *DeleteProfileIdentityOptions) (response *core.DetailedResponse, err error) { response, err = iamIdentity.DeleteProfileIdentityWithContext(context.Background(), deleteProfileIdentityOptions) err = core.RepurposeSDKProblem(err, "") @@ -2854,7 +3325,7 @@ func (iamIdentity *IamIdentityV1) DeleteProfileIdentityWithContext(ctx context.C } pathParamsMap := map[string]string{ - "profile-id": *deleteProfileIdentityOptions.ProfileID, + "profile-id": *deleteProfileIdentityOptions.ProfileID, "identity-type": *deleteProfileIdentityOptions.IdentityType, "identifier-id": *deleteProfileIdentityOptions.IdentifierID, } @@ -2868,12 +3339,12 @@ func (iamIdentity *IamIdentityV1) DeleteProfileIdentityWithContext(ctx context.C return } - for headerName, headerValue := range deleteProfileIdentityOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteProfileIdentity") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteProfileIdentity") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteProfileIdentityOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -2893,52 +3364,56 @@ func (iamIdentity *IamIdentityV1) DeleteProfileIdentityWithContext(ctx context.C return } -// GetAccountSettings : Get account configurations -// Returns the details of an account's configuration. -func (iamIdentity *IamIdentityV1) GetAccountSettings(getAccountSettingsOptions *GetAccountSettingsOptions) (result *AccountSettingsResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetAccountSettingsWithContext(context.Background(), getAccountSettingsOptions) +// CreateReport : Trigger activity report for the account +// Trigger activity report for the account by specifying the account ID. It can take a few minutes to generate the +// report for retrieval. +func (iamIdentity *IamIdentityV1) CreateReport(createReportOptions *CreateReportOptions) (result *ReportReference, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateReportWithContext(context.Background(), createReportOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetAccountSettingsWithContext is an alternate form of the GetAccountSettings method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetAccountSettingsWithContext(ctx context.Context, getAccountSettingsOptions *GetAccountSettingsOptions) (result *AccountSettingsResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getAccountSettingsOptions, "getAccountSettingsOptions cannot be nil") +// CreateReportWithContext is an alternate form of the CreateReport method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateReportWithContext(ctx context.Context, createReportOptions *CreateReportOptions) (result *ReportReference, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createReportOptions, "createReportOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getAccountSettingsOptions, "getAccountSettingsOptions") + err = core.ValidateStruct(createReportOptions, "createReportOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *getAccountSettingsOptions.AccountID, + "account_id": *createReportOptions.AccountID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/accounts/{account_id}/settings/identity`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/activity/accounts/{account_id}/report`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getAccountSettingsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateReport") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAccountSettings") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createReportOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if getAccountSettingsOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getAccountSettingsOptions.IncludeHistory)) + if createReportOptions.Type != nil { + builder.AddQuery("type", fmt.Sprint(*createReportOptions.Type)) + } + if createReportOptions.Duration != nil { + builder.AddQuery("duration", fmt.Sprint(*createReportOptions.Duration)) } request, err := builder.Build() @@ -2950,12 +3425,12 @@ func (iamIdentity *IamIdentityV1) GetAccountSettingsWithContext(ctx context.Cont var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "getAccountSettings", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_report", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReportReference) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2966,91 +3441,51 @@ func (iamIdentity *IamIdentityV1) GetAccountSettingsWithContext(ctx context.Cont return } -// UpdateAccountSettings : Update account configurations -// Allows a user to configure settings on their account with regards to MFA, MFA excemption list, session lifetimes, -// access control for creating new identities, and enforcing IP restrictions on token creation. -func (iamIdentity *IamIdentityV1) UpdateAccountSettings(updateAccountSettingsOptions *UpdateAccountSettingsOptions) (result *AccountSettingsResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.UpdateAccountSettingsWithContext(context.Background(), updateAccountSettingsOptions) +// GetReport : Get activity report for the account +// Get activity report for the account by specifying the account ID and the reference that is generated by triggering +// the report. Reports older than a day are deleted when generating a new report. +func (iamIdentity *IamIdentityV1) GetReport(getReportOptions *GetReportOptions) (result *Report, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetReportWithContext(context.Background(), getReportOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateAccountSettingsWithContext is an alternate form of the UpdateAccountSettings method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UpdateAccountSettingsWithContext(ctx context.Context, updateAccountSettingsOptions *UpdateAccountSettingsOptions) (result *AccountSettingsResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateAccountSettingsOptions, "updateAccountSettingsOptions cannot be nil") +// GetReportWithContext is an alternate form of the GetReport method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetReportWithContext(ctx context.Context, getReportOptions *GetReportOptions) (result *Report, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getReportOptions, "getReportOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateAccountSettingsOptions, "updateAccountSettingsOptions") + err = core.ValidateStruct(getReportOptions, "getReportOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *updateAccountSettingsOptions.AccountID, + "account_id": *getReportOptions.AccountID, + "reference": *getReportOptions.Reference, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/accounts/{account_id}/settings/identity`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/activity/accounts/{account_id}/report/{reference}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateAccountSettingsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetReport") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateAccountSettings") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getReportOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - if updateAccountSettingsOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateAccountSettingsOptions.IfMatch)) - } - - body := make(map[string]interface{}) - if updateAccountSettingsOptions.RestrictCreateServiceID != nil { - body["restrict_create_service_id"] = updateAccountSettingsOptions.RestrictCreateServiceID - } - if updateAccountSettingsOptions.RestrictCreatePlatformApikey != nil { - body["restrict_create_platform_apikey"] = updateAccountSettingsOptions.RestrictCreatePlatformApikey - } - if updateAccountSettingsOptions.AllowedIPAddresses != nil { - body["allowed_ip_addresses"] = updateAccountSettingsOptions.AllowedIPAddresses - } - if updateAccountSettingsOptions.Mfa != nil { - body["mfa"] = updateAccountSettingsOptions.Mfa - } - if updateAccountSettingsOptions.UserMfa != nil { - body["user_mfa"] = updateAccountSettingsOptions.UserMfa - } - if updateAccountSettingsOptions.SessionExpirationInSeconds != nil { - body["session_expiration_in_seconds"] = updateAccountSettingsOptions.SessionExpirationInSeconds - } - if updateAccountSettingsOptions.SessionInvalidationInSeconds != nil { - body["session_invalidation_in_seconds"] = updateAccountSettingsOptions.SessionInvalidationInSeconds - } - if updateAccountSettingsOptions.MaxSessionsPerIdentity != nil { - body["max_sessions_per_identity"] = updateAccountSettingsOptions.MaxSessionsPerIdentity - } - if updateAccountSettingsOptions.SystemAccessTokenExpirationInSeconds != nil { - body["system_access_token_expiration_in_seconds"] = updateAccountSettingsOptions.SystemAccessTokenExpirationInSeconds - } - if updateAccountSettingsOptions.SystemRefreshTokenExpirationInSeconds != nil { - body["system_refresh_token_expiration_in_seconds"] = updateAccountSettingsOptions.SystemRefreshTokenExpirationInSeconds - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } request, err := builder.Build() if err != nil { @@ -3061,12 +3496,12 @@ func (iamIdentity *IamIdentityV1) UpdateAccountSettingsWithContext(ctx context.C var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "updateAccountSettings", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_report", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReport) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3077,51 +3512,53 @@ func (iamIdentity *IamIdentityV1) UpdateAccountSettingsWithContext(ctx context.C return } -// GetMfaStatus : Get MFA enrollment status for a single user in the account -// Get MFA enrollment status for a single user in the account. -func (iamIdentity *IamIdentityV1) GetMfaStatus(getMfaStatusOptions *GetMfaStatusOptions) (result *UserMfaEnrollments, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetMfaStatusWithContext(context.Background(), getMfaStatusOptions) +// GetAccountSettings : Get account configurations +// Returns the details of an account's configuration. +func (iamIdentity *IamIdentityV1) GetAccountSettings(getAccountSettingsOptions *GetAccountSettingsOptions) (result *AccountSettingsResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetAccountSettingsWithContext(context.Background(), getAccountSettingsOptions) err = core.RepurposeSDKProblem(err, "") return } - -// GetMfaStatusWithContext is an alternate form of the GetMfaStatus method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetMfaStatusWithContext(ctx context.Context, getMfaStatusOptions *GetMfaStatusOptions) (result *UserMfaEnrollments, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getMfaStatusOptions, "getMfaStatusOptions cannot be nil") + +// GetAccountSettingsWithContext is an alternate form of the GetAccountSettings method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetAccountSettingsWithContext(ctx context.Context, getAccountSettingsOptions *GetAccountSettingsOptions) (result *AccountSettingsResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getAccountSettingsOptions, "getAccountSettingsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getMfaStatusOptions, "getMfaStatusOptions") + err = core.ValidateStruct(getAccountSettingsOptions, "getAccountSettingsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *getMfaStatusOptions.AccountID, + "account_id": *getAccountSettingsOptions.AccountID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/mfa/accounts/{account_id}/status`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/accounts/{account_id}/settings/identity`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getMfaStatusOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAccountSettings") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetMfaStatus") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getAccountSettingsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddQuery("iam_id", fmt.Sprint(*getMfaStatusOptions.IamID)) + if getAccountSettingsOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getAccountSettingsOptions.IncludeHistory)) + } request, err := builder.Build() if err != nil { @@ -3132,12 +3569,12 @@ func (iamIdentity *IamIdentityV1) GetMfaStatusWithContext(ctx context.Context, g var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_mfa_status", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "getAccountSettings", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalUserMfaEnrollments) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3148,53 +3585,90 @@ func (iamIdentity *IamIdentityV1) GetMfaStatusWithContext(ctx context.Context, g return } -// CreateMfaReport : Trigger MFA enrollment status report for the account -// Trigger MFA enrollment status report for the account by specifying the account ID. It can take a few minutes to -// generate the report for retrieval. -func (iamIdentity *IamIdentityV1) CreateMfaReport(createMfaReportOptions *CreateMfaReportOptions) (result *ReportReference, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateMfaReportWithContext(context.Background(), createMfaReportOptions) +// UpdateAccountSettings : Update account configurations +// Allows a user to configure settings on their account with regards to MFA, MFA excemption list, session lifetimes, +// access control for creating new identities, and enforcing IP restrictions on token creation. +func (iamIdentity *IamIdentityV1) UpdateAccountSettings(updateAccountSettingsOptions *UpdateAccountSettingsOptions) (result *AccountSettingsResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdateAccountSettingsWithContext(context.Background(), updateAccountSettingsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateMfaReportWithContext is an alternate form of the CreateMfaReport method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateMfaReportWithContext(ctx context.Context, createMfaReportOptions *CreateMfaReportOptions) (result *ReportReference, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createMfaReportOptions, "createMfaReportOptions cannot be nil") +// UpdateAccountSettingsWithContext is an alternate form of the UpdateAccountSettings method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdateAccountSettingsWithContext(ctx context.Context, updateAccountSettingsOptions *UpdateAccountSettingsOptions) (result *AccountSettingsResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateAccountSettingsOptions, "updateAccountSettingsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createMfaReportOptions, "createMfaReportOptions") + err = core.ValidateStruct(updateAccountSettingsOptions, "updateAccountSettingsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *createMfaReportOptions.AccountID, + "account_id": *updateAccountSettingsOptions.AccountID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/mfa/accounts/{account_id}/report`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/accounts/{account_id}/settings/identity`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createMfaReportOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateAccountSettings") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateMfaReport") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateAccountSettingsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + if updateAccountSettingsOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateAccountSettingsOptions.IfMatch)) + } - if createMfaReportOptions.Type != nil { - builder.AddQuery("type", fmt.Sprint(*createMfaReportOptions.Type)) + body := make(map[string]interface{}) + if updateAccountSettingsOptions.RestrictCreateServiceID != nil { + body["restrict_create_service_id"] = updateAccountSettingsOptions.RestrictCreateServiceID + } + if updateAccountSettingsOptions.RestrictCreatePlatformApikey != nil { + body["restrict_create_platform_apikey"] = updateAccountSettingsOptions.RestrictCreatePlatformApikey + } + if updateAccountSettingsOptions.AllowedIPAddresses != nil { + body["allowed_ip_addresses"] = updateAccountSettingsOptions.AllowedIPAddresses + } + if updateAccountSettingsOptions.Mfa != nil { + body["mfa"] = updateAccountSettingsOptions.Mfa + } + if updateAccountSettingsOptions.UserMfa != nil { + body["user_mfa"] = updateAccountSettingsOptions.UserMfa + } + if updateAccountSettingsOptions.SessionExpirationInSeconds != nil { + body["session_expiration_in_seconds"] = updateAccountSettingsOptions.SessionExpirationInSeconds + } + if updateAccountSettingsOptions.SessionInvalidationInSeconds != nil { + body["session_invalidation_in_seconds"] = updateAccountSettingsOptions.SessionInvalidationInSeconds + } + if updateAccountSettingsOptions.MaxSessionsPerIdentity != nil { + body["max_sessions_per_identity"] = updateAccountSettingsOptions.MaxSessionsPerIdentity + } + if updateAccountSettingsOptions.SystemAccessTokenExpirationInSeconds != nil { + body["system_access_token_expiration_in_seconds"] = updateAccountSettingsOptions.SystemAccessTokenExpirationInSeconds + } + if updateAccountSettingsOptions.SystemRefreshTokenExpirationInSeconds != nil { + body["system_refresh_token_expiration_in_seconds"] = updateAccountSettingsOptions.SystemRefreshTokenExpirationInSeconds + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -3206,12 +3680,12 @@ func (iamIdentity *IamIdentityV1) CreateMfaReportWithContext(ctx context.Context var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_mfa_report", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "updateAccountSettings", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReportReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3222,52 +3696,57 @@ func (iamIdentity *IamIdentityV1) CreateMfaReportWithContext(ctx context.Context return } -// GetMfaReport : Get MFA enrollment status report for the account -// Get MFA enrollment status report for the account by specifying the account ID and the reference that is generated by -// triggering the report. Reports older than a day are deleted when generating a new report. -func (iamIdentity *IamIdentityV1) GetMfaReport(getMfaReportOptions *GetMfaReportOptions) (result *ReportMfaEnrollmentStatus, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetMfaReportWithContext(context.Background(), getMfaReportOptions) +// GetEffectiveAccountSettings : Get effective account settings configuration +// Returns effective account settings for given account ID. +func (iamIdentity *IamIdentityV1) GetEffectiveAccountSettings(getEffectiveAccountSettingsOptions *GetEffectiveAccountSettingsOptions) (result *EffectiveAccountSettingsResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetEffectiveAccountSettingsWithContext(context.Background(), getEffectiveAccountSettingsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetMfaReportWithContext is an alternate form of the GetMfaReport method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetMfaReportWithContext(ctx context.Context, getMfaReportOptions *GetMfaReportOptions) (result *ReportMfaEnrollmentStatus, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getMfaReportOptions, "getMfaReportOptions cannot be nil") +// GetEffectiveAccountSettingsWithContext is an alternate form of the GetEffectiveAccountSettings method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetEffectiveAccountSettingsWithContext(ctx context.Context, getEffectiveAccountSettingsOptions *GetEffectiveAccountSettingsOptions) (result *EffectiveAccountSettingsResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getEffectiveAccountSettingsOptions, "getEffectiveAccountSettingsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getMfaReportOptions, "getMfaReportOptions") + err = core.ValidateStruct(getEffectiveAccountSettingsOptions, "getEffectiveAccountSettingsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *getMfaReportOptions.AccountID, - "reference": *getMfaReportOptions.Reference, + "account_id": *getEffectiveAccountSettingsOptions.AccountID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/mfa/accounts/{account_id}/report/{reference}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/accounts/{account_id}/effective_settings/identity`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getMfaReportOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetEffectiveAccountSettings") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetMfaReport") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getEffectiveAccountSettingsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + if getEffectiveAccountSettingsOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getEffectiveAccountSettingsOptions.IncludeHistory)) + } + if getEffectiveAccountSettingsOptions.ResolveUserMfa != nil { + builder.AddQuery("resolve_user_mfa", fmt.Sprint(*getEffectiveAccountSettingsOptions.ResolveUserMfa)) + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -3277,12 +3756,12 @@ func (iamIdentity *IamIdentityV1) GetMfaReportWithContext(ctx context.Context, g var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_mfa_report", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_effective_account_settings", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReportMfaEnrollmentStatus) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEffectiveAccountSettingsResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3293,71 +3772,51 @@ func (iamIdentity *IamIdentityV1) GetMfaReportWithContext(ctx context.Context, g return } -// ListAccountSettingsAssignments : List assignments -// List account settings assignments. -func (iamIdentity *IamIdentityV1) ListAccountSettingsAssignments(listAccountSettingsAssignmentsOptions *ListAccountSettingsAssignmentsOptions) (result *TemplateAssignmentListResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.ListAccountSettingsAssignmentsWithContext(context.Background(), listAccountSettingsAssignmentsOptions) +// GetMfaStatus : Get MFA enrollment status for a single user in the account +// Get MFA enrollment status for a single user in the account. +func (iamIdentity *IamIdentityV1) GetMfaStatus(getMfaStatusOptions *GetMfaStatusOptions) (result *UserMfaEnrollments, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetMfaStatusWithContext(context.Background(), getMfaStatusOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListAccountSettingsAssignmentsWithContext is an alternate form of the ListAccountSettingsAssignments method which supports a Context parameter -func (iamIdentity *IamIdentityV1) ListAccountSettingsAssignmentsWithContext(ctx context.Context, listAccountSettingsAssignmentsOptions *ListAccountSettingsAssignmentsOptions) (result *TemplateAssignmentListResponse, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listAccountSettingsAssignmentsOptions, "listAccountSettingsAssignmentsOptions") +// GetMfaStatusWithContext is an alternate form of the GetMfaStatus method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetMfaStatusWithContext(ctx context.Context, getMfaStatusOptions *GetMfaStatusOptions) (result *UserMfaEnrollments, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getMfaStatusOptions, "getMfaStatusOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getMfaStatusOptions, "getMfaStatusOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "account_id": *getMfaStatusOptions.AccountID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/mfa/accounts/{account_id}/status`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listAccountSettingsAssignmentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetMfaStatus") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListAccountSettingsAssignments") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getMfaStatusOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if listAccountSettingsAssignmentsOptions.AccountID != nil { - builder.AddQuery("account_id", fmt.Sprint(*listAccountSettingsAssignmentsOptions.AccountID)) - } - if listAccountSettingsAssignmentsOptions.TemplateID != nil { - builder.AddQuery("template_id", fmt.Sprint(*listAccountSettingsAssignmentsOptions.TemplateID)) - } - if listAccountSettingsAssignmentsOptions.TemplateVersion != nil { - builder.AddQuery("template_version", fmt.Sprint(*listAccountSettingsAssignmentsOptions.TemplateVersion)) - } - if listAccountSettingsAssignmentsOptions.Target != nil { - builder.AddQuery("target", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Target)) - } - if listAccountSettingsAssignmentsOptions.TargetType != nil { - builder.AddQuery("target_type", fmt.Sprint(*listAccountSettingsAssignmentsOptions.TargetType)) - } - if listAccountSettingsAssignmentsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Limit)) - } - if listAccountSettingsAssignmentsOptions.Pagetoken != nil { - builder.AddQuery("pagetoken", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Pagetoken)) - } - if listAccountSettingsAssignmentsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Sort)) - } - if listAccountSettingsAssignmentsOptions.Order != nil { - builder.AddQuery("order", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Order)) - } - if listAccountSettingsAssignmentsOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*listAccountSettingsAssignmentsOptions.IncludeHistory)) - } + builder.AddQuery("iam_id", fmt.Sprint(*getMfaStatusOptions.IamID)) request, err := builder.Build() if err != nil { @@ -3368,12 +3827,12 @@ func (iamIdentity *IamIdentityV1) ListAccountSettingsAssignmentsWithContext(ctx var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_account_settings_assignments", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_mfa_status", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentListResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalUserMfaEnrollments) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3384,66 +3843,55 @@ func (iamIdentity *IamIdentityV1) ListAccountSettingsAssignmentsWithContext(ctx return } -// CreateAccountSettingsAssignment : Create assignment -// Create an assigment for an account settings template. -func (iamIdentity *IamIdentityV1) CreateAccountSettingsAssignment(createAccountSettingsAssignmentOptions *CreateAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateAccountSettingsAssignmentWithContext(context.Background(), createAccountSettingsAssignmentOptions) +// CreateMfaReport : Trigger MFA enrollment status report for the account +// Trigger MFA enrollment status report for the account by specifying the account ID. It can take a few minutes to +// generate the report for retrieval. +func (iamIdentity *IamIdentityV1) CreateMfaReport(createMfaReportOptions *CreateMfaReportOptions) (result *ReportReference, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateMfaReportWithContext(context.Background(), createMfaReportOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateAccountSettingsAssignmentWithContext is an alternate form of the CreateAccountSettingsAssignment method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateAccountSettingsAssignmentWithContext(ctx context.Context, createAccountSettingsAssignmentOptions *CreateAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createAccountSettingsAssignmentOptions, "createAccountSettingsAssignmentOptions cannot be nil") +// CreateMfaReportWithContext is an alternate form of the CreateMfaReport method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateMfaReportWithContext(ctx context.Context, createMfaReportOptions *CreateMfaReportOptions) (result *ReportReference, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createMfaReportOptions, "createMfaReportOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createAccountSettingsAssignmentOptions, "createAccountSettingsAssignmentOptions") + err = core.ValidateStruct(createMfaReportOptions, "createMfaReportOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "account_id": *createMfaReportOptions.AccountID, + } + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/`, nil) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range createAccountSettingsAssignmentOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateAccountSettingsAssignment") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - - body := make(map[string]interface{}) - if createAccountSettingsAssignmentOptions.TemplateID != nil { - body["template_id"] = createAccountSettingsAssignmentOptions.TemplateID - } - if createAccountSettingsAssignmentOptions.TemplateVersion != nil { - body["template_version"] = createAccountSettingsAssignmentOptions.TemplateVersion - } - if createAccountSettingsAssignmentOptions.TargetType != nil { - body["target_type"] = createAccountSettingsAssignmentOptions.TargetType - } - if createAccountSettingsAssignmentOptions.Target != nil { - body["target"] = createAccountSettingsAssignmentOptions.Target - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/mfa/accounts/{account_id}/report`, pathParamsMap) if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateMfaReport") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range createMfaReportOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + if createMfaReportOptions.Type != nil { + builder.AddQuery("type", fmt.Sprint(*createMfaReportOptions.Type)) + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -3453,12 +3901,12 @@ func (iamIdentity *IamIdentityV1) CreateAccountSettingsAssignmentWithContext(ctx var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_account_settings_assignment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_mfa_report", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReportReference) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3469,54 +3917,52 @@ func (iamIdentity *IamIdentityV1) CreateAccountSettingsAssignmentWithContext(ctx return } -// GetAccountSettingsAssignment : Get assignment -// Get an assigment for an account settings template. -func (iamIdentity *IamIdentityV1) GetAccountSettingsAssignment(getAccountSettingsAssignmentOptions *GetAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetAccountSettingsAssignmentWithContext(context.Background(), getAccountSettingsAssignmentOptions) +// GetMfaReport : Get MFA enrollment status report for the account +// Get MFA enrollment status report for the account by specifying the account ID and the reference that is generated by +// triggering the report. Reports older than a day are deleted when generating a new report. +func (iamIdentity *IamIdentityV1) GetMfaReport(getMfaReportOptions *GetMfaReportOptions) (result *ReportMfaEnrollmentStatus, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetMfaReportWithContext(context.Background(), getMfaReportOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetAccountSettingsAssignmentWithContext is an alternate form of the GetAccountSettingsAssignment method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetAccountSettingsAssignmentWithContext(ctx context.Context, getAccountSettingsAssignmentOptions *GetAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getAccountSettingsAssignmentOptions, "getAccountSettingsAssignmentOptions cannot be nil") +// GetMfaReportWithContext is an alternate form of the GetMfaReport method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetMfaReportWithContext(ctx context.Context, getMfaReportOptions *GetMfaReportOptions) (result *ReportMfaEnrollmentStatus, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getMfaReportOptions, "getMfaReportOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getAccountSettingsAssignmentOptions, "getAccountSettingsAssignmentOptions") + err = core.ValidateStruct(getMfaReportOptions, "getMfaReportOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "assignment_id": *getAccountSettingsAssignmentOptions.AssignmentID, + "account_id": *getMfaReportOptions.AccountID, + "reference": *getMfaReportOptions.Reference, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/{assignment_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/mfa/accounts/{account_id}/report/{reference}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getAccountSettingsAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetMfaReport") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAccountSettingsAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getMfaReportOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if getAccountSettingsAssignmentOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getAccountSettingsAssignmentOptions.IncludeHistory)) - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -3526,12 +3972,12 @@ func (iamIdentity *IamIdentityV1) GetAccountSettingsAssignmentWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_account_settings_assignment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_mfa_report", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReportMfaEnrollmentStatus) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3542,50 +3988,110 @@ func (iamIdentity *IamIdentityV1) GetAccountSettingsAssignmentWithContext(ctx co return } -// DeleteAccountSettingsAssignment : Delete assignment -// Delete an account settings template assignment. This removes any IAM resources created by this assignment in child -// accounts. -func (iamIdentity *IamIdentityV1) DeleteAccountSettingsAssignment(deleteAccountSettingsAssignmentOptions *DeleteAccountSettingsAssignmentOptions) (result *ExceptionResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.DeleteAccountSettingsAssignmentWithContext(context.Background(), deleteAccountSettingsAssignmentOptions) +// UpdatePreferenceOnScopeAccount : Update Identity Preference on scope account +// Update one Identity Preference on scope `account`. +// +// The following preferences are storing values for identities inside an account, i.e. for each account that an +// identity is member of, the value stored might be different. This means, **users** who might be member of multiple +// accounts can have multiple preferences, one per account. Identities like **Service Ids** or **Trusted Profiles** can +// only exist in one account, therefore they can only have one preference inside their related account. +// +// ### Preferences +// +// - **console/landing_page** +// +// service: `console` +// +// preference_id: `landing_page` +// +// supported identity types: `Trusted Profile` +// +// type: `string` +// +// validation: valid path for the IBM Cloud Console (without host part), e.g. `/billing` or `/iam` +// +// - **console/global_left_navigation** +// +// service: `console` +// +// preference_id: `global_left_navigation` +// +// supported identity types: `Trusted Profile` +// +// type: `list of strings` +// +// validation: each entry in the list of strings must match the identifier of one navigation entry in the console; +// these identifiers are defined and interpreted by the IBM Cloud Console; currently the following entries are +// supported: +// +// `slash,projects,rex,containers,databases,is,logmet,automation,complianceAndSecurity,apis,cp4d,partner-center,sap,satellite,vmWare,watsonx` +// +// ### Authorization +// +// To call this method for the identity type `Trusted Profile`, you must be assigned one or more IAM access roles that +// include the following action on the target resource `account` and resource type `preferences`: +// +// - iam-identity.preferences.update +// +// By default, the `Administrator` role on service `iam-identity` contains this action. +func (iamIdentity *IamIdentityV1) UpdatePreferenceOnScopeAccount(updatePreferenceOnScopeAccountOptions *UpdatePreferenceOnScopeAccountOptions) (result *IdentityPreferenceResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdatePreferenceOnScopeAccountWithContext(context.Background(), updatePreferenceOnScopeAccountOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteAccountSettingsAssignmentWithContext is an alternate form of the DeleteAccountSettingsAssignment method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeleteAccountSettingsAssignmentWithContext(ctx context.Context, deleteAccountSettingsAssignmentOptions *DeleteAccountSettingsAssignmentOptions) (result *ExceptionResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteAccountSettingsAssignmentOptions, "deleteAccountSettingsAssignmentOptions cannot be nil") +// UpdatePreferenceOnScopeAccountWithContext is an alternate form of the UpdatePreferenceOnScopeAccount method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdatePreferenceOnScopeAccountWithContext(ctx context.Context, updatePreferenceOnScopeAccountOptions *UpdatePreferenceOnScopeAccountOptions) (result *IdentityPreferenceResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updatePreferenceOnScopeAccountOptions, "updatePreferenceOnScopeAccountOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteAccountSettingsAssignmentOptions, "deleteAccountSettingsAssignmentOptions") + err = core.ValidateStruct(updatePreferenceOnScopeAccountOptions, "updatePreferenceOnScopeAccountOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "assignment_id": *deleteAccountSettingsAssignmentOptions.AssignmentID, + "account_id": *updatePreferenceOnScopeAccountOptions.AccountID, + "iam_id": *updatePreferenceOnScopeAccountOptions.IamID, + "service": *updatePreferenceOnScopeAccountOptions.Service, + "preference_id": *updatePreferenceOnScopeAccountOptions.PreferenceID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/{assignment_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/preferences/accounts/{account_id}/identities/{iam_id}/{service}/{preference_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteAccountSettingsAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdatePreferenceOnScopeAccount") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAccountSettingsAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updatePreferenceOnScopeAccountOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if updatePreferenceOnScopeAccountOptions.ValueString != nil { + body["value_string"] = updatePreferenceOnScopeAccountOptions.ValueString + } + if updatePreferenceOnScopeAccountOptions.ValueListOfStrings != nil { + body["value_list_of_strings"] = updatePreferenceOnScopeAccountOptions.ValueListOfStrings + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } request, err := builder.Build() if err != nil { @@ -3596,12 +4102,12 @@ func (iamIdentity *IamIdentityV1) DeleteAccountSettingsAssignmentWithContext(ctx var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_account_settings_assignment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_preference_on_scope_account", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalExceptionResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIdentityPreferenceResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3612,63 +4118,52 @@ func (iamIdentity *IamIdentityV1) DeleteAccountSettingsAssignmentWithContext(ctx return } -// UpdateAccountSettingsAssignment : Update assignment -// Update an account settings assignment. Call this method to retry failed assignments or migrate the settings in child -// accounts to a new version. -func (iamIdentity *IamIdentityV1) UpdateAccountSettingsAssignment(updateAccountSettingsAssignmentOptions *UpdateAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.UpdateAccountSettingsAssignmentWithContext(context.Background(), updateAccountSettingsAssignmentOptions) +// DeletePreferencesOnScopeAccount : Delete Identity Preference on scope account +// Delete one Identity Preference on scope `account`. For details about the preferences supported and how the method +// request is authorized, refer to the description of operation +// `Update Identity Preference on scope account`. +func (iamIdentity *IamIdentityV1) DeletePreferencesOnScopeAccount(deletePreferencesOnScopeAccountOptions *DeletePreferencesOnScopeAccountOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeletePreferencesOnScopeAccountWithContext(context.Background(), deletePreferencesOnScopeAccountOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateAccountSettingsAssignmentWithContext is an alternate form of the UpdateAccountSettingsAssignment method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UpdateAccountSettingsAssignmentWithContext(ctx context.Context, updateAccountSettingsAssignmentOptions *UpdateAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateAccountSettingsAssignmentOptions, "updateAccountSettingsAssignmentOptions cannot be nil") +// DeletePreferencesOnScopeAccountWithContext is an alternate form of the DeletePreferencesOnScopeAccount method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeletePreferencesOnScopeAccountWithContext(ctx context.Context, deletePreferencesOnScopeAccountOptions *DeletePreferencesOnScopeAccountOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deletePreferencesOnScopeAccountOptions, "deletePreferencesOnScopeAccountOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateAccountSettingsAssignmentOptions, "updateAccountSettingsAssignmentOptions") + err = core.ValidateStruct(deletePreferencesOnScopeAccountOptions, "deletePreferencesOnScopeAccountOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "assignment_id": *updateAccountSettingsAssignmentOptions.AssignmentID, + "account_id": *deletePreferencesOnScopeAccountOptions.AccountID, + "iam_id": *deletePreferencesOnScopeAccountOptions.IamID, + "service": *deletePreferencesOnScopeAccountOptions.Service, + "preference_id": *deletePreferencesOnScopeAccountOptions.PreferenceID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/{assignment_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/preferences/accounts/{account_id}/identities/{iam_id}/{service}/{preference_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateAccountSettingsAssignmentOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateAccountSettingsAssignment") + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeletePreferencesOnScopeAccount") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - if updateAccountSettingsAssignmentOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateAccountSettingsAssignmentOptions.IfMatch)) - } - body := make(map[string]interface{}) - if updateAccountSettingsAssignmentOptions.TemplateVersion != nil { - body["template_version"] = updateAccountSettingsAssignmentOptions.TemplateVersion - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + for headerName, headerValue := range deletePreferencesOnScopeAccountOptions.Headers { + builder.AddHeader(headerName, headerValue) } request, err := builder.Build() @@ -3677,79 +4172,79 @@ func (iamIdentity *IamIdentityV1) UpdateAccountSettingsAssignmentWithContext(ctx return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "update_account_settings_assignment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_preferences_on_scope_account", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListAccountSettingsTemplates : List account settings templates -// List account settings templates in an enterprise account. -func (iamIdentity *IamIdentityV1) ListAccountSettingsTemplates(listAccountSettingsTemplatesOptions *ListAccountSettingsTemplatesOptions) (result *AccountSettingsTemplateList, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.ListAccountSettingsTemplatesWithContext(context.Background(), listAccountSettingsTemplatesOptions) +// GetPreferencesOnScopeAccount : Get Identity Preference on scope account +// Get one Identity Preference on scope `account`. For details about the preferences supported, refer to the +// description of operation `Update Identity Preference on scope account`. +// +// ### Authorization +// +// To call this method for the identity type `Trusted Profile`, one of the following conditions must be true: +// +// - the Authorization token represents the trusted profile which is addressed by this request +// +// - you must be assigned one or more IAM access roles that include the following action on the target resource +// `account` and resource type `preferences`: +// +// - iam-identity.preferences.update +// +// By default, the `Administrator` role on service `iam-identity` contains this action. +// +// - Services inside the IBM Cloud Console can call this method. +func (iamIdentity *IamIdentityV1) GetPreferencesOnScopeAccount(getPreferencesOnScopeAccountOptions *GetPreferencesOnScopeAccountOptions) (result *IdentityPreferenceResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetPreferencesOnScopeAccountWithContext(context.Background(), getPreferencesOnScopeAccountOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListAccountSettingsTemplatesWithContext is an alternate form of the ListAccountSettingsTemplates method which supports a Context parameter -func (iamIdentity *IamIdentityV1) ListAccountSettingsTemplatesWithContext(ctx context.Context, listAccountSettingsTemplatesOptions *ListAccountSettingsTemplatesOptions) (result *AccountSettingsTemplateList, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listAccountSettingsTemplatesOptions, "listAccountSettingsTemplatesOptions") +// GetPreferencesOnScopeAccountWithContext is an alternate form of the GetPreferencesOnScopeAccount method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetPreferencesOnScopeAccountWithContext(ctx context.Context, getPreferencesOnScopeAccountOptions *GetPreferencesOnScopeAccountOptions) (result *IdentityPreferenceResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getPreferencesOnScopeAccountOptions, "getPreferencesOnScopeAccountOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getPreferencesOnScopeAccountOptions, "getPreferencesOnScopeAccountOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "account_id": *getPreferencesOnScopeAccountOptions.AccountID, + "iam_id": *getPreferencesOnScopeAccountOptions.IamID, + "service": *getPreferencesOnScopeAccountOptions.Service, + "preference_id": *getPreferencesOnScopeAccountOptions.PreferenceID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/preferences/accounts/{account_id}/identities/{iam_id}/{service}/{preference_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listAccountSettingsTemplatesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetPreferencesOnScopeAccount") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListAccountSettingsTemplates") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPreferencesOnScopeAccountOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if listAccountSettingsTemplatesOptions.AccountID != nil { - builder.AddQuery("account_id", fmt.Sprint(*listAccountSettingsTemplatesOptions.AccountID)) - } - if listAccountSettingsTemplatesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listAccountSettingsTemplatesOptions.Limit)) - } - if listAccountSettingsTemplatesOptions.Pagetoken != nil { - builder.AddQuery("pagetoken", fmt.Sprint(*listAccountSettingsTemplatesOptions.Pagetoken)) - } - if listAccountSettingsTemplatesOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listAccountSettingsTemplatesOptions.Sort)) - } - if listAccountSettingsTemplatesOptions.Order != nil { - builder.AddQuery("order", fmt.Sprint(*listAccountSettingsTemplatesOptions.Order)) - } - if listAccountSettingsTemplatesOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*listAccountSettingsTemplatesOptions.IncludeHistory)) - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -3759,12 +4254,12 @@ func (iamIdentity *IamIdentityV1) ListAccountSettingsTemplatesWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_account_settings_templates", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_preferences_on_scope_account", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateList) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIdentityPreferenceResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3775,65 +4270,55 @@ func (iamIdentity *IamIdentityV1) ListAccountSettingsTemplatesWithContext(ctx co return } -// CreateAccountSettingsTemplate : Create an account settings template -// Create a new account settings template in an enterprise account. -func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplate(createAccountSettingsTemplateOptions *CreateAccountSettingsTemplateOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateAccountSettingsTemplateWithContext(context.Background(), createAccountSettingsTemplateOptions) +// GetAllPreferencesOnScopeAccount : Get all Identity Preferences on scope account +// Get all Identity Preferences for one account / identity combination. For details about the preferences supported and +// how the method request is authorized, refer to the description of operation +// `Get Identity Preference on scope account`. +// +// If you are not allowed to read a preference, the call will not fail. Instead, this preference is/ these preferences +// are not returned in the list call. +func (iamIdentity *IamIdentityV1) GetAllPreferencesOnScopeAccount(getAllPreferencesOnScopeAccountOptions *GetAllPreferencesOnScopeAccountOptions) (result *IdentityPreferencesResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetAllPreferencesOnScopeAccountWithContext(context.Background(), getAllPreferencesOnScopeAccountOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateAccountSettingsTemplateWithContext is an alternate form of the CreateAccountSettingsTemplate method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplateWithContext(ctx context.Context, createAccountSettingsTemplateOptions *CreateAccountSettingsTemplateOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createAccountSettingsTemplateOptions, "createAccountSettingsTemplateOptions cannot be nil") +// GetAllPreferencesOnScopeAccountWithContext is an alternate form of the GetAllPreferencesOnScopeAccount method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetAllPreferencesOnScopeAccountWithContext(ctx context.Context, getAllPreferencesOnScopeAccountOptions *GetAllPreferencesOnScopeAccountOptions) (result *IdentityPreferencesResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getAllPreferencesOnScopeAccountOptions, "getAllPreferencesOnScopeAccountOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createAccountSettingsTemplateOptions, "createAccountSettingsTemplateOptions") + err = core.ValidateStruct(getAllPreferencesOnScopeAccountOptions, "getAllPreferencesOnScopeAccountOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "account_id": *getAllPreferencesOnScopeAccountOptions.AccountID, + "iam_id": *getAllPreferencesOnScopeAccountOptions.IamID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/preferences/accounts/{account_id}/identities/{iam_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createAccountSettingsTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAllPreferencesOnScopeAccount") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateAccountSettingsTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getAllPreferencesOnScopeAccountOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - - body := make(map[string]interface{}) - if createAccountSettingsTemplateOptions.AccountID != nil { - body["account_id"] = createAccountSettingsTemplateOptions.AccountID - } - if createAccountSettingsTemplateOptions.Name != nil { - body["name"] = createAccountSettingsTemplateOptions.Name - } - if createAccountSettingsTemplateOptions.Description != nil { - body["description"] = createAccountSettingsTemplateOptions.Description - } - if createAccountSettingsTemplateOptions.AccountSettings != nil { - body["account_settings"] = createAccountSettingsTemplateOptions.AccountSettings - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } request, err := builder.Build() if err != nil { @@ -3844,12 +4329,12 @@ func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplateWithContext(ctx c var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_account_settings_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_all_preferences_on_scope_account", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIdentityPreferencesResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3860,52 +4345,58 @@ func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplateWithContext(ctx c return } -// GetLatestAccountSettingsTemplateVersion : Get latest version of an account settings template -// Get the latest version of a specific account settings template in an enterprise account. -func (iamIdentity *IamIdentityV1) GetLatestAccountSettingsTemplateVersion(getLatestAccountSettingsTemplateVersionOptions *GetLatestAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetLatestAccountSettingsTemplateVersionWithContext(context.Background(), getLatestAccountSettingsTemplateVersionOptions) +// ListProfileTemplates : List trusted profile templates +// List the trusted profile templates in an enterprise account. +func (iamIdentity *IamIdentityV1) ListProfileTemplates(listProfileTemplatesOptions *ListProfileTemplatesOptions) (result *TrustedProfileTemplateList, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListProfileTemplatesWithContext(context.Background(), listProfileTemplatesOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLatestAccountSettingsTemplateVersionWithContext is an alternate form of the GetLatestAccountSettingsTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetLatestAccountSettingsTemplateVersionWithContext(ctx context.Context, getLatestAccountSettingsTemplateVersionOptions *GetLatestAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLatestAccountSettingsTemplateVersionOptions, "getLatestAccountSettingsTemplateVersionOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getLatestAccountSettingsTemplateVersionOptions, "getLatestAccountSettingsTemplateVersionOptions") +// ListProfileTemplatesWithContext is an alternate form of the ListProfileTemplates method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListProfileTemplatesWithContext(ctx context.Context, listProfileTemplatesOptions *ListProfileTemplatesOptions) (result *TrustedProfileTemplateList, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listProfileTemplatesOptions, "listProfileTemplatesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "template_id": *getLatestAccountSettingsTemplateVersionOptions.TemplateID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLatestAccountSettingsTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListProfileTemplates") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetLatestAccountSettingsTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listProfileTemplatesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if getLatestAccountSettingsTemplateVersionOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getLatestAccountSettingsTemplateVersionOptions.IncludeHistory)) + if listProfileTemplatesOptions.AccountID != nil { + builder.AddQuery("account_id", fmt.Sprint(*listProfileTemplatesOptions.AccountID)) + } + if listProfileTemplatesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listProfileTemplatesOptions.Limit)) + } + if listProfileTemplatesOptions.Pagetoken != nil { + builder.AddQuery("pagetoken", fmt.Sprint(*listProfileTemplatesOptions.Pagetoken)) + } + if listProfileTemplatesOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listProfileTemplatesOptions.Sort)) + } + if listProfileTemplatesOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listProfileTemplatesOptions.Order)) + } + if listProfileTemplatesOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*listProfileTemplatesOptions.IncludeHistory)) } request, err := builder.Build() @@ -3917,12 +4408,12 @@ func (iamIdentity *IamIdentityV1) GetLatestAccountSettingsTemplateVersionWithCon var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_latest_account_settings_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_profile_templates", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateList) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3933,49 +4424,71 @@ func (iamIdentity *IamIdentityV1) GetLatestAccountSettingsTemplateVersionWithCon return } -// DeleteAllVersionsOfAccountSettingsTemplate : Delete all versions of an account settings template -// Delete all versions of an account settings template in an enterprise account. If any version is assigned to child -// accounts, you must first delete the assignment. -func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfAccountSettingsTemplate(deleteAllVersionsOfAccountSettingsTemplateOptions *DeleteAllVersionsOfAccountSettingsTemplateOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.DeleteAllVersionsOfAccountSettingsTemplateWithContext(context.Background(), deleteAllVersionsOfAccountSettingsTemplateOptions) +// CreateProfileTemplate : Create a trusted profile template +// Create a new trusted profile template in an enterprise account. +func (iamIdentity *IamIdentityV1) CreateProfileTemplate(createProfileTemplateOptions *CreateProfileTemplateOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateProfileTemplateWithContext(context.Background(), createProfileTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteAllVersionsOfAccountSettingsTemplateWithContext is an alternate form of the DeleteAllVersionsOfAccountSettingsTemplate method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfAccountSettingsTemplateWithContext(ctx context.Context, deleteAllVersionsOfAccountSettingsTemplateOptions *DeleteAllVersionsOfAccountSettingsTemplateOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteAllVersionsOfAccountSettingsTemplateOptions, "deleteAllVersionsOfAccountSettingsTemplateOptions cannot be nil") +// CreateProfileTemplateWithContext is an alternate form of the CreateProfileTemplate method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateProfileTemplateWithContext(ctx context.Context, createProfileTemplateOptions *CreateProfileTemplateOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createProfileTemplateOptions, "createProfileTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteAllVersionsOfAccountSettingsTemplateOptions, "deleteAllVersionsOfAccountSettingsTemplateOptions") + err = core.ValidateStruct(createProfileTemplateOptions, "createProfileTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "template_id": *deleteAllVersionsOfAccountSettingsTemplateOptions.TemplateID, - } - - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteAllVersionsOfAccountSettingsTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateProfileTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAllVersionsOfAccountSettingsTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createProfileTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if createProfileTemplateOptions.AccountID != nil { + body["account_id"] = createProfileTemplateOptions.AccountID + } + if createProfileTemplateOptions.Name != nil { + body["name"] = createProfileTemplateOptions.Name + } + if createProfileTemplateOptions.Description != nil { + body["description"] = createProfileTemplateOptions.Description + } + if createProfileTemplateOptions.Profile != nil { + body["profile"] = createProfileTemplateOptions.Profile + } + if createProfileTemplateOptions.PolicyTemplateReferences != nil { + body["policy_template_references"] = createProfileTemplateOptions.PolicyTemplateReferences + } + if createProfileTemplateOptions.ActionControls != nil { + body["action_controls"] = createProfileTemplateOptions.ActionControls + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } request, err := builder.Build() if err != nil { @@ -3983,74 +4496,71 @@ func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfAccountSettingsTemplateWith return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_all_versions_of_account_settings_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_profile_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListVersionsOfAccountSettingsTemplate : List account settings template versions -// List the versions of a specific account settings template in an enterprise account. -func (iamIdentity *IamIdentityV1) ListVersionsOfAccountSettingsTemplate(listVersionsOfAccountSettingsTemplateOptions *ListVersionsOfAccountSettingsTemplateOptions) (result *AccountSettingsTemplateList, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.ListVersionsOfAccountSettingsTemplateWithContext(context.Background(), listVersionsOfAccountSettingsTemplateOptions) +// GetLatestProfileTemplateVersion : Get latest version of a trusted profile template +// Get the latest version of a trusted profile template in an enterprise account. +func (iamIdentity *IamIdentityV1) GetLatestProfileTemplateVersion(getLatestProfileTemplateVersionOptions *GetLatestProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetLatestProfileTemplateVersionWithContext(context.Background(), getLatestProfileTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVersionsOfAccountSettingsTemplateWithContext is an alternate form of the ListVersionsOfAccountSettingsTemplate method which supports a Context parameter -func (iamIdentity *IamIdentityV1) ListVersionsOfAccountSettingsTemplateWithContext(ctx context.Context, listVersionsOfAccountSettingsTemplateOptions *ListVersionsOfAccountSettingsTemplateOptions) (result *AccountSettingsTemplateList, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVersionsOfAccountSettingsTemplateOptions, "listVersionsOfAccountSettingsTemplateOptions cannot be nil") +// GetLatestProfileTemplateVersionWithContext is an alternate form of the GetLatestProfileTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetLatestProfileTemplateVersionWithContext(ctx context.Context, getLatestProfileTemplateVersionOptions *GetLatestProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLatestProfileTemplateVersionOptions, "getLatestProfileTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVersionsOfAccountSettingsTemplateOptions, "listVersionsOfAccountSettingsTemplateOptions") + err = core.ValidateStruct(getLatestProfileTemplateVersionOptions, "getLatestProfileTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *listVersionsOfAccountSettingsTemplateOptions.TemplateID, + "template_id": *getLatestProfileTemplateVersionOptions.TemplateID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVersionsOfAccountSettingsTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetLatestProfileTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListVersionsOfAccountSettingsTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLatestProfileTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if listVersionsOfAccountSettingsTemplateOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.Limit)) - } - if listVersionsOfAccountSettingsTemplateOptions.Pagetoken != nil { - builder.AddQuery("pagetoken", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.Pagetoken)) - } - if listVersionsOfAccountSettingsTemplateOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.Sort)) - } - if listVersionsOfAccountSettingsTemplateOptions.Order != nil { - builder.AddQuery("order", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.Order)) - } - if listVersionsOfAccountSettingsTemplateOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.IncludeHistory)) + if getLatestProfileTemplateVersionOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getLatestProfileTemplateVersionOptions.IncludeHistory)) } request, err := builder.Build() @@ -4062,12 +4572,12 @@ func (iamIdentity *IamIdentityV1) ListVersionsOfAccountSettingsTemplateWithConte var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_versions_of_account_settings_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_latest_profile_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateList) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4078,142 +4588,124 @@ func (iamIdentity *IamIdentityV1) ListVersionsOfAccountSettingsTemplateWithConte return } -// CreateAccountSettingsTemplateVersion : Create a new version of an account settings template -// Create a new version of an account settings template in an Enterprise Account. -func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplateVersion(createAccountSettingsTemplateVersionOptions *CreateAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateAccountSettingsTemplateVersionWithContext(context.Background(), createAccountSettingsTemplateVersionOptions) +// DeleteAllVersionsOfProfileTemplate : Delete all versions of a trusted profile template +// Delete all versions of a trusted profile template in an enterprise account. If any version is assigned to child +// accounts, you must first delete the assignment. +func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfProfileTemplate(deleteAllVersionsOfProfileTemplateOptions *DeleteAllVersionsOfProfileTemplateOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeleteAllVersionsOfProfileTemplateWithContext(context.Background(), deleteAllVersionsOfProfileTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateAccountSettingsTemplateVersionWithContext is an alternate form of the CreateAccountSettingsTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplateVersionWithContext(ctx context.Context, createAccountSettingsTemplateVersionOptions *CreateAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createAccountSettingsTemplateVersionOptions, "createAccountSettingsTemplateVersionOptions cannot be nil") +// DeleteAllVersionsOfProfileTemplateWithContext is an alternate form of the DeleteAllVersionsOfProfileTemplate method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfProfileTemplateWithContext(ctx context.Context, deleteAllVersionsOfProfileTemplateOptions *DeleteAllVersionsOfProfileTemplateOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteAllVersionsOfProfileTemplateOptions, "deleteAllVersionsOfProfileTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createAccountSettingsTemplateVersionOptions, "createAccountSettingsTemplateVersionOptions") + err = core.ValidateStruct(deleteAllVersionsOfProfileTemplateOptions, "deleteAllVersionsOfProfileTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *createAccountSettingsTemplateVersionOptions.TemplateID, + "template_id": *deleteAllVersionsOfProfileTemplateOptions.TemplateID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range createAccountSettingsTemplateVersionOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateAccountSettingsTemplateVersion") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - - body := make(map[string]interface{}) - if createAccountSettingsTemplateVersionOptions.AccountID != nil { - body["account_id"] = createAccountSettingsTemplateVersionOptions.AccountID - } - if createAccountSettingsTemplateVersionOptions.Name != nil { - body["name"] = createAccountSettingsTemplateVersionOptions.Name - } - if createAccountSettingsTemplateVersionOptions.Description != nil { - body["description"] = createAccountSettingsTemplateVersionOptions.Description - } - if createAccountSettingsTemplateVersionOptions.AccountSettings != nil { - body["account_settings"] = createAccountSettingsTemplateVersionOptions.AccountSettings - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}`, pathParamsMap) if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAllVersionsOfProfileTemplate") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range deleteAllVersionsOfProfileTemplateOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "create_account_settings_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_all_versions_of_profile_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetAccountSettingsTemplateVersion : Get version of an account settings template -// Get a specific version of an account settings template in an Enterprise Account. -func (iamIdentity *IamIdentityV1) GetAccountSettingsTemplateVersion(getAccountSettingsTemplateVersionOptions *GetAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetAccountSettingsTemplateVersionWithContext(context.Background(), getAccountSettingsTemplateVersionOptions) +// ListVersionsOfProfileTemplate : List trusted profile template versions +// List the versions of a trusted profile template in an enterprise account. +func (iamIdentity *IamIdentityV1) ListVersionsOfProfileTemplate(listVersionsOfProfileTemplateOptions *ListVersionsOfProfileTemplateOptions) (result *TrustedProfileTemplateList, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListVersionsOfProfileTemplateWithContext(context.Background(), listVersionsOfProfileTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetAccountSettingsTemplateVersionWithContext is an alternate form of the GetAccountSettingsTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetAccountSettingsTemplateVersionWithContext(ctx context.Context, getAccountSettingsTemplateVersionOptions *GetAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getAccountSettingsTemplateVersionOptions, "getAccountSettingsTemplateVersionOptions cannot be nil") +// ListVersionsOfProfileTemplateWithContext is an alternate form of the ListVersionsOfProfileTemplate method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListVersionsOfProfileTemplateWithContext(ctx context.Context, listVersionsOfProfileTemplateOptions *ListVersionsOfProfileTemplateOptions) (result *TrustedProfileTemplateList, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVersionsOfProfileTemplateOptions, "listVersionsOfProfileTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getAccountSettingsTemplateVersionOptions, "getAccountSettingsTemplateVersionOptions") + err = core.ValidateStruct(listVersionsOfProfileTemplateOptions, "listVersionsOfProfileTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *getAccountSettingsTemplateVersionOptions.TemplateID, - "version": *getAccountSettingsTemplateVersionOptions.Version, + "template_id": *listVersionsOfProfileTemplateOptions.TemplateID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions/{version}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getAccountSettingsTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListVersionsOfProfileTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAccountSettingsTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVersionsOfProfileTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if getAccountSettingsTemplateVersionOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getAccountSettingsTemplateVersionOptions.IncludeHistory)) + if listVersionsOfProfileTemplateOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVersionsOfProfileTemplateOptions.Limit)) + } + if listVersionsOfProfileTemplateOptions.Pagetoken != nil { + builder.AddQuery("pagetoken", fmt.Sprint(*listVersionsOfProfileTemplateOptions.Pagetoken)) + } + if listVersionsOfProfileTemplateOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listVersionsOfProfileTemplateOptions.Sort)) + } + if listVersionsOfProfileTemplateOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listVersionsOfProfileTemplateOptions.Order)) + } + if listVersionsOfProfileTemplateOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*listVersionsOfProfileTemplateOptions.IncludeHistory)) } request, err := builder.Build() @@ -4225,12 +4717,12 @@ func (iamIdentity *IamIdentityV1) GetAccountSettingsTemplateVersionWithContext(c var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_account_settings_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_versions_of_profile_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateList) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4241,67 +4733,69 @@ func (iamIdentity *IamIdentityV1) GetAccountSettingsTemplateVersionWithContext(c return } -// UpdateAccountSettingsTemplateVersion : Update version of an account settings template -// Update a specific version of an account settings template in an Enterprise Account. -func (iamIdentity *IamIdentityV1) UpdateAccountSettingsTemplateVersion(updateAccountSettingsTemplateVersionOptions *UpdateAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.UpdateAccountSettingsTemplateVersionWithContext(context.Background(), updateAccountSettingsTemplateVersionOptions) +// CreateProfileTemplateVersion : Create new version of a trusted profile template +// Create a new version of a trusted profile template in an enterprise account. +func (iamIdentity *IamIdentityV1) CreateProfileTemplateVersion(createProfileTemplateVersionOptions *CreateProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateProfileTemplateVersionWithContext(context.Background(), createProfileTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateAccountSettingsTemplateVersionWithContext is an alternate form of the UpdateAccountSettingsTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UpdateAccountSettingsTemplateVersionWithContext(ctx context.Context, updateAccountSettingsTemplateVersionOptions *UpdateAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateAccountSettingsTemplateVersionOptions, "updateAccountSettingsTemplateVersionOptions cannot be nil") +// CreateProfileTemplateVersionWithContext is an alternate form of the CreateProfileTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateProfileTemplateVersionWithContext(ctx context.Context, createProfileTemplateVersionOptions *CreateProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createProfileTemplateVersionOptions, "createProfileTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateAccountSettingsTemplateVersionOptions, "updateAccountSettingsTemplateVersionOptions") + err = core.ValidateStruct(createProfileTemplateVersionOptions, "createProfileTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *updateAccountSettingsTemplateVersionOptions.TemplateID, - "version": *updateAccountSettingsTemplateVersionOptions.Version, + "template_id": *createProfileTemplateVersionOptions.TemplateID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions/{version}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateAccountSettingsTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateProfileTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateAccountSettingsTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createProfileTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") - if updateAccountSettingsTemplateVersionOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateAccountSettingsTemplateVersionOptions.IfMatch)) - } body := make(map[string]interface{}) - if updateAccountSettingsTemplateVersionOptions.AccountID != nil { - body["account_id"] = updateAccountSettingsTemplateVersionOptions.AccountID + if createProfileTemplateVersionOptions.AccountID != nil { + body["account_id"] = createProfileTemplateVersionOptions.AccountID } - if updateAccountSettingsTemplateVersionOptions.Name != nil { - body["name"] = updateAccountSettingsTemplateVersionOptions.Name + if createProfileTemplateVersionOptions.Name != nil { + body["name"] = createProfileTemplateVersionOptions.Name } - if updateAccountSettingsTemplateVersionOptions.Description != nil { - body["description"] = updateAccountSettingsTemplateVersionOptions.Description + if createProfileTemplateVersionOptions.Description != nil { + body["description"] = createProfileTemplateVersionOptions.Description } - if updateAccountSettingsTemplateVersionOptions.AccountSettings != nil { - body["account_settings"] = updateAccountSettingsTemplateVersionOptions.AccountSettings + if createProfileTemplateVersionOptions.Profile != nil { + body["profile"] = createProfileTemplateVersionOptions.Profile + } + if createProfileTemplateVersionOptions.PolicyTemplateReferences != nil { + body["policy_template_references"] = createProfileTemplateVersionOptions.PolicyTemplateReferences + } + if createProfileTemplateVersionOptions.ActionControls != nil { + body["action_controls"] = createProfileTemplateVersionOptions.ActionControls } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -4318,12 +4812,12 @@ func (iamIdentity *IamIdentityV1) UpdateAccountSettingsTemplateVersionWithContex var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_account_settings_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_profile_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4334,49 +4828,54 @@ func (iamIdentity *IamIdentityV1) UpdateAccountSettingsTemplateVersionWithContex return } -// DeleteAccountSettingsTemplateVersion : Delete version of an account settings template -// Delete a specific version of an account settings template in an Enterprise Account. -func (iamIdentity *IamIdentityV1) DeleteAccountSettingsTemplateVersion(deleteAccountSettingsTemplateVersionOptions *DeleteAccountSettingsTemplateVersionOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.DeleteAccountSettingsTemplateVersionWithContext(context.Background(), deleteAccountSettingsTemplateVersionOptions) +// GetProfileTemplateVersion : Get version of trusted profile template +// Get a specific version of a trusted profile template in an enterprise account. +func (iamIdentity *IamIdentityV1) GetProfileTemplateVersion(getProfileTemplateVersionOptions *GetProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetProfileTemplateVersionWithContext(context.Background(), getProfileTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteAccountSettingsTemplateVersionWithContext is an alternate form of the DeleteAccountSettingsTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeleteAccountSettingsTemplateVersionWithContext(ctx context.Context, deleteAccountSettingsTemplateVersionOptions *DeleteAccountSettingsTemplateVersionOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteAccountSettingsTemplateVersionOptions, "deleteAccountSettingsTemplateVersionOptions cannot be nil") +// GetProfileTemplateVersionWithContext is an alternate form of the GetProfileTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetProfileTemplateVersionWithContext(ctx context.Context, getProfileTemplateVersionOptions *GetProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getProfileTemplateVersionOptions, "getProfileTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteAccountSettingsTemplateVersionOptions, "deleteAccountSettingsTemplateVersionOptions") + err = core.ValidateStruct(getProfileTemplateVersionOptions, "getProfileTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *deleteAccountSettingsTemplateVersionOptions.TemplateID, - "version": *deleteAccountSettingsTemplateVersionOptions.Version, + "template_id": *getProfileTemplateVersionOptions.TemplateID, + "version": *getProfileTemplateVersionOptions.Version, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions/{version}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions/{version}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteAccountSettingsTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetProfileTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAccountSettingsTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getProfileTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + + if getProfileTemplateVersionOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getProfileTemplateVersionOptions.IncludeHistory)) + } request, err := builder.Build() if err != nil { @@ -4384,60 +4883,98 @@ func (iamIdentity *IamIdentityV1) DeleteAccountSettingsTemplateVersionWithContex return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_account_settings_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_profile_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// CommitAccountSettingsTemplate : Commit a template version -// Commit a specific version of an account settings template in an Enterprise Account. A Template must be committed -// before being assigned, and once committed, can no longer be modified. -func (iamIdentity *IamIdentityV1) CommitAccountSettingsTemplate(commitAccountSettingsTemplateOptions *CommitAccountSettingsTemplateOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.CommitAccountSettingsTemplateWithContext(context.Background(), commitAccountSettingsTemplateOptions) +// UpdateProfileTemplateVersion : Update version of trusted profile template +// Update a specific version of a trusted profile template in an enterprise account. +func (iamIdentity *IamIdentityV1) UpdateProfileTemplateVersion(updateProfileTemplateVersionOptions *UpdateProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdateProfileTemplateVersionWithContext(context.Background(), updateProfileTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// CommitAccountSettingsTemplateWithContext is an alternate form of the CommitAccountSettingsTemplate method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CommitAccountSettingsTemplateWithContext(ctx context.Context, commitAccountSettingsTemplateOptions *CommitAccountSettingsTemplateOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(commitAccountSettingsTemplateOptions, "commitAccountSettingsTemplateOptions cannot be nil") +// UpdateProfileTemplateVersionWithContext is an alternate form of the UpdateProfileTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdateProfileTemplateVersionWithContext(ctx context.Context, updateProfileTemplateVersionOptions *UpdateProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateProfileTemplateVersionOptions, "updateProfileTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(commitAccountSettingsTemplateOptions, "commitAccountSettingsTemplateOptions") + err = core.ValidateStruct(updateProfileTemplateVersionOptions, "updateProfileTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *commitAccountSettingsTemplateOptions.TemplateID, - "version": *commitAccountSettingsTemplateOptions.Version, + "template_id": *updateProfileTemplateVersionOptions.TemplateID, + "version": *updateProfileTemplateVersionOptions.Version, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions/{version}/commit`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions/{version}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range commitAccountSettingsTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateProfileTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CommitAccountSettingsTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateProfileTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + if updateProfileTemplateVersionOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateProfileTemplateVersionOptions.IfMatch)) + } + + body := make(map[string]interface{}) + if updateProfileTemplateVersionOptions.AccountID != nil { + body["account_id"] = updateProfileTemplateVersionOptions.AccountID + } + if updateProfileTemplateVersionOptions.Name != nil { + body["name"] = updateProfileTemplateVersionOptions.Name + } + if updateProfileTemplateVersionOptions.Description != nil { + body["description"] = updateProfileTemplateVersionOptions.Description + } + if updateProfileTemplateVersionOptions.Profile != nil { + body["profile"] = updateProfileTemplateVersionOptions.Profile + } + if updateProfileTemplateVersionOptions.PolicyTemplateReferences != nil { + body["policy_template_references"] = updateProfileTemplateVersionOptions.PolicyTemplateReferences + } + if updateProfileTemplateVersionOptions.ActionControls != nil { + body["action_controls"] = updateProfileTemplateVersionOptions.ActionControls + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } request, err := builder.Build() if err != nil { @@ -4445,66 +4982,68 @@ func (iamIdentity *IamIdentityV1) CommitAccountSettingsTemplateWithContext(ctx c return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "commit_account_settings_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_profile_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// CreateReport : Trigger activity report for the account -// Trigger activity report for the account by specifying the account ID. It can take a few minutes to generate the -// report for retrieval. -func (iamIdentity *IamIdentityV1) CreateReport(createReportOptions *CreateReportOptions) (result *ReportReference, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateReportWithContext(context.Background(), createReportOptions) +// DeleteProfileTemplateVersion : Delete version of trusted profile template +// Delete a specific version of a trusted profile template in an enterprise account. If the version is assigned to child +// accounts, you must first delete the assignment. +func (iamIdentity *IamIdentityV1) DeleteProfileTemplateVersion(deleteProfileTemplateVersionOptions *DeleteProfileTemplateVersionOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeleteProfileTemplateVersionWithContext(context.Background(), deleteProfileTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateReportWithContext is an alternate form of the CreateReport method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateReportWithContext(ctx context.Context, createReportOptions *CreateReportOptions) (result *ReportReference, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createReportOptions, "createReportOptions cannot be nil") +// DeleteProfileTemplateVersionWithContext is an alternate form of the DeleteProfileTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteProfileTemplateVersionWithContext(ctx context.Context, deleteProfileTemplateVersionOptions *DeleteProfileTemplateVersionOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteProfileTemplateVersionOptions, "deleteProfileTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createReportOptions, "createReportOptions") + err = core.ValidateStruct(deleteProfileTemplateVersionOptions, "deleteProfileTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *createReportOptions.AccountID, + "template_id": *deleteProfileTemplateVersionOptions.TemplateID, + "version": *deleteProfileTemplateVersionOptions.Version, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/activity/accounts/{account_id}/report`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions/{version}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createReportOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateReport") + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteProfileTemplateVersion") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - if createReportOptions.Type != nil { - builder.AddQuery("type", fmt.Sprint(*createReportOptions.Type)) - } - if createReportOptions.Duration != nil { - builder.AddQuery("duration", fmt.Sprint(*createReportOptions.Duration)) + for headerName, headerValue := range deleteProfileTemplateVersionOptions.Headers { + builder.AddHeader(headerName, headerValue) } request, err := builder.Build() @@ -4513,70 +5052,60 @@ func (iamIdentity *IamIdentityV1) CreateReportWithContext(ctx context.Context, c return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "create_report", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_profile_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReportReference) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetReport : Get activity report for the account -// Get activity report for the account by specifying the account ID and the reference that is generated by triggering -// the report. Reports older than a day are deleted when generating a new report. -func (iamIdentity *IamIdentityV1) GetReport(getReportOptions *GetReportOptions) (result *Report, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetReportWithContext(context.Background(), getReportOptions) +// CommitProfileTemplate : Commit a template version +// Commit a specific version of a trusted profile template in an enterprise account. You must commit a template before +// you can assign it to child accounts. Once a template is committed, you can no longer modify the template. +func (iamIdentity *IamIdentityV1) CommitProfileTemplate(commitProfileTemplateOptions *CommitProfileTemplateOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.CommitProfileTemplateWithContext(context.Background(), commitProfileTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetReportWithContext is an alternate form of the GetReport method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetReportWithContext(ctx context.Context, getReportOptions *GetReportOptions) (result *Report, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getReportOptions, "getReportOptions cannot be nil") +// CommitProfileTemplateWithContext is an alternate form of the CommitProfileTemplate method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CommitProfileTemplateWithContext(ctx context.Context, commitProfileTemplateOptions *CommitProfileTemplateOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(commitProfileTemplateOptions, "commitProfileTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getReportOptions, "getReportOptions") + err = core.ValidateStruct(commitProfileTemplateOptions, "commitProfileTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *getReportOptions.AccountID, - "reference": *getReportOptions.Reference, + "template_id": *commitProfileTemplateOptions.TemplateID, + "version": *commitProfileTemplateOptions.Version, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/activity/accounts/{account_id}/report/{reference}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions/{version}/commit`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getReportOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CommitProfileTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetReport") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range commitProfileTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { @@ -4584,74 +5113,80 @@ func (iamIdentity *IamIdentityV1) GetReportWithContext(ctx context.Context, getR return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_report", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "commit_profile_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReport) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetEffectiveAccountSettings : Get effective account settings configuration -// Returns effective account settings for given account ID. -func (iamIdentity *IamIdentityV1) GetEffectiveAccountSettings(getEffectiveAccountSettingsOptions *GetEffectiveAccountSettingsOptions) (result *EffectiveAccountSettingsResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetEffectiveAccountSettingsWithContext(context.Background(), getEffectiveAccountSettingsOptions) +// ListTrustedProfileAssignments : List assignments +// List trusted profile template assignments. +func (iamIdentity *IamIdentityV1) ListTrustedProfileAssignments(listTrustedProfileAssignmentsOptions *ListTrustedProfileAssignmentsOptions) (result *TemplateAssignmentListResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListTrustedProfileAssignmentsWithContext(context.Background(), listTrustedProfileAssignmentsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetEffectiveAccountSettingsWithContext is an alternate form of the GetEffectiveAccountSettings method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetEffectiveAccountSettingsWithContext(ctx context.Context, getEffectiveAccountSettingsOptions *GetEffectiveAccountSettingsOptions) (result *EffectiveAccountSettingsResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getEffectiveAccountSettingsOptions, "getEffectiveAccountSettingsOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getEffectiveAccountSettingsOptions, "getEffectiveAccountSettingsOptions") +// ListTrustedProfileAssignmentsWithContext is an alternate form of the ListTrustedProfileAssignments method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListTrustedProfileAssignmentsWithContext(ctx context.Context, listTrustedProfileAssignmentsOptions *ListTrustedProfileAssignmentsOptions) (result *TemplateAssignmentListResponse, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listTrustedProfileAssignmentsOptions, "listTrustedProfileAssignmentsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "account_id": *getEffectiveAccountSettingsOptions.AccountID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/accounts/{account_id}/effective_settings/identity`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getEffectiveAccountSettingsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListTrustedProfileAssignments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetEffectiveAccountSettings") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listTrustedProfileAssignmentsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if getEffectiveAccountSettingsOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getEffectiveAccountSettingsOptions.IncludeHistory)) + if listTrustedProfileAssignmentsOptions.AccountID != nil { + builder.AddQuery("account_id", fmt.Sprint(*listTrustedProfileAssignmentsOptions.AccountID)) } - if getEffectiveAccountSettingsOptions.ResolveUserMfa != nil { - builder.AddQuery("resolve_user_mfa", fmt.Sprint(*getEffectiveAccountSettingsOptions.ResolveUserMfa)) + if listTrustedProfileAssignmentsOptions.TemplateID != nil { + builder.AddQuery("template_id", fmt.Sprint(*listTrustedProfileAssignmentsOptions.TemplateID)) + } + if listTrustedProfileAssignmentsOptions.TemplateVersion != nil { + builder.AddQuery("template_version", fmt.Sprint(*listTrustedProfileAssignmentsOptions.TemplateVersion)) + } + if listTrustedProfileAssignmentsOptions.Target != nil { + builder.AddQuery("target", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Target)) + } + if listTrustedProfileAssignmentsOptions.TargetType != nil { + builder.AddQuery("target_type", fmt.Sprint(*listTrustedProfileAssignmentsOptions.TargetType)) + } + if listTrustedProfileAssignmentsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Limit)) + } + if listTrustedProfileAssignmentsOptions.Pagetoken != nil { + builder.AddQuery("pagetoken", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Pagetoken)) + } + if listTrustedProfileAssignmentsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Sort)) + } + if listTrustedProfileAssignmentsOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Order)) + } + if listTrustedProfileAssignmentsOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*listTrustedProfileAssignmentsOptions.IncludeHistory)) } request, err := builder.Build() @@ -4663,12 +5198,12 @@ func (iamIdentity *IamIdentityV1) GetEffectiveAccountSettingsWithContext(ctx con var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_effective_account_settings", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_trusted_profile_assignments", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEffectiveAccountSettingsResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentListResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4679,78 +5214,59 @@ func (iamIdentity *IamIdentityV1) GetEffectiveAccountSettingsWithContext(ctx con return } -// UpdatePreferenceOnScopeAccount : Update Identity Preference on scope account -// Update one Identity Preference on scope 'account'. supported preferences: -// -// The following preferences are storing values for identities inside an account, -// i.e. for each account that an identity is member of, the value stored might be different. -// This means, users who might be member of multiple accounts can have multiple preferences, one per account. -// Identities like Service Ids or Trusted Profiles can only exist in one account, -// therefore they can only have one preference inside their related account. -// preference: console/landing_page -// service: console -// preferenceId: landing_page -// supportedIdentityType: Trusted Profiles, Users -// type: string -// validation: valid URL (without host part), e.g. /billing or /iam -// preference: console/global_left_navigation -// service: console -// preferenceId: global_left_navigation -// supportedIdentityType: Trusted Profiles, Users -// type: list of strings -// validation: each entry in the list of strings must match the identifier of one navigation entry in the console. -func (iamIdentity *IamIdentityV1) UpdatePreferenceOnScopeAccount(updatePreferenceOnScopeAccountOptions *UpdatePreferenceOnScopeAccountOptions) (result *IdentityPreferenceResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.UpdatePreferenceOnScopeAccountWithContext(context.Background(), updatePreferenceOnScopeAccountOptions) +// CreateTrustedProfileAssignment : Create assignment +// Create an assigment for a trusted profile template. +func (iamIdentity *IamIdentityV1) CreateTrustedProfileAssignment(createTrustedProfileAssignmentOptions *CreateTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateTrustedProfileAssignmentWithContext(context.Background(), createTrustedProfileAssignmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdatePreferenceOnScopeAccountWithContext is an alternate form of the UpdatePreferenceOnScopeAccount method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UpdatePreferenceOnScopeAccountWithContext(ctx context.Context, updatePreferenceOnScopeAccountOptions *UpdatePreferenceOnScopeAccountOptions) (result *IdentityPreferenceResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updatePreferenceOnScopeAccountOptions, "updatePreferenceOnScopeAccountOptions cannot be nil") +// CreateTrustedProfileAssignmentWithContext is an alternate form of the CreateTrustedProfileAssignment method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateTrustedProfileAssignmentWithContext(ctx context.Context, createTrustedProfileAssignmentOptions *CreateTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createTrustedProfileAssignmentOptions, "createTrustedProfileAssignmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updatePreferenceOnScopeAccountOptions, "updatePreferenceOnScopeAccountOptions") + err = core.ValidateStruct(createTrustedProfileAssignmentOptions, "createTrustedProfileAssignmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "account_id": *updatePreferenceOnScopeAccountOptions.AccountID, - "iam_id": *updatePreferenceOnScopeAccountOptions.IamID, - "service": *updatePreferenceOnScopeAccountOptions.Service, - "preference_id": *updatePreferenceOnScopeAccountOptions.PreferenceID, - } - - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/preferences/accounts/{account_id}/identities/{iam_id}/{service}/{preference_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updatePreferenceOnScopeAccountOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateTrustedProfileAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdatePreferenceOnScopeAccount") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createTrustedProfileAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) - if updatePreferenceOnScopeAccountOptions.ValueString != nil { - body["value_string"] = updatePreferenceOnScopeAccountOptions.ValueString + if createTrustedProfileAssignmentOptions.TemplateID != nil { + body["template_id"] = createTrustedProfileAssignmentOptions.TemplateID } - if updatePreferenceOnScopeAccountOptions.ValueListOfStrings != nil { - body["value_list_of_strings"] = updatePreferenceOnScopeAccountOptions.ValueListOfStrings + if createTrustedProfileAssignmentOptions.TemplateVersion != nil { + body["template_version"] = createTrustedProfileAssignmentOptions.TemplateVersion + } + if createTrustedProfileAssignmentOptions.TargetType != nil { + body["target_type"] = createTrustedProfileAssignmentOptions.TargetType + } + if createTrustedProfileAssignmentOptions.Target != nil { + body["target"] = createTrustedProfileAssignmentOptions.Target } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -4767,12 +5283,12 @@ func (iamIdentity *IamIdentityV1) UpdatePreferenceOnScopeAccountWithContext(ctx var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_preference_on_scope_account", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_trusted_profile_assignment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIdentityPreferenceResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4783,51 +5299,53 @@ func (iamIdentity *IamIdentityV1) UpdatePreferenceOnScopeAccountWithContext(ctx return } -// DeletePreferencesOnScopeAccount : Delete Identity Preference on scope account -// Delete one Identity Preference on scope 'account'. -func (iamIdentity *IamIdentityV1) DeletePreferencesOnScopeAccount(deletePreferencesOnScopeAccountOptions *DeletePreferencesOnScopeAccountOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.DeletePreferencesOnScopeAccountWithContext(context.Background(), deletePreferencesOnScopeAccountOptions) +// GetTrustedProfileAssignment : Get assignment +// Get an assigment for a trusted profile template. +func (iamIdentity *IamIdentityV1) GetTrustedProfileAssignment(getTrustedProfileAssignmentOptions *GetTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetTrustedProfileAssignmentWithContext(context.Background(), getTrustedProfileAssignmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeletePreferencesOnScopeAccountWithContext is an alternate form of the DeletePreferencesOnScopeAccount method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeletePreferencesOnScopeAccountWithContext(ctx context.Context, deletePreferencesOnScopeAccountOptions *DeletePreferencesOnScopeAccountOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deletePreferencesOnScopeAccountOptions, "deletePreferencesOnScopeAccountOptions cannot be nil") +// GetTrustedProfileAssignmentWithContext is an alternate form of the GetTrustedProfileAssignment method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetTrustedProfileAssignmentWithContext(ctx context.Context, getTrustedProfileAssignmentOptions *GetTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getTrustedProfileAssignmentOptions, "getTrustedProfileAssignmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deletePreferencesOnScopeAccountOptions, "deletePreferencesOnScopeAccountOptions") + err = core.ValidateStruct(getTrustedProfileAssignmentOptions, "getTrustedProfileAssignmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *deletePreferencesOnScopeAccountOptions.AccountID, - "iam_id": *deletePreferencesOnScopeAccountOptions.IamID, - "service": *deletePreferencesOnScopeAccountOptions.Service, - "preference_id": *deletePreferencesOnScopeAccountOptions.PreferenceID, + "assignment_id": *getTrustedProfileAssignmentOptions.AssignmentID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/preferences/accounts/{account_id}/identities/{iam_id}/{service}/{preference_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/{assignment_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deletePreferencesOnScopeAccountOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetTrustedProfileAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeletePreferencesOnScopeAccount") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getTrustedProfileAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + + if getTrustedProfileAssignmentOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getTrustedProfileAssignmentOptions.IncludeHistory)) + } request, err := builder.Build() if err != nil { @@ -4835,59 +5353,65 @@ func (iamIdentity *IamIdentityV1) DeletePreferencesOnScopeAccountWithContext(ctx return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_preferences_on_scope_account", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_trusted_profile_assignment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetPreferencesOnScopeAccount : Get Identity Preference on scope account -// Get one Identity Preference on scope 'account'. -func (iamIdentity *IamIdentityV1) GetPreferencesOnScopeAccount(getPreferencesOnScopeAccountOptions *GetPreferencesOnScopeAccountOptions) (result *IdentityPreferenceResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetPreferencesOnScopeAccountWithContext(context.Background(), getPreferencesOnScopeAccountOptions) +// DeleteTrustedProfileAssignment : Delete assignment +// Delete a trusted profile assignment. This removes any IAM resources created by this assignment in child accounts. +func (iamIdentity *IamIdentityV1) DeleteTrustedProfileAssignment(deleteTrustedProfileAssignmentOptions *DeleteTrustedProfileAssignmentOptions) (result *ExceptionResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.DeleteTrustedProfileAssignmentWithContext(context.Background(), deleteTrustedProfileAssignmentOptions) err = core.RepurposeSDKProblem(err, "") return } - -// GetPreferencesOnScopeAccountWithContext is an alternate form of the GetPreferencesOnScopeAccount method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetPreferencesOnScopeAccountWithContext(ctx context.Context, getPreferencesOnScopeAccountOptions *GetPreferencesOnScopeAccountOptions) (result *IdentityPreferenceResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getPreferencesOnScopeAccountOptions, "getPreferencesOnScopeAccountOptions cannot be nil") + +// DeleteTrustedProfileAssignmentWithContext is an alternate form of the DeleteTrustedProfileAssignment method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteTrustedProfileAssignmentWithContext(ctx context.Context, deleteTrustedProfileAssignmentOptions *DeleteTrustedProfileAssignmentOptions) (result *ExceptionResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteTrustedProfileAssignmentOptions, "deleteTrustedProfileAssignmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getPreferencesOnScopeAccountOptions, "getPreferencesOnScopeAccountOptions") + err = core.ValidateStruct(deleteTrustedProfileAssignmentOptions, "deleteTrustedProfileAssignmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *getPreferencesOnScopeAccountOptions.AccountID, - "iam_id": *getPreferencesOnScopeAccountOptions.IamID, - "service": *getPreferencesOnScopeAccountOptions.Service, - "preference_id": *getPreferencesOnScopeAccountOptions.PreferenceID, + "assignment_id": *deleteTrustedProfileAssignmentOptions.AssignmentID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/preferences/accounts/{account_id}/identities/{iam_id}/{service}/{preference_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/{assignment_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getPreferencesOnScopeAccountOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteTrustedProfileAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetPreferencesOnScopeAccount") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteTrustedProfileAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -4901,12 +5425,12 @@ func (iamIdentity *IamIdentityV1) GetPreferencesOnScopeAccountWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_preferences_on_scope_account", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_trusted_profile_assignment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIdentityPreferenceResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalExceptionResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4917,50 +5441,64 @@ func (iamIdentity *IamIdentityV1) GetPreferencesOnScopeAccountWithContext(ctx co return } -// GetAllPreferencesOnScopeAccount : Get all Identity Preferences for one account -// Get all Identity Preferences for one account / user combination. -func (iamIdentity *IamIdentityV1) GetAllPreferencesOnScopeAccount(getAllPreferencesOnScopeAccountOptions *GetAllPreferencesOnScopeAccountOptions) (result *IdentityPreferencesResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetAllPreferencesOnScopeAccountWithContext(context.Background(), getAllPreferencesOnScopeAccountOptions) +// UpdateTrustedProfileAssignment : Update assignment +// Update a trusted profile assignment. Call this method to retry failed assignments or migrate the trusted profile in +// child accounts to a new version. +func (iamIdentity *IamIdentityV1) UpdateTrustedProfileAssignment(updateTrustedProfileAssignmentOptions *UpdateTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdateTrustedProfileAssignmentWithContext(context.Background(), updateTrustedProfileAssignmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetAllPreferencesOnScopeAccountWithContext is an alternate form of the GetAllPreferencesOnScopeAccount method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetAllPreferencesOnScopeAccountWithContext(ctx context.Context, getAllPreferencesOnScopeAccountOptions *GetAllPreferencesOnScopeAccountOptions) (result *IdentityPreferencesResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getAllPreferencesOnScopeAccountOptions, "getAllPreferencesOnScopeAccountOptions cannot be nil") +// UpdateTrustedProfileAssignmentWithContext is an alternate form of the UpdateTrustedProfileAssignment method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdateTrustedProfileAssignmentWithContext(ctx context.Context, updateTrustedProfileAssignmentOptions *UpdateTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateTrustedProfileAssignmentOptions, "updateTrustedProfileAssignmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getAllPreferencesOnScopeAccountOptions, "getAllPreferencesOnScopeAccountOptions") + err = core.ValidateStruct(updateTrustedProfileAssignmentOptions, "updateTrustedProfileAssignmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "account_id": *getAllPreferencesOnScopeAccountOptions.AccountID, - "iam_id": *getAllPreferencesOnScopeAccountOptions.IamID, + "assignment_id": *updateTrustedProfileAssignmentOptions.AssignmentID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/preferences/accounts/{account_id}/identities/{iam_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/{assignment_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getAllPreferencesOnScopeAccountOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateTrustedProfileAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAllPreferencesOnScopeAccount") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateTrustedProfileAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + if updateTrustedProfileAssignmentOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateTrustedProfileAssignmentOptions.IfMatch)) + } + + body := make(map[string]interface{}) + if updateTrustedProfileAssignmentOptions.TemplateVersion != nil { + body["template_version"] = updateTrustedProfileAssignmentOptions.TemplateVersion + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } request, err := builder.Build() if err != nil { @@ -4971,12 +5509,12 @@ func (iamIdentity *IamIdentityV1) GetAllPreferencesOnScopeAccountWithContext(ctx var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_all_preferences_on_scope_account", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_trusted_profile_assignment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIdentityPreferencesResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4987,17 +5525,17 @@ func (iamIdentity *IamIdentityV1) GetAllPreferencesOnScopeAccountWithContext(ctx return } -// ListTrustedProfileAssignments : List assignments -// List trusted profile template assignments. -func (iamIdentity *IamIdentityV1) ListTrustedProfileAssignments(listTrustedProfileAssignmentsOptions *ListTrustedProfileAssignmentsOptions) (result *TemplateAssignmentListResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.ListTrustedProfileAssignmentsWithContext(context.Background(), listTrustedProfileAssignmentsOptions) +// ListAccountSettingsTemplates : List account settings templates +// List account settings templates in an enterprise account. +func (iamIdentity *IamIdentityV1) ListAccountSettingsTemplates(listAccountSettingsTemplatesOptions *ListAccountSettingsTemplatesOptions) (result *AccountSettingsTemplateList, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListAccountSettingsTemplatesWithContext(context.Background(), listAccountSettingsTemplatesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListTrustedProfileAssignmentsWithContext is an alternate form of the ListTrustedProfileAssignments method which supports a Context parameter -func (iamIdentity *IamIdentityV1) ListTrustedProfileAssignmentsWithContext(ctx context.Context, listTrustedProfileAssignmentsOptions *ListTrustedProfileAssignmentsOptions) (result *TemplateAssignmentListResponse, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listTrustedProfileAssignmentsOptions, "listTrustedProfileAssignmentsOptions") +// ListAccountSettingsTemplatesWithContext is an alternate form of the ListAccountSettingsTemplates method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListAccountSettingsTemplatesWithContext(ctx context.Context, listAccountSettingsTemplatesOptions *ListAccountSettingsTemplatesOptions) (result *AccountSettingsTemplateList, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listAccountSettingsTemplatesOptions, "listAccountSettingsTemplatesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -5006,51 +5544,39 @@ func (iamIdentity *IamIdentityV1) ListTrustedProfileAssignmentsWithContext(ctx c builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listTrustedProfileAssignmentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListAccountSettingsTemplates") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListTrustedProfileAssignments") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listAccountSettingsTemplatesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if listTrustedProfileAssignmentsOptions.AccountID != nil { - builder.AddQuery("account_id", fmt.Sprint(*listTrustedProfileAssignmentsOptions.AccountID)) - } - if listTrustedProfileAssignmentsOptions.TemplateID != nil { - builder.AddQuery("template_id", fmt.Sprint(*listTrustedProfileAssignmentsOptions.TemplateID)) - } - if listTrustedProfileAssignmentsOptions.TemplateVersion != nil { - builder.AddQuery("template_version", fmt.Sprint(*listTrustedProfileAssignmentsOptions.TemplateVersion)) - } - if listTrustedProfileAssignmentsOptions.Target != nil { - builder.AddQuery("target", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Target)) - } - if listTrustedProfileAssignmentsOptions.TargetType != nil { - builder.AddQuery("target_type", fmt.Sprint(*listTrustedProfileAssignmentsOptions.TargetType)) + if listAccountSettingsTemplatesOptions.AccountID != nil { + builder.AddQuery("account_id", fmt.Sprint(*listAccountSettingsTemplatesOptions.AccountID)) } - if listTrustedProfileAssignmentsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Limit)) + if listAccountSettingsTemplatesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listAccountSettingsTemplatesOptions.Limit)) } - if listTrustedProfileAssignmentsOptions.Pagetoken != nil { - builder.AddQuery("pagetoken", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Pagetoken)) + if listAccountSettingsTemplatesOptions.Pagetoken != nil { + builder.AddQuery("pagetoken", fmt.Sprint(*listAccountSettingsTemplatesOptions.Pagetoken)) } - if listTrustedProfileAssignmentsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Sort)) + if listAccountSettingsTemplatesOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listAccountSettingsTemplatesOptions.Sort)) } - if listTrustedProfileAssignmentsOptions.Order != nil { - builder.AddQuery("order", fmt.Sprint(*listTrustedProfileAssignmentsOptions.Order)) + if listAccountSettingsTemplatesOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listAccountSettingsTemplatesOptions.Order)) } - if listTrustedProfileAssignmentsOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*listTrustedProfileAssignmentsOptions.IncludeHistory)) + if listAccountSettingsTemplatesOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*listAccountSettingsTemplatesOptions.IncludeHistory)) } request, err := builder.Build() @@ -5062,12 +5588,12 @@ func (iamIdentity *IamIdentityV1) ListTrustedProfileAssignmentsWithContext(ctx c var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_trusted_profile_assignments", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_account_settings_templates", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentListResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateList) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5078,22 +5604,22 @@ func (iamIdentity *IamIdentityV1) ListTrustedProfileAssignmentsWithContext(ctx c return } -// CreateTrustedProfileAssignment : Create assignment -// Create an assigment for a trusted profile template. -func (iamIdentity *IamIdentityV1) CreateTrustedProfileAssignment(createTrustedProfileAssignmentOptions *CreateTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateTrustedProfileAssignmentWithContext(context.Background(), createTrustedProfileAssignmentOptions) +// CreateAccountSettingsTemplate : Create an account settings template +// Create a new account settings template in an enterprise account. +func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplate(createAccountSettingsTemplateOptions *CreateAccountSettingsTemplateOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateAccountSettingsTemplateWithContext(context.Background(), createAccountSettingsTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateTrustedProfileAssignmentWithContext is an alternate form of the CreateTrustedProfileAssignment method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateTrustedProfileAssignmentWithContext(ctx context.Context, createTrustedProfileAssignmentOptions *CreateTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createTrustedProfileAssignmentOptions, "createTrustedProfileAssignmentOptions cannot be nil") +// CreateAccountSettingsTemplateWithContext is an alternate form of the CreateAccountSettingsTemplate method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplateWithContext(ctx context.Context, createAccountSettingsTemplateOptions *CreateAccountSettingsTemplateOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createAccountSettingsTemplateOptions, "createAccountSettingsTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createTrustedProfileAssignmentOptions, "createTrustedProfileAssignmentOptions") + err = core.ValidateStruct(createAccountSettingsTemplateOptions, "createAccountSettingsTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -5102,35 +5628,35 @@ func (iamIdentity *IamIdentityV1) CreateTrustedProfileAssignmentWithContext(ctx builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createTrustedProfileAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateAccountSettingsTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateTrustedProfileAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createAccountSettingsTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) - if createTrustedProfileAssignmentOptions.TemplateID != nil { - body["template_id"] = createTrustedProfileAssignmentOptions.TemplateID + if createAccountSettingsTemplateOptions.AccountID != nil { + body["account_id"] = createAccountSettingsTemplateOptions.AccountID } - if createTrustedProfileAssignmentOptions.TemplateVersion != nil { - body["template_version"] = createTrustedProfileAssignmentOptions.TemplateVersion + if createAccountSettingsTemplateOptions.Name != nil { + body["name"] = createAccountSettingsTemplateOptions.Name } - if createTrustedProfileAssignmentOptions.TargetType != nil { - body["target_type"] = createTrustedProfileAssignmentOptions.TargetType + if createAccountSettingsTemplateOptions.Description != nil { + body["description"] = createAccountSettingsTemplateOptions.Description } - if createTrustedProfileAssignmentOptions.Target != nil { - body["target"] = createTrustedProfileAssignmentOptions.Target + if createAccountSettingsTemplateOptions.AccountSettings != nil { + body["account_settings"] = createAccountSettingsTemplateOptions.AccountSettings } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -5147,12 +5673,12 @@ func (iamIdentity *IamIdentityV1) CreateTrustedProfileAssignmentWithContext(ctx var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_trusted_profile_assignment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_account_settings_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5163,52 +5689,52 @@ func (iamIdentity *IamIdentityV1) CreateTrustedProfileAssignmentWithContext(ctx return } -// GetTrustedProfileAssignment : Get assignment -// Get an assigment for a trusted profile template. -func (iamIdentity *IamIdentityV1) GetTrustedProfileAssignment(getTrustedProfileAssignmentOptions *GetTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetTrustedProfileAssignmentWithContext(context.Background(), getTrustedProfileAssignmentOptions) +// GetLatestAccountSettingsTemplateVersion : Get latest version of an account settings template +// Get the latest version of a specific account settings template in an enterprise account. +func (iamIdentity *IamIdentityV1) GetLatestAccountSettingsTemplateVersion(getLatestAccountSettingsTemplateVersionOptions *GetLatestAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetLatestAccountSettingsTemplateVersionWithContext(context.Background(), getLatestAccountSettingsTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetTrustedProfileAssignmentWithContext is an alternate form of the GetTrustedProfileAssignment method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetTrustedProfileAssignmentWithContext(ctx context.Context, getTrustedProfileAssignmentOptions *GetTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getTrustedProfileAssignmentOptions, "getTrustedProfileAssignmentOptions cannot be nil") +// GetLatestAccountSettingsTemplateVersionWithContext is an alternate form of the GetLatestAccountSettingsTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetLatestAccountSettingsTemplateVersionWithContext(ctx context.Context, getLatestAccountSettingsTemplateVersionOptions *GetLatestAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLatestAccountSettingsTemplateVersionOptions, "getLatestAccountSettingsTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getTrustedProfileAssignmentOptions, "getTrustedProfileAssignmentOptions") + err = core.ValidateStruct(getLatestAccountSettingsTemplateVersionOptions, "getLatestAccountSettingsTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "assignment_id": *getTrustedProfileAssignmentOptions.AssignmentID, + "template_id": *getLatestAccountSettingsTemplateVersionOptions.TemplateID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/{assignment_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getTrustedProfileAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetLatestAccountSettingsTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetTrustedProfileAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLatestAccountSettingsTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if getTrustedProfileAssignmentOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getTrustedProfileAssignmentOptions.IncludeHistory)) + if getLatestAccountSettingsTemplateVersionOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getLatestAccountSettingsTemplateVersionOptions.IncludeHistory)) } request, err := builder.Build() @@ -5220,12 +5746,12 @@ func (iamIdentity *IamIdentityV1) GetTrustedProfileAssignmentWithContext(ctx con var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_trusted_profile_assignment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_latest_account_settings_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5236,49 +5762,49 @@ func (iamIdentity *IamIdentityV1) GetTrustedProfileAssignmentWithContext(ctx con return } -// DeleteTrustedProfileAssignment : Delete assignment -// Delete a trusted profile assignment. This removes any IAM resources created by this assignment in child accounts. -func (iamIdentity *IamIdentityV1) DeleteTrustedProfileAssignment(deleteTrustedProfileAssignmentOptions *DeleteTrustedProfileAssignmentOptions) (result *ExceptionResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.DeleteTrustedProfileAssignmentWithContext(context.Background(), deleteTrustedProfileAssignmentOptions) +// DeleteAllVersionsOfAccountSettingsTemplate : Delete all versions of an account settings template +// Delete all versions of an account settings template in an enterprise account. If any version is assigned to child +// accounts, you must first delete the assignment. +func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfAccountSettingsTemplate(deleteAllVersionsOfAccountSettingsTemplateOptions *DeleteAllVersionsOfAccountSettingsTemplateOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeleteAllVersionsOfAccountSettingsTemplateWithContext(context.Background(), deleteAllVersionsOfAccountSettingsTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteTrustedProfileAssignmentWithContext is an alternate form of the DeleteTrustedProfileAssignment method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeleteTrustedProfileAssignmentWithContext(ctx context.Context, deleteTrustedProfileAssignmentOptions *DeleteTrustedProfileAssignmentOptions) (result *ExceptionResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteTrustedProfileAssignmentOptions, "deleteTrustedProfileAssignmentOptions cannot be nil") +// DeleteAllVersionsOfAccountSettingsTemplateWithContext is an alternate form of the DeleteAllVersionsOfAccountSettingsTemplate method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfAccountSettingsTemplateWithContext(ctx context.Context, deleteAllVersionsOfAccountSettingsTemplateOptions *DeleteAllVersionsOfAccountSettingsTemplateOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteAllVersionsOfAccountSettingsTemplateOptions, "deleteAllVersionsOfAccountSettingsTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteTrustedProfileAssignmentOptions, "deleteTrustedProfileAssignmentOptions") + err = core.ValidateStruct(deleteAllVersionsOfAccountSettingsTemplateOptions, "deleteAllVersionsOfAccountSettingsTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "assignment_id": *deleteTrustedProfileAssignmentOptions.AssignmentID, + "template_id": *deleteAllVersionsOfAccountSettingsTemplateOptions.TemplateID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/{assignment_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteTrustedProfileAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAllVersionsOfAccountSettingsTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteTrustedProfileAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteAllVersionsOfAccountSettingsTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { @@ -5286,82 +5812,74 @@ func (iamIdentity *IamIdentityV1) DeleteTrustedProfileAssignmentWithContext(ctx return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_trusted_profile_assignment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_all_versions_of_account_settings_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalExceptionResponse) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } - return -} - -// UpdateTrustedProfileAssignment : Update assignment -// Update a trusted profile assignment. Call this method to retry failed assignments or migrate the trusted profile in -// child accounts to a new version. -func (iamIdentity *IamIdentityV1) UpdateTrustedProfileAssignment(updateTrustedProfileAssignmentOptions *UpdateTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.UpdateTrustedProfileAssignmentWithContext(context.Background(), updateTrustedProfileAssignmentOptions) + return +} + +// ListVersionsOfAccountSettingsTemplate : List account settings template versions +// List the versions of a specific account settings template in an enterprise account. +func (iamIdentity *IamIdentityV1) ListVersionsOfAccountSettingsTemplate(listVersionsOfAccountSettingsTemplateOptions *ListVersionsOfAccountSettingsTemplateOptions) (result *AccountSettingsTemplateList, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListVersionsOfAccountSettingsTemplateWithContext(context.Background(), listVersionsOfAccountSettingsTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateTrustedProfileAssignmentWithContext is an alternate form of the UpdateTrustedProfileAssignment method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UpdateTrustedProfileAssignmentWithContext(ctx context.Context, updateTrustedProfileAssignmentOptions *UpdateTrustedProfileAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateTrustedProfileAssignmentOptions, "updateTrustedProfileAssignmentOptions cannot be nil") +// ListVersionsOfAccountSettingsTemplateWithContext is an alternate form of the ListVersionsOfAccountSettingsTemplate method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListVersionsOfAccountSettingsTemplateWithContext(ctx context.Context, listVersionsOfAccountSettingsTemplateOptions *ListVersionsOfAccountSettingsTemplateOptions) (result *AccountSettingsTemplateList, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVersionsOfAccountSettingsTemplateOptions, "listVersionsOfAccountSettingsTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateTrustedProfileAssignmentOptions, "updateTrustedProfileAssignmentOptions") + err = core.ValidateStruct(listVersionsOfAccountSettingsTemplateOptions, "listVersionsOfAccountSettingsTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "assignment_id": *updateTrustedProfileAssignmentOptions.AssignmentID, + "template_id": *listVersionsOfAccountSettingsTemplateOptions.TemplateID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_assignments/{assignment_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateTrustedProfileAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListVersionsOfAccountSettingsTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateTrustedProfileAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVersionsOfAccountSettingsTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - if updateTrustedProfileAssignmentOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateTrustedProfileAssignmentOptions.IfMatch)) - } - body := make(map[string]interface{}) - if updateTrustedProfileAssignmentOptions.TemplateVersion != nil { - body["template_version"] = updateTrustedProfileAssignmentOptions.TemplateVersion + if listVersionsOfAccountSettingsTemplateOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.Limit)) } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listVersionsOfAccountSettingsTemplateOptions.Pagetoken != nil { + builder.AddQuery("pagetoken", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.Pagetoken)) + } + if listVersionsOfAccountSettingsTemplateOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.Sort)) + } + if listVersionsOfAccountSettingsTemplateOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.Order)) + } + if listVersionsOfAccountSettingsTemplateOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*listVersionsOfAccountSettingsTemplateOptions.IncludeHistory)) } request, err := builder.Build() @@ -5373,12 +5891,12 @@ func (iamIdentity *IamIdentityV1) UpdateTrustedProfileAssignmentWithContext(ctx var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_trusted_profile_assignment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_versions_of_account_settings_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateList) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5389,58 +5907,68 @@ func (iamIdentity *IamIdentityV1) UpdateTrustedProfileAssignmentWithContext(ctx return } -// ListProfileTemplates : List trusted profile templates -// List the trusted profile templates in an enterprise account. -func (iamIdentity *IamIdentityV1) ListProfileTemplates(listProfileTemplatesOptions *ListProfileTemplatesOptions) (result *TrustedProfileTemplateList, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.ListProfileTemplatesWithContext(context.Background(), listProfileTemplatesOptions) +// CreateAccountSettingsTemplateVersion : Create a new version of an account settings template +// Create a new version of an account settings template in an Enterprise Account. +func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplateVersion(createAccountSettingsTemplateVersionOptions *CreateAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateAccountSettingsTemplateVersionWithContext(context.Background(), createAccountSettingsTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListProfileTemplatesWithContext is an alternate form of the ListProfileTemplates method which supports a Context parameter -func (iamIdentity *IamIdentityV1) ListProfileTemplatesWithContext(ctx context.Context, listProfileTemplatesOptions *ListProfileTemplatesOptions) (result *TrustedProfileTemplateList, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listProfileTemplatesOptions, "listProfileTemplatesOptions") +// CreateAccountSettingsTemplateVersionWithContext is an alternate form of the CreateAccountSettingsTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateAccountSettingsTemplateVersionWithContext(ctx context.Context, createAccountSettingsTemplateVersionOptions *CreateAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createAccountSettingsTemplateVersionOptions, "createAccountSettingsTemplateVersionOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(createAccountSettingsTemplateVersionOptions, "createAccountSettingsTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "template_id": *createAccountSettingsTemplateVersionOptions.TemplateID, + } + + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listProfileTemplatesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateAccountSettingsTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListProfileTemplates") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createAccountSettingsTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") - if listProfileTemplatesOptions.AccountID != nil { - builder.AddQuery("account_id", fmt.Sprint(*listProfileTemplatesOptions.AccountID)) - } - if listProfileTemplatesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listProfileTemplatesOptions.Limit)) + body := make(map[string]interface{}) + if createAccountSettingsTemplateVersionOptions.AccountID != nil { + body["account_id"] = createAccountSettingsTemplateVersionOptions.AccountID } - if listProfileTemplatesOptions.Pagetoken != nil { - builder.AddQuery("pagetoken", fmt.Sprint(*listProfileTemplatesOptions.Pagetoken)) + if createAccountSettingsTemplateVersionOptions.Name != nil { + body["name"] = createAccountSettingsTemplateVersionOptions.Name } - if listProfileTemplatesOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listProfileTemplatesOptions.Sort)) + if createAccountSettingsTemplateVersionOptions.Description != nil { + body["description"] = createAccountSettingsTemplateVersionOptions.Description } - if listProfileTemplatesOptions.Order != nil { - builder.AddQuery("order", fmt.Sprint(*listProfileTemplatesOptions.Order)) + if createAccountSettingsTemplateVersionOptions.AccountSettings != nil { + body["account_settings"] = createAccountSettingsTemplateVersionOptions.AccountSettings } - if listProfileTemplatesOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*listProfileTemplatesOptions.IncludeHistory)) + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -5452,12 +5980,12 @@ func (iamIdentity *IamIdentityV1) ListProfileTemplatesWithContext(ctx context.Co var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_profile_templates", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_account_settings_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateList) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5468,70 +5996,53 @@ func (iamIdentity *IamIdentityV1) ListProfileTemplatesWithContext(ctx context.Co return } -// CreateProfileTemplate : Create a trusted profile template -// Create a new trusted profile template in an enterprise account. -func (iamIdentity *IamIdentityV1) CreateProfileTemplate(createProfileTemplateOptions *CreateProfileTemplateOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateProfileTemplateWithContext(context.Background(), createProfileTemplateOptions) +// GetAccountSettingsTemplateVersion : Get version of an account settings template +// Get a specific version of an account settings template in an Enterprise Account. +func (iamIdentity *IamIdentityV1) GetAccountSettingsTemplateVersion(getAccountSettingsTemplateVersionOptions *GetAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetAccountSettingsTemplateVersionWithContext(context.Background(), getAccountSettingsTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateProfileTemplateWithContext is an alternate form of the CreateProfileTemplate method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateProfileTemplateWithContext(ctx context.Context, createProfileTemplateOptions *CreateProfileTemplateOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createProfileTemplateOptions, "createProfileTemplateOptions cannot be nil") +// GetAccountSettingsTemplateVersionWithContext is an alternate form of the GetAccountSettingsTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetAccountSettingsTemplateVersionWithContext(ctx context.Context, getAccountSettingsTemplateVersionOptions *GetAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getAccountSettingsTemplateVersionOptions, "getAccountSettingsTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createProfileTemplateOptions, "createProfileTemplateOptions") + err = core.ValidateStruct(getAccountSettingsTemplateVersionOptions, "getAccountSettingsTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "template_id": *getAccountSettingsTemplateVersionOptions.TemplateID, + "version": *getAccountSettingsTemplateVersionOptions.Version, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates`, nil) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions/{version}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createProfileTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAccountSettingsTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateProfileTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getAccountSettingsTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - body := make(map[string]interface{}) - if createProfileTemplateOptions.AccountID != nil { - body["account_id"] = createProfileTemplateOptions.AccountID - } - if createProfileTemplateOptions.Name != nil { - body["name"] = createProfileTemplateOptions.Name - } - if createProfileTemplateOptions.Description != nil { - body["description"] = createProfileTemplateOptions.Description - } - if createProfileTemplateOptions.Profile != nil { - body["profile"] = createProfileTemplateOptions.Profile - } - if createProfileTemplateOptions.PolicyTemplateReferences != nil { - body["policy_template_references"] = createProfileTemplateOptions.PolicyTemplateReferences - } - if createProfileTemplateOptions.ActionControls != nil { - body["action_controls"] = createProfileTemplateOptions.ActionControls - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if getAccountSettingsTemplateVersionOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getAccountSettingsTemplateVersionOptions.IncludeHistory)) } request, err := builder.Build() @@ -5543,12 +6054,12 @@ func (iamIdentity *IamIdentityV1) CreateProfileTemplateWithContext(ctx context.C var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_profile_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_account_settings_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5559,52 +6070,72 @@ func (iamIdentity *IamIdentityV1) CreateProfileTemplateWithContext(ctx context.C return } -// GetLatestProfileTemplateVersion : Get latest version of a trusted profile template -// Get the latest version of a trusted profile template in an enterprise account. -func (iamIdentity *IamIdentityV1) GetLatestProfileTemplateVersion(getLatestProfileTemplateVersionOptions *GetLatestProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetLatestProfileTemplateVersionWithContext(context.Background(), getLatestProfileTemplateVersionOptions) +// UpdateAccountSettingsTemplateVersion : Update version of an account settings template +// Update a specific version of an account settings template in an Enterprise Account. +func (iamIdentity *IamIdentityV1) UpdateAccountSettingsTemplateVersion(updateAccountSettingsTemplateVersionOptions *UpdateAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdateAccountSettingsTemplateVersionWithContext(context.Background(), updateAccountSettingsTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLatestProfileTemplateVersionWithContext is an alternate form of the GetLatestProfileTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetLatestProfileTemplateVersionWithContext(ctx context.Context, getLatestProfileTemplateVersionOptions *GetLatestProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLatestProfileTemplateVersionOptions, "getLatestProfileTemplateVersionOptions cannot be nil") +// UpdateAccountSettingsTemplateVersionWithContext is an alternate form of the UpdateAccountSettingsTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdateAccountSettingsTemplateVersionWithContext(ctx context.Context, updateAccountSettingsTemplateVersionOptions *UpdateAccountSettingsTemplateVersionOptions) (result *AccountSettingsTemplateResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateAccountSettingsTemplateVersionOptions, "updateAccountSettingsTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLatestProfileTemplateVersionOptions, "getLatestProfileTemplateVersionOptions") + err = core.ValidateStruct(updateAccountSettingsTemplateVersionOptions, "updateAccountSettingsTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *getLatestProfileTemplateVersionOptions.TemplateID, + "template_id": *updateAccountSettingsTemplateVersionOptions.TemplateID, + "version": *updateAccountSettingsTemplateVersionOptions.Version, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions/{version}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLatestProfileTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateAccountSettingsTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetLatestProfileTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateAccountSettingsTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + if updateAccountSettingsTemplateVersionOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateAccountSettingsTemplateVersionOptions.IfMatch)) + } - if getLatestProfileTemplateVersionOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getLatestProfileTemplateVersionOptions.IncludeHistory)) + body := make(map[string]interface{}) + if updateAccountSettingsTemplateVersionOptions.AccountID != nil { + body["account_id"] = updateAccountSettingsTemplateVersionOptions.AccountID + } + if updateAccountSettingsTemplateVersionOptions.Name != nil { + body["name"] = updateAccountSettingsTemplateVersionOptions.Name + } + if updateAccountSettingsTemplateVersionOptions.Description != nil { + body["description"] = updateAccountSettingsTemplateVersionOptions.Description + } + if updateAccountSettingsTemplateVersionOptions.AccountSettings != nil { + body["account_settings"] = updateAccountSettingsTemplateVersionOptions.AccountSettings + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -5616,12 +6147,12 @@ func (iamIdentity *IamIdentityV1) GetLatestProfileTemplateVersionWithContext(ctx var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_latest_profile_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_account_settings_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAccountSettingsTemplateResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5632,47 +6163,47 @@ func (iamIdentity *IamIdentityV1) GetLatestProfileTemplateVersionWithContext(ctx return } -// DeleteAllVersionsOfProfileTemplate : Delete all versions of a trusted profile template -// Delete all versions of a trusted profile template in an enterprise account. If any version is assigned to child -// accounts, you must first delete the assignment. -func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfProfileTemplate(deleteAllVersionsOfProfileTemplateOptions *DeleteAllVersionsOfProfileTemplateOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.DeleteAllVersionsOfProfileTemplateWithContext(context.Background(), deleteAllVersionsOfProfileTemplateOptions) +// DeleteAccountSettingsTemplateVersion : Delete version of an account settings template +// Delete a specific version of an account settings template in an Enterprise Account. +func (iamIdentity *IamIdentityV1) DeleteAccountSettingsTemplateVersion(deleteAccountSettingsTemplateVersionOptions *DeleteAccountSettingsTemplateVersionOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.DeleteAccountSettingsTemplateVersionWithContext(context.Background(), deleteAccountSettingsTemplateVersionOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteAllVersionsOfProfileTemplateWithContext is an alternate form of the DeleteAllVersionsOfProfileTemplate method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfProfileTemplateWithContext(ctx context.Context, deleteAllVersionsOfProfileTemplateOptions *DeleteAllVersionsOfProfileTemplateOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteAllVersionsOfProfileTemplateOptions, "deleteAllVersionsOfProfileTemplateOptions cannot be nil") +// DeleteAccountSettingsTemplateVersionWithContext is an alternate form of the DeleteAccountSettingsTemplateVersion method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteAccountSettingsTemplateVersionWithContext(ctx context.Context, deleteAccountSettingsTemplateVersionOptions *DeleteAccountSettingsTemplateVersionOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteAccountSettingsTemplateVersionOptions, "deleteAccountSettingsTemplateVersionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteAllVersionsOfProfileTemplateOptions, "deleteAllVersionsOfProfileTemplateOptions") + err = core.ValidateStruct(deleteAccountSettingsTemplateVersionOptions, "deleteAccountSettingsTemplateVersionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *deleteAllVersionsOfProfileTemplateOptions.TemplateID, + "template_id": *deleteAccountSettingsTemplateVersionOptions.TemplateID, + "version": *deleteAccountSettingsTemplateVersionOptions.Version, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions/{version}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteAllVersionsOfProfileTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAccountSettingsTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAllVersionsOfProfileTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteAccountSettingsTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -5684,7 +6215,7 @@ func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfProfileTemplateWithContext( response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_all_versions_of_profile_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_account_settings_template_version", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -5692,64 +6223,49 @@ func (iamIdentity *IamIdentityV1) DeleteAllVersionsOfProfileTemplateWithContext( return } -// ListVersionsOfProfileTemplate : List trusted profile template versions -// List the versions of a trusted profile template in an enterprise account. -func (iamIdentity *IamIdentityV1) ListVersionsOfProfileTemplate(listVersionsOfProfileTemplateOptions *ListVersionsOfProfileTemplateOptions) (result *TrustedProfileTemplateList, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.ListVersionsOfProfileTemplateWithContext(context.Background(), listVersionsOfProfileTemplateOptions) +// CommitAccountSettingsTemplate : Commit a template version +// Commit a specific version of an account settings template in an Enterprise Account. A Template must be committed +// before being assigned, and once committed, can no longer be modified. +func (iamIdentity *IamIdentityV1) CommitAccountSettingsTemplate(commitAccountSettingsTemplateOptions *CommitAccountSettingsTemplateOptions) (response *core.DetailedResponse, err error) { + response, err = iamIdentity.CommitAccountSettingsTemplateWithContext(context.Background(), commitAccountSettingsTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVersionsOfProfileTemplateWithContext is an alternate form of the ListVersionsOfProfileTemplate method which supports a Context parameter -func (iamIdentity *IamIdentityV1) ListVersionsOfProfileTemplateWithContext(ctx context.Context, listVersionsOfProfileTemplateOptions *ListVersionsOfProfileTemplateOptions) (result *TrustedProfileTemplateList, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVersionsOfProfileTemplateOptions, "listVersionsOfProfileTemplateOptions cannot be nil") +// CommitAccountSettingsTemplateWithContext is an alternate form of the CommitAccountSettingsTemplate method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CommitAccountSettingsTemplateWithContext(ctx context.Context, commitAccountSettingsTemplateOptions *CommitAccountSettingsTemplateOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(commitAccountSettingsTemplateOptions, "commitAccountSettingsTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVersionsOfProfileTemplateOptions, "listVersionsOfProfileTemplateOptions") + err = core.ValidateStruct(commitAccountSettingsTemplateOptions, "commitAccountSettingsTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *listVersionsOfProfileTemplateOptions.TemplateID, + "template_id": *commitAccountSettingsTemplateOptions.TemplateID, + "version": *commitAccountSettingsTemplateOptions.Version, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_templates/{template_id}/versions/{version}/commit`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVersionsOfProfileTemplateOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListVersionsOfProfileTemplate") + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CommitAccountSettingsTemplate") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - if listVersionsOfProfileTemplateOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVersionsOfProfileTemplateOptions.Limit)) - } - if listVersionsOfProfileTemplateOptions.Pagetoken != nil { - builder.AddQuery("pagetoken", fmt.Sprint(*listVersionsOfProfileTemplateOptions.Pagetoken)) - } - if listVersionsOfProfileTemplateOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listVersionsOfProfileTemplateOptions.Sort)) - } - if listVersionsOfProfileTemplateOptions.Order != nil { - builder.AddQuery("order", fmt.Sprint(*listVersionsOfProfileTemplateOptions.Order)) - } - if listVersionsOfProfileTemplateOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*listVersionsOfProfileTemplateOptions.IncludeHistory)) + for headerName, headerValue := range commitAccountSettingsTemplateOptions.Headers { + builder.AddHeader(headerName, headerValue) } request, err := builder.Build() @@ -5758,93 +6274,80 @@ func (iamIdentity *IamIdentityV1) ListVersionsOfProfileTemplateWithContext(ctx c return } - var rawResponse map[string]json.RawMessage - response, err = iamIdentity.Service.Request(request, &rawResponse) + response, err = iamIdentity.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_versions_of_profile_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "commit_account_settings_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateList) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateProfileTemplateVersion : Create new version of a trusted profile template -// Create a new version of a trusted profile template in an enterprise account. -func (iamIdentity *IamIdentityV1) CreateProfileTemplateVersion(createProfileTemplateVersionOptions *CreateProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.CreateProfileTemplateVersionWithContext(context.Background(), createProfileTemplateVersionOptions) +// ListAccountSettingsAssignments : List assignments +// List account settings assignments. +func (iamIdentity *IamIdentityV1) ListAccountSettingsAssignments(listAccountSettingsAssignmentsOptions *ListAccountSettingsAssignmentsOptions) (result *TemplateAssignmentListResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.ListAccountSettingsAssignmentsWithContext(context.Background(), listAccountSettingsAssignmentsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateProfileTemplateVersionWithContext is an alternate form of the CreateProfileTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CreateProfileTemplateVersionWithContext(ctx context.Context, createProfileTemplateVersionOptions *CreateProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createProfileTemplateVersionOptions, "createProfileTemplateVersionOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(createProfileTemplateVersionOptions, "createProfileTemplateVersionOptions") +// ListAccountSettingsAssignmentsWithContext is an alternate form of the ListAccountSettingsAssignments method which supports a Context parameter +func (iamIdentity *IamIdentityV1) ListAccountSettingsAssignmentsWithContext(ctx context.Context, listAccountSettingsAssignmentsOptions *ListAccountSettingsAssignmentsOptions) (result *TemplateAssignmentListResponse, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listAccountSettingsAssignmentsOptions, "listAccountSettingsAssignmentsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "template_id": *createProfileTemplateVersionOptions.TemplateID, - } - - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createProfileTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "ListAccountSettingsAssignments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateProfileTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listAccountSettingsAssignmentsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - body := make(map[string]interface{}) - if createProfileTemplateVersionOptions.AccountID != nil { - body["account_id"] = createProfileTemplateVersionOptions.AccountID + if listAccountSettingsAssignmentsOptions.AccountID != nil { + builder.AddQuery("account_id", fmt.Sprint(*listAccountSettingsAssignmentsOptions.AccountID)) } - if createProfileTemplateVersionOptions.Name != nil { - body["name"] = createProfileTemplateVersionOptions.Name + if listAccountSettingsAssignmentsOptions.TemplateID != nil { + builder.AddQuery("template_id", fmt.Sprint(*listAccountSettingsAssignmentsOptions.TemplateID)) } - if createProfileTemplateVersionOptions.Description != nil { - body["description"] = createProfileTemplateVersionOptions.Description + if listAccountSettingsAssignmentsOptions.TemplateVersion != nil { + builder.AddQuery("template_version", fmt.Sprint(*listAccountSettingsAssignmentsOptions.TemplateVersion)) } - if createProfileTemplateVersionOptions.Profile != nil { - body["profile"] = createProfileTemplateVersionOptions.Profile + if listAccountSettingsAssignmentsOptions.Target != nil { + builder.AddQuery("target", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Target)) } - if createProfileTemplateVersionOptions.PolicyTemplateReferences != nil { - body["policy_template_references"] = createProfileTemplateVersionOptions.PolicyTemplateReferences + if listAccountSettingsAssignmentsOptions.TargetType != nil { + builder.AddQuery("target_type", fmt.Sprint(*listAccountSettingsAssignmentsOptions.TargetType)) } - if createProfileTemplateVersionOptions.ActionControls != nil { - body["action_controls"] = createProfileTemplateVersionOptions.ActionControls + if listAccountSettingsAssignmentsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Limit)) } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listAccountSettingsAssignmentsOptions.Pagetoken != nil { + builder.AddQuery("pagetoken", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Pagetoken)) + } + if listAccountSettingsAssignmentsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Sort)) + } + if listAccountSettingsAssignmentsOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listAccountSettingsAssignmentsOptions.Order)) + } + if listAccountSettingsAssignmentsOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*listAccountSettingsAssignmentsOptions.IncludeHistory)) } request, err := builder.Build() @@ -5856,12 +6359,12 @@ func (iamIdentity *IamIdentityV1) CreateProfileTemplateVersionWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_profile_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_account_settings_assignments", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentListResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5872,53 +6375,64 @@ func (iamIdentity *IamIdentityV1) CreateProfileTemplateVersionWithContext(ctx co return } -// GetProfileTemplateVersion : Get version of trusted profile template -// Get a specific version of a trusted profile template in an enterprise account. -func (iamIdentity *IamIdentityV1) GetProfileTemplateVersion(getProfileTemplateVersionOptions *GetProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.GetProfileTemplateVersionWithContext(context.Background(), getProfileTemplateVersionOptions) +// CreateAccountSettingsAssignment : Create assignment +// Create an assigment for an account settings template. +func (iamIdentity *IamIdentityV1) CreateAccountSettingsAssignment(createAccountSettingsAssignmentOptions *CreateAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.CreateAccountSettingsAssignmentWithContext(context.Background(), createAccountSettingsAssignmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetProfileTemplateVersionWithContext is an alternate form of the GetProfileTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) GetProfileTemplateVersionWithContext(ctx context.Context, getProfileTemplateVersionOptions *GetProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getProfileTemplateVersionOptions, "getProfileTemplateVersionOptions cannot be nil") +// CreateAccountSettingsAssignmentWithContext is an alternate form of the CreateAccountSettingsAssignment method which supports a Context parameter +func (iamIdentity *IamIdentityV1) CreateAccountSettingsAssignmentWithContext(ctx context.Context, createAccountSettingsAssignmentOptions *CreateAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createAccountSettingsAssignmentOptions, "createAccountSettingsAssignmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getProfileTemplateVersionOptions, "getProfileTemplateVersionOptions") + err = core.ValidateStruct(createAccountSettingsAssignmentOptions, "createAccountSettingsAssignmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "template_id": *getProfileTemplateVersionOptions.TemplateID, - "version": *getProfileTemplateVersionOptions.Version, - } - - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions/{version}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getProfileTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CreateAccountSettingsAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetProfileTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createAccountSettingsAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") - if getProfileTemplateVersionOptions.IncludeHistory != nil { - builder.AddQuery("include_history", fmt.Sprint(*getProfileTemplateVersionOptions.IncludeHistory)) + body := make(map[string]interface{}) + if createAccountSettingsAssignmentOptions.TemplateID != nil { + body["template_id"] = createAccountSettingsAssignmentOptions.TemplateID + } + if createAccountSettingsAssignmentOptions.TemplateVersion != nil { + body["template_version"] = createAccountSettingsAssignmentOptions.TemplateVersion + } + if createAccountSettingsAssignmentOptions.TargetType != nil { + body["target_type"] = createAccountSettingsAssignmentOptions.TargetType + } + if createAccountSettingsAssignmentOptions.Target != nil { + body["target"] = createAccountSettingsAssignmentOptions.Target + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -5930,12 +6444,12 @@ func (iamIdentity *IamIdentityV1) GetProfileTemplateVersionWithContext(ctx conte var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_profile_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_account_settings_assignment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5946,78 +6460,52 @@ func (iamIdentity *IamIdentityV1) GetProfileTemplateVersionWithContext(ctx conte return } -// UpdateProfileTemplateVersion : Update version of trusted profile template -// Update a specific version of a trusted profile template in an enterprise account. -func (iamIdentity *IamIdentityV1) UpdateProfileTemplateVersion(updateProfileTemplateVersionOptions *UpdateProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - result, response, err = iamIdentity.UpdateProfileTemplateVersionWithContext(context.Background(), updateProfileTemplateVersionOptions) +// GetAccountSettingsAssignment : Get assignment +// Get an assigment for an account settings template. +func (iamIdentity *IamIdentityV1) GetAccountSettingsAssignment(getAccountSettingsAssignmentOptions *GetAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.GetAccountSettingsAssignmentWithContext(context.Background(), getAccountSettingsAssignmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateProfileTemplateVersionWithContext is an alternate form of the UpdateProfileTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) UpdateProfileTemplateVersionWithContext(ctx context.Context, updateProfileTemplateVersionOptions *UpdateProfileTemplateVersionOptions) (result *TrustedProfileTemplateResponse, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateProfileTemplateVersionOptions, "updateProfileTemplateVersionOptions cannot be nil") +// GetAccountSettingsAssignmentWithContext is an alternate form of the GetAccountSettingsAssignment method which supports a Context parameter +func (iamIdentity *IamIdentityV1) GetAccountSettingsAssignmentWithContext(ctx context.Context, getAccountSettingsAssignmentOptions *GetAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getAccountSettingsAssignmentOptions, "getAccountSettingsAssignmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateProfileTemplateVersionOptions, "updateProfileTemplateVersionOptions") + err = core.ValidateStruct(getAccountSettingsAssignmentOptions, "getAccountSettingsAssignmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *updateProfileTemplateVersionOptions.TemplateID, - "version": *updateProfileTemplateVersionOptions.Version, + "assignment_id": *getAccountSettingsAssignmentOptions.AssignmentID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions/{version}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/{assignment_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateProfileTemplateVersionOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateProfileTemplateVersion") + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "GetAccountSettingsAssignment") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - if updateProfileTemplateVersionOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateProfileTemplateVersionOptions.IfMatch)) - } - body := make(map[string]interface{}) - if updateProfileTemplateVersionOptions.AccountID != nil { - body["account_id"] = updateProfileTemplateVersionOptions.AccountID - } - if updateProfileTemplateVersionOptions.Name != nil { - body["name"] = updateProfileTemplateVersionOptions.Name - } - if updateProfileTemplateVersionOptions.Description != nil { - body["description"] = updateProfileTemplateVersionOptions.Description - } - if updateProfileTemplateVersionOptions.Profile != nil { - body["profile"] = updateProfileTemplateVersionOptions.Profile - } - if updateProfileTemplateVersionOptions.PolicyTemplateReferences != nil { - body["policy_template_references"] = updateProfileTemplateVersionOptions.PolicyTemplateReferences - } - if updateProfileTemplateVersionOptions.ActionControls != nil { - body["action_controls"] = updateProfileTemplateVersionOptions.ActionControls - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + for headerName, headerValue := range getAccountSettingsAssignmentOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + if getAccountSettingsAssignmentOptions.IncludeHistory != nil { + builder.AddQuery("include_history", fmt.Sprint(*getAccountSettingsAssignmentOptions.IncludeHistory)) } request, err := builder.Build() @@ -6029,12 +6517,12 @@ func (iamIdentity *IamIdentityV1) UpdateProfileTemplateVersionWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_profile_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_account_settings_assignment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTrustedProfileTemplateResponse) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6045,50 +6533,50 @@ func (iamIdentity *IamIdentityV1) UpdateProfileTemplateVersionWithContext(ctx co return } -// DeleteProfileTemplateVersion : Delete version of trusted profile template -// Delete a specific version of a trusted profile template in an enterprise account. If the version is assigned to child -// accounts, you must first delete the assignment. -func (iamIdentity *IamIdentityV1) DeleteProfileTemplateVersion(deleteProfileTemplateVersionOptions *DeleteProfileTemplateVersionOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.DeleteProfileTemplateVersionWithContext(context.Background(), deleteProfileTemplateVersionOptions) +// DeleteAccountSettingsAssignment : Delete assignment +// Delete an account settings template assignment. This removes any IAM resources created by this assignment in child +// accounts. +func (iamIdentity *IamIdentityV1) DeleteAccountSettingsAssignment(deleteAccountSettingsAssignmentOptions *DeleteAccountSettingsAssignmentOptions) (result *ExceptionResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.DeleteAccountSettingsAssignmentWithContext(context.Background(), deleteAccountSettingsAssignmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteProfileTemplateVersionWithContext is an alternate form of the DeleteProfileTemplateVersion method which supports a Context parameter -func (iamIdentity *IamIdentityV1) DeleteProfileTemplateVersionWithContext(ctx context.Context, deleteProfileTemplateVersionOptions *DeleteProfileTemplateVersionOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteProfileTemplateVersionOptions, "deleteProfileTemplateVersionOptions cannot be nil") +// DeleteAccountSettingsAssignmentWithContext is an alternate form of the DeleteAccountSettingsAssignment method which supports a Context parameter +func (iamIdentity *IamIdentityV1) DeleteAccountSettingsAssignmentWithContext(ctx context.Context, deleteAccountSettingsAssignmentOptions *DeleteAccountSettingsAssignmentOptions) (result *ExceptionResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteAccountSettingsAssignmentOptions, "deleteAccountSettingsAssignmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteProfileTemplateVersionOptions, "deleteProfileTemplateVersionOptions") + err = core.ValidateStruct(deleteAccountSettingsAssignmentOptions, "deleteAccountSettingsAssignmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *deleteProfileTemplateVersionOptions.TemplateID, - "version": *deleteProfileTemplateVersionOptions.Version, + "assignment_id": *deleteAccountSettingsAssignmentOptions.AssignmentID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions/{version}`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/{assignment_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteProfileTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteAccountSettingsAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "DeleteProfileTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteAccountSettingsAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { @@ -6096,60 +6584,83 @@ func (iamIdentity *IamIdentityV1) DeleteProfileTemplateVersionWithContext(ctx co return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_profile_template_version", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_account_settings_assignment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalExceptionResponse) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// CommitProfileTemplate : Commit a template version -// Commit a specific version of a trusted profile template in an enterprise account. You must commit a template before -// you can assign it to child accounts. Once a template is committed, you can no longer modify the template. -func (iamIdentity *IamIdentityV1) CommitProfileTemplate(commitProfileTemplateOptions *CommitProfileTemplateOptions) (response *core.DetailedResponse, err error) { - response, err = iamIdentity.CommitProfileTemplateWithContext(context.Background(), commitProfileTemplateOptions) +// UpdateAccountSettingsAssignment : Update assignment +// Update an account settings assignment. Call this method to retry failed assignments or migrate the settings in child +// accounts to a new version. +func (iamIdentity *IamIdentityV1) UpdateAccountSettingsAssignment(updateAccountSettingsAssignmentOptions *UpdateAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + result, response, err = iamIdentity.UpdateAccountSettingsAssignmentWithContext(context.Background(), updateAccountSettingsAssignmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// CommitProfileTemplateWithContext is an alternate form of the CommitProfileTemplate method which supports a Context parameter -func (iamIdentity *IamIdentityV1) CommitProfileTemplateWithContext(ctx context.Context, commitProfileTemplateOptions *CommitProfileTemplateOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(commitProfileTemplateOptions, "commitProfileTemplateOptions cannot be nil") +// UpdateAccountSettingsAssignmentWithContext is an alternate form of the UpdateAccountSettingsAssignment method which supports a Context parameter +func (iamIdentity *IamIdentityV1) UpdateAccountSettingsAssignmentWithContext(ctx context.Context, updateAccountSettingsAssignmentOptions *UpdateAccountSettingsAssignmentOptions) (result *TemplateAssignmentResponse, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateAccountSettingsAssignmentOptions, "updateAccountSettingsAssignmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(commitProfileTemplateOptions, "commitProfileTemplateOptions") + err = core.ValidateStruct(updateAccountSettingsAssignmentOptions, "updateAccountSettingsAssignmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "template_id": *commitProfileTemplateOptions.TemplateID, - "version": *commitProfileTemplateOptions.Version, + "assignment_id": *updateAccountSettingsAssignmentOptions.AssignmentID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = iamIdentity.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/profile_templates/{template_id}/versions/{version}/commit`, pathParamsMap) + _, err = builder.ResolveRequestURL(iamIdentity.Service.Options.URL, `/v1/account_settings_assignments/{assignment_id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range commitProfileTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "UpdateAccountSettingsAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_identity", "V1", "CommitProfileTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateAccountSettingsAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + if updateAccountSettingsAssignmentOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateAccountSettingsAssignmentOptions.IfMatch)) + } + + body := make(map[string]interface{}) + if updateAccountSettingsAssignmentOptions.TemplateVersion != nil { + body["template_version"] = updateAccountSettingsAssignmentOptions.TemplateVersion + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } request, err := builder.Build() if err != nil { @@ -6157,12 +6668,21 @@ func (iamIdentity *IamIdentityV1) CommitProfileTemplateWithContext(ctx context.C return } - response, err = iamIdentity.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = iamIdentity.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "commit_profile_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_account_settings_assignment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTemplateAssignmentResponse) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } @@ -6274,45 +6794,44 @@ type AccountSettingsAccountSection struct { // Constants associated with the AccountSettingsAccountSection.RestrictCreateServiceID property. // Defines whether or not creating a service ID is access controlled. Valid values: -// - RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service -// +// * RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service // IDs, including the account owner -// - NOT_RESTRICTED - all members of an account can create service IDs -// - NOT_SET - to 'unset' a previous set value. +// * NOT_RESTRICTED - all members of an account can create service IDs +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsAccountSectionRestrictCreateServiceIDNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsAccountSectionRestrictCreateServiceIDNotSetConst = "NOT_SET" - AccountSettingsAccountSectionRestrictCreateServiceIDRestrictedConst = "RESTRICTED" + AccountSettingsAccountSectionRestrictCreateServiceIDNotSetConst = "NOT_SET" + AccountSettingsAccountSectionRestrictCreateServiceIDRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsAccountSection.RestrictCreatePlatformApikey property. // Defines whether or not creating platform API keys is access controlled. Valid values: -// - RESTRICTED - to apply access control -// - NOT_RESTRICTED - to remove access control -// - NOT_SET - to 'unset' a previous set value. +// * RESTRICTED - to apply access control +// * NOT_RESTRICTED - to remove access control +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsAccountSectionRestrictCreatePlatformApikeyNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsAccountSectionRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" - AccountSettingsAccountSectionRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" + AccountSettingsAccountSectionRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" + AccountSettingsAccountSectionRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsAccountSection.Mfa property. // Defines the MFA requirement for the user. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - AccountSettingsAccountSectionMfaLevel1Const = "LEVEL1" - AccountSettingsAccountSectionMfaLevel2Const = "LEVEL2" - AccountSettingsAccountSectionMfaLevel3Const = "LEVEL3" - AccountSettingsAccountSectionMfaNoneConst = "NONE" + AccountSettingsAccountSectionMfaLevel1Const = "LEVEL1" + AccountSettingsAccountSectionMfaLevel2Const = "LEVEL2" + AccountSettingsAccountSectionMfaLevel3Const = "LEVEL3" + AccountSettingsAccountSectionMfaNoneConst = "NONE" AccountSettingsAccountSectionMfaNoneNoRopcConst = "NONE_NO_ROPC" - AccountSettingsAccountSectionMfaTotpConst = "TOTP" - AccountSettingsAccountSectionMfaTotp4allConst = "TOTP4ALL" + AccountSettingsAccountSectionMfaTotpConst = "TOTP" + AccountSettingsAccountSectionMfaTotp4allConst = "TOTP4ALL" ) // UnmarshalAccountSettingsAccountSection unmarshals an instance of AccountSettingsAccountSection from the specified map of raw messages. @@ -6450,45 +6969,44 @@ type AccountSettingsAssignedTemplatesSection struct { // Constants associated with the AccountSettingsAssignedTemplatesSection.RestrictCreateServiceID property. // Defines whether or not creating a service ID is access controlled. Valid values: -// - RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service -// +// * RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service // IDs, including the account owner -// - NOT_RESTRICTED - all members of an account can create service IDs -// - NOT_SET - to 'unset' a previous set value. +// * NOT_RESTRICTED - all members of an account can create service IDs +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsAssignedTemplatesSectionRestrictCreateServiceIDNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsAssignedTemplatesSectionRestrictCreateServiceIDNotSetConst = "NOT_SET" - AccountSettingsAssignedTemplatesSectionRestrictCreateServiceIDRestrictedConst = "RESTRICTED" + AccountSettingsAssignedTemplatesSectionRestrictCreateServiceIDNotSetConst = "NOT_SET" + AccountSettingsAssignedTemplatesSectionRestrictCreateServiceIDRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsAssignedTemplatesSection.RestrictCreatePlatformApikey property. // Defines whether or not creating platform API keys is access controlled. Valid values: -// - RESTRICTED - to apply access control -// - NOT_RESTRICTED - to remove access control -// - NOT_SET - to 'unset' a previous set value. +// * RESTRICTED - to apply access control +// * NOT_RESTRICTED - to remove access control +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsAssignedTemplatesSectionRestrictCreatePlatformApikeyNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsAssignedTemplatesSectionRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" - AccountSettingsAssignedTemplatesSectionRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" + AccountSettingsAssignedTemplatesSectionRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" + AccountSettingsAssignedTemplatesSectionRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsAssignedTemplatesSection.Mfa property. // Defines the MFA requirement for the user. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - AccountSettingsAssignedTemplatesSectionMfaLevel1Const = "LEVEL1" - AccountSettingsAssignedTemplatesSectionMfaLevel2Const = "LEVEL2" - AccountSettingsAssignedTemplatesSectionMfaLevel3Const = "LEVEL3" - AccountSettingsAssignedTemplatesSectionMfaNoneConst = "NONE" + AccountSettingsAssignedTemplatesSectionMfaLevel1Const = "LEVEL1" + AccountSettingsAssignedTemplatesSectionMfaLevel2Const = "LEVEL2" + AccountSettingsAssignedTemplatesSectionMfaLevel3Const = "LEVEL3" + AccountSettingsAssignedTemplatesSectionMfaNoneConst = "NONE" AccountSettingsAssignedTemplatesSectionMfaNoneNoRopcConst = "NONE_NO_ROPC" - AccountSettingsAssignedTemplatesSectionMfaTotpConst = "TOTP" - AccountSettingsAssignedTemplatesSectionMfaTotp4allConst = "TOTP4ALL" + AccountSettingsAssignedTemplatesSectionMfaTotpConst = "TOTP" + AccountSettingsAssignedTemplatesSectionMfaTotp4allConst = "TOTP4ALL" ) // UnmarshalAccountSettingsAssignedTemplatesSection unmarshals an instance of AccountSettingsAssignedTemplatesSection from the specified map of raw messages. @@ -6622,45 +7140,44 @@ type AccountSettingsComponent struct { // Constants associated with the AccountSettingsComponent.RestrictCreateServiceID property. // Defines whether or not creating a service ID is access controlled. Valid values: -// - RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service -// +// * RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service // IDs, including the account owner -// - NOT_RESTRICTED - all members of an account can create service IDs -// - NOT_SET - to 'unset' a previous set value. +// * NOT_RESTRICTED - all members of an account can create service IDs +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsComponentRestrictCreateServiceIDNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsComponentRestrictCreateServiceIDNotSetConst = "NOT_SET" - AccountSettingsComponentRestrictCreateServiceIDRestrictedConst = "RESTRICTED" + AccountSettingsComponentRestrictCreateServiceIDNotSetConst = "NOT_SET" + AccountSettingsComponentRestrictCreateServiceIDRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsComponent.RestrictCreatePlatformApikey property. // Defines whether or not creating platform API keys is access controlled. Valid values: -// - RESTRICTED - to apply access control -// - NOT_RESTRICTED - to remove access control -// - NOT_SET - to 'unset' a previous set value. +// * RESTRICTED - to apply access control +// * NOT_RESTRICTED - to remove access control +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsComponentRestrictCreatePlatformApikeyNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsComponentRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" - AccountSettingsComponentRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" + AccountSettingsComponentRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" + AccountSettingsComponentRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsComponent.Mfa property. // Defines the MFA trait for the account. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - AccountSettingsComponentMfaLevel1Const = "LEVEL1" - AccountSettingsComponentMfaLevel2Const = "LEVEL2" - AccountSettingsComponentMfaLevel3Const = "LEVEL3" - AccountSettingsComponentMfaNoneConst = "NONE" + AccountSettingsComponentMfaLevel1Const = "LEVEL1" + AccountSettingsComponentMfaLevel2Const = "LEVEL2" + AccountSettingsComponentMfaLevel3Const = "LEVEL3" + AccountSettingsComponentMfaNoneConst = "NONE" AccountSettingsComponentMfaNoneNoRopcConst = "NONE_NO_ROPC" - AccountSettingsComponentMfaTotpConst = "TOTP" - AccountSettingsComponentMfaTotp4allConst = "TOTP4ALL" + AccountSettingsComponentMfaTotpConst = "TOTP" + AccountSettingsComponentMfaTotp4allConst = "TOTP4ALL" ) // UnmarshalAccountSettingsComponent unmarshals an instance of AccountSettingsComponent from the specified map of raw messages. @@ -6779,45 +7296,44 @@ type AccountSettingsEffectiveSection struct { // Constants associated with the AccountSettingsEffectiveSection.RestrictCreateServiceID property. // Defines whether or not creating a service ID is access controlled. Valid values: -// - RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service -// +// * RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service // IDs, including the account owner -// - NOT_RESTRICTED - all members of an account can create service IDs -// - NOT_SET - to 'unset' a previous set value. +// * NOT_RESTRICTED - all members of an account can create service IDs +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsEffectiveSectionRestrictCreateServiceIDNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsEffectiveSectionRestrictCreateServiceIDNotSetConst = "NOT_SET" - AccountSettingsEffectiveSectionRestrictCreateServiceIDRestrictedConst = "RESTRICTED" + AccountSettingsEffectiveSectionRestrictCreateServiceIDNotSetConst = "NOT_SET" + AccountSettingsEffectiveSectionRestrictCreateServiceIDRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsEffectiveSection.RestrictCreatePlatformApikey property. // Defines whether or not creating platform API keys is access controlled. Valid values: -// - RESTRICTED - to apply access control -// - NOT_RESTRICTED - to remove access control -// - NOT_SET - to 'unset' a previous set value. +// * RESTRICTED - to apply access control +// * NOT_RESTRICTED - to remove access control +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsEffectiveSectionRestrictCreatePlatformApikeyNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsEffectiveSectionRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" - AccountSettingsEffectiveSectionRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" + AccountSettingsEffectiveSectionRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" + AccountSettingsEffectiveSectionRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsEffectiveSection.Mfa property. // Defines the MFA requirement for the user. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - AccountSettingsEffectiveSectionMfaLevel1Const = "LEVEL1" - AccountSettingsEffectiveSectionMfaLevel2Const = "LEVEL2" - AccountSettingsEffectiveSectionMfaLevel3Const = "LEVEL3" - AccountSettingsEffectiveSectionMfaNoneConst = "NONE" + AccountSettingsEffectiveSectionMfaLevel1Const = "LEVEL1" + AccountSettingsEffectiveSectionMfaLevel2Const = "LEVEL2" + AccountSettingsEffectiveSectionMfaLevel3Const = "LEVEL3" + AccountSettingsEffectiveSectionMfaNoneConst = "NONE" AccountSettingsEffectiveSectionMfaNoneNoRopcConst = "NONE_NO_ROPC" - AccountSettingsEffectiveSectionMfaTotpConst = "TOTP" - AccountSettingsEffectiveSectionMfaTotp4allConst = "TOTP4ALL" + AccountSettingsEffectiveSectionMfaTotpConst = "TOTP" + AccountSettingsEffectiveSectionMfaTotp4allConst = "TOTP4ALL" ) // UnmarshalAccountSettingsEffectiveSection unmarshals an instance of AccountSettingsEffectiveSection from the specified map of raw messages. @@ -6948,45 +7464,44 @@ type AccountSettingsResponse struct { // Constants associated with the AccountSettingsResponse.RestrictCreateServiceID property. // Defines whether or not creating a service ID is access controlled. Valid values: -// - RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service -// +// * RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service // IDs, including the account owner -// - NOT_RESTRICTED - all members of an account can create service IDs -// - NOT_SET - to 'unset' a previous set value. +// * NOT_RESTRICTED - all members of an account can create service IDs +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsResponseRestrictCreateServiceIDNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsResponseRestrictCreateServiceIDNotSetConst = "NOT_SET" - AccountSettingsResponseRestrictCreateServiceIDRestrictedConst = "RESTRICTED" + AccountSettingsResponseRestrictCreateServiceIDNotSetConst = "NOT_SET" + AccountSettingsResponseRestrictCreateServiceIDRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsResponse.RestrictCreatePlatformApikey property. // Defines whether or not creating platform API keys is access controlled. Valid values: -// - RESTRICTED - to apply access control -// - NOT_RESTRICTED - to remove access control -// - NOT_SET - to 'unset' a previous set value. +// * RESTRICTED - to apply access control +// * NOT_RESTRICTED - to remove access control +// * NOT_SET - to 'unset' a previous set value. const ( AccountSettingsResponseRestrictCreatePlatformApikeyNotRestrictedConst = "NOT_RESTRICTED" - AccountSettingsResponseRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" - AccountSettingsResponseRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" + AccountSettingsResponseRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" + AccountSettingsResponseRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" ) // Constants associated with the AccountSettingsResponse.Mfa property. // Defines the MFA trait for the account. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - AccountSettingsResponseMfaLevel1Const = "LEVEL1" - AccountSettingsResponseMfaLevel2Const = "LEVEL2" - AccountSettingsResponseMfaLevel3Const = "LEVEL3" - AccountSettingsResponseMfaNoneConst = "NONE" + AccountSettingsResponseMfaLevel1Const = "LEVEL1" + AccountSettingsResponseMfaLevel2Const = "LEVEL2" + AccountSettingsResponseMfaLevel3Const = "LEVEL3" + AccountSettingsResponseMfaNoneConst = "NONE" AccountSettingsResponseMfaNoneNoRopcConst = "NONE_NO_ROPC" - AccountSettingsResponseMfaTotpConst = "TOTP" - AccountSettingsResponseMfaTotp4allConst = "TOTP4ALL" + AccountSettingsResponseMfaTotpConst = "TOTP" + AccountSettingsResponseMfaTotp4allConst = "TOTP4ALL" ) // UnmarshalAccountSettingsResponse unmarshals an instance of AccountSettingsResponse from the specified map of raw messages. @@ -7273,28 +7788,28 @@ type AccountSettingsUserMfa struct { // Constants associated with the AccountSettingsUserMfa.Mfa property. // Defines the MFA requirement for the user. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - AccountSettingsUserMfaMfaLevel1Const = "LEVEL1" - AccountSettingsUserMfaMfaLevel2Const = "LEVEL2" - AccountSettingsUserMfaMfaLevel3Const = "LEVEL3" - AccountSettingsUserMfaMfaNoneConst = "NONE" + AccountSettingsUserMfaMfaLevel1Const = "LEVEL1" + AccountSettingsUserMfaMfaLevel2Const = "LEVEL2" + AccountSettingsUserMfaMfaLevel3Const = "LEVEL3" + AccountSettingsUserMfaMfaNoneConst = "NONE" AccountSettingsUserMfaMfaNoneNoRopcConst = "NONE_NO_ROPC" - AccountSettingsUserMfaMfaTotpConst = "TOTP" - AccountSettingsUserMfaMfaTotp4allConst = "TOTP4ALL" + AccountSettingsUserMfaMfaTotpConst = "TOTP" + AccountSettingsUserMfaMfaTotp4allConst = "TOTP4ALL" ) // NewAccountSettingsUserMfa : Instantiate AccountSettingsUserMfa (Generic Model Constructor) func (*IamIdentityV1) NewAccountSettingsUserMfa(iamID string, mfa string) (_model *AccountSettingsUserMfa, err error) { _model = &AccountSettingsUserMfa{ IamID: core.StringPtr(iamID), - Mfa: core.StringPtr(mfa), + Mfa: core.StringPtr(mfa), } err = core.ValidateStruct(_model, "required parameters") if err != nil { @@ -7332,7 +7847,7 @@ type ActionControls struct { // NewActionControls : Instantiate ActionControls (Generic Model Constructor) func (*IamIdentityV1) NewActionControls(rules *ActionControlsRules, policies *ActionControlsPolicies) (_model *ActionControls, err error) { _model = &ActionControls{ - Rules: rules, + Rules: rules, Policies: policies, } err = core.ValidateStruct(_model, "required parameters") @@ -7374,7 +7889,7 @@ type ActionControlsIdentities struct { // NewActionControlsIdentities : Instantiate ActionControlsIdentities (Generic Model Constructor) func (*IamIdentityV1) NewActionControlsIdentities(add bool, remove bool) (_model *ActionControlsIdentities, err error) { _model = &ActionControlsIdentities{ - Add: core.BoolPtr(add), + Add: core.BoolPtr(add), Remove: core.BoolPtr(remove), } err = core.ValidateStruct(_model, "required parameters") @@ -7411,7 +7926,7 @@ type ActionControlsPolicies struct { // NewActionControlsPolicies : Instantiate ActionControlsPolicies (Generic Model Constructor) func (*IamIdentityV1) NewActionControlsPolicies(add bool, remove bool) (_model *ActionControlsPolicies, err error) { _model = &ActionControlsPolicies{ - Add: core.BoolPtr(add), + Add: core.BoolPtr(add), Remove: core.BoolPtr(remove), } err = core.ValidateStruct(_model, "required parameters") @@ -7448,7 +7963,7 @@ type ActionControlsRules struct { // NewActionControlsRules : Instantiate ActionControlsRules (Generic Model Constructor) func (*IamIdentityV1) NewActionControlsRules(add bool, remove bool) (_model *ActionControlsRules, err error) { _model = &ActionControlsRules{ - Add: core.BoolPtr(add), + Add: core.BoolPtr(add), Remove: core.BoolPtr(remove), } err = core.ValidateStruct(_model, "required parameters") @@ -7935,7 +8450,7 @@ type CommitAccountSettingsTemplateOptions struct { func (*IamIdentityV1) NewCommitAccountSettingsTemplateOptions(templateID string, version string) *CommitAccountSettingsTemplateOptions { return &CommitAccountSettingsTemplateOptions{ TemplateID: core.StringPtr(templateID), - Version: core.StringPtr(version), + Version: core.StringPtr(version), } } @@ -7973,7 +8488,7 @@ type CommitProfileTemplateOptions struct { func (*IamIdentityV1) NewCommitProfileTemplateOptions(templateID string, version string) *CommitProfileTemplateOptions { return &CommitProfileTemplateOptions{ TemplateID: core.StringPtr(templateID), - Version: core.StringPtr(version), + Version: core.StringPtr(version), } } @@ -8016,17 +8531,17 @@ type CreateAccountSettingsAssignmentOptions struct { // Constants associated with the CreateAccountSettingsAssignmentOptions.TargetType property. // Type of target to deploy to. const ( - CreateAccountSettingsAssignmentOptionsTargetTypeAccountConst = "Account" + CreateAccountSettingsAssignmentOptionsTargetTypeAccountConst = "Account" CreateAccountSettingsAssignmentOptionsTargetTypeAccountgroupConst = "AccountGroup" ) // NewCreateAccountSettingsAssignmentOptions : Instantiate CreateAccountSettingsAssignmentOptions func (*IamIdentityV1) NewCreateAccountSettingsAssignmentOptions(templateID string, templateVersion int64, targetType string, target string) *CreateAccountSettingsAssignmentOptions { return &CreateAccountSettingsAssignmentOptions{ - TemplateID: core.StringPtr(templateID), + TemplateID: core.StringPtr(templateID), TemplateVersion: core.Int64Ptr(templateVersion), - TargetType: core.StringPtr(targetType), - Target: core.StringPtr(target), + TargetType: core.StringPtr(targetType), + Target: core.StringPtr(target), } } @@ -8224,7 +8739,7 @@ type CreateAPIKeyOptions struct { // NewCreateAPIKeyOptions : Instantiate CreateAPIKeyOptions func (*IamIdentityV1) NewCreateAPIKeyOptions(name string, iamID string) *CreateAPIKeyOptions { return &CreateAPIKeyOptions{ - Name: core.StringPtr(name), + Name: core.StringPtr(name), IamID: core.StringPtr(iamID), } } @@ -8330,8 +8845,8 @@ type CreateClaimRuleOptions struct { // NewCreateClaimRuleOptions : Instantiate CreateClaimRuleOptions func (*IamIdentityV1) NewCreateClaimRuleOptions(profileID string, typeVar string, conditions []ProfileClaimRuleConditions) *CreateClaimRuleOptions { return &CreateClaimRuleOptions{ - ProfileID: core.StringPtr(profileID), - Type: core.StringPtr(typeVar), + ProfileID: core.StringPtr(profileID), + Type: core.StringPtr(typeVar), Conditions: conditions, } } @@ -8412,8 +8927,8 @@ type CreateLinkOptions struct { func (*IamIdentityV1) NewCreateLinkOptions(profileID string, crType string, link *CreateProfileLinkRequestLink) *CreateLinkOptions { return &CreateLinkOptions{ ProfileID: core.StringPtr(profileID), - CrType: core.StringPtr(crType), - Link: link, + CrType: core.StringPtr(crType), + Link: link, } } @@ -8490,17 +9005,22 @@ type CreateProfileLinkRequestLink struct { CRN *string `json:"crn" validate:"required"` // The compute resource namespace, only required if cr_type is IKS_SA or ROKS_SA. - Namespace *string `json:"namespace" validate:"required"` + Namespace *string `json:"namespace,omitempty"` // Name of the compute resource, only required if cr_type is IKS_SA or ROKS_SA. Name *string `json:"name,omitempty"` + + // Component type of the compute resource, only required if cr_type is CE. + ComponentType *string `json:"component_type,omitempty"` + + // Component name of the compute resource, only required if cr_type is CE. + ComponentName *string `json:"component_name,omitempty"` } // NewCreateProfileLinkRequestLink : Instantiate CreateProfileLinkRequestLink (Generic Model Constructor) -func (*IamIdentityV1) NewCreateProfileLinkRequestLink(crn string, namespace string) (_model *CreateProfileLinkRequestLink, err error) { +func (*IamIdentityV1) NewCreateProfileLinkRequestLink(crn string) (_model *CreateProfileLinkRequestLink, err error) { _model = &CreateProfileLinkRequestLink{ - CRN: core.StringPtr(crn), - Namespace: core.StringPtr(namespace), + CRN: core.StringPtr(crn), } err = core.ValidateStruct(_model, "required parameters") if err != nil { @@ -8527,6 +9047,16 @@ func UnmarshalCreateProfileLinkRequestLink(m map[string]json.RawMessage, result err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "component_type", &obj.ComponentType) + if err != nil { + err = core.SDKErrorf(err, "", "component_type-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "component_name", &obj.ComponentName) + if err != nil { + err = core.SDKErrorf(err, "", "component_name-error", common.GetComponentInfo()) + return + } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } @@ -8544,6 +9074,9 @@ type CreateProfileOptions struct { // provided during creation of trusted profile. Description *string `json:"description,omitempty"` + // The email of the trusted profile. + Email *string `json:"email,omitempty"` + // Allows users to set headers on API requests. Headers map[string]string } @@ -8551,7 +9084,7 @@ type CreateProfileOptions struct { // NewCreateProfileOptions : Instantiate CreateProfileOptions func (*IamIdentityV1) NewCreateProfileOptions(name string, accountID string) *CreateProfileOptions { return &CreateProfileOptions{ - Name: core.StringPtr(name), + Name: core.StringPtr(name), AccountID: core.StringPtr(accountID), } } @@ -8574,6 +9107,12 @@ func (_options *CreateProfileOptions) SetDescription(description string) *Create return _options } +// SetEmail : Allow user to set Email +func (_options *CreateProfileOptions) SetEmail(email string) *CreateProfileOptions { + _options.Email = core.StringPtr(email) + return _options +} + // SetHeaders : Allow user to set Headers func (options *CreateProfileOptions) SetHeaders(param map[string]string) *CreateProfileOptions { options.Headers = param @@ -8782,6 +9321,53 @@ func (options *CreateReportOptions) SetHeaders(param map[string]string) *CreateR return options } +// CreateServiceIDGroupOptions : The CreateServiceIDGroup options. +type CreateServiceIDGroupOptions struct { + // ID of the account the service ID group belongs to. + AccountID *string `json:"account_id" validate:"required"` + + // Name of the service ID group. Unique in the account. + Name *string `json:"name" validate:"required"` + + // Description of the service ID group. + Description *string `json:"description,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewCreateServiceIDGroupOptions : Instantiate CreateServiceIDGroupOptions +func (*IamIdentityV1) NewCreateServiceIDGroupOptions(accountID string, name string) *CreateServiceIDGroupOptions { + return &CreateServiceIDGroupOptions{ + AccountID: core.StringPtr(accountID), + Name: core.StringPtr(name), + } +} + +// SetAccountID : Allow user to set AccountID +func (_options *CreateServiceIDGroupOptions) SetAccountID(accountID string) *CreateServiceIDGroupOptions { + _options.AccountID = core.StringPtr(accountID) + return _options +} + +// SetName : Allow user to set Name +func (_options *CreateServiceIDGroupOptions) SetName(name string) *CreateServiceIDGroupOptions { + _options.Name = core.StringPtr(name) + return _options +} + +// SetDescription : Allow user to set Description +func (_options *CreateServiceIDGroupOptions) SetDescription(description string) *CreateServiceIDGroupOptions { + _options.Description = core.StringPtr(description) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *CreateServiceIDGroupOptions) SetHeaders(param map[string]string) *CreateServiceIDGroupOptions { + options.Headers = param + return options +} + // CreateServiceIDOptions : The CreateServiceID options. type CreateServiceIDOptions struct { // ID of the account the service ID belongs to. @@ -8791,6 +9377,10 @@ type CreateServiceIDOptions struct { // exist. Access is done via the UUID of the Service Id. Name *string `json:"name" validate:"required"` + // ID of the group to which the service ID belongs to. If the value is not set, the service ID is bound to the default + // group. + GroupID *string `json:"group_id,omitempty"` + // The optional description of the Service Id. The 'description' property is only available if a description was // provided during a create of a Service Id. Description *string `json:"description,omitempty"` @@ -8801,6 +9391,9 @@ type CreateServiceIDOptions struct { // Parameters for the API key in the Create service Id V1 REST request. Apikey *APIKeyInsideCreateServiceIDRequest `json:"apikey,omitempty"` + // Defines if the service ID group ID is included in the response. + ShowGroupID *string `json:"show_group_id,omitempty"` + // Indicates if the service ID is locked for further write operations. False by default. EntityLock *string `json:"Entity-Lock,omitempty"` @@ -8812,7 +9405,7 @@ type CreateServiceIDOptions struct { func (*IamIdentityV1) NewCreateServiceIDOptions(accountID string, name string) *CreateServiceIDOptions { return &CreateServiceIDOptions{ AccountID: core.StringPtr(accountID), - Name: core.StringPtr(name), + Name: core.StringPtr(name), } } @@ -8828,6 +9421,12 @@ func (_options *CreateServiceIDOptions) SetName(name string) *CreateServiceIDOpt return _options } +// SetGroupID : Allow user to set GroupID +func (_options *CreateServiceIDOptions) SetGroupID(groupID string) *CreateServiceIDOptions { + _options.GroupID = core.StringPtr(groupID) + return _options +} + // SetDescription : Allow user to set Description func (_options *CreateServiceIDOptions) SetDescription(description string) *CreateServiceIDOptions { _options.Description = core.StringPtr(description) @@ -8846,6 +9445,12 @@ func (_options *CreateServiceIDOptions) SetApikey(apikey *APIKeyInsideCreateServ return _options } +// SetShowGroupID : Allow user to set ShowGroupID +func (_options *CreateServiceIDOptions) SetShowGroupID(showGroupID string) *CreateServiceIDOptions { + _options.ShowGroupID = core.StringPtr(showGroupID) + return _options +} + // SetEntityLock : Allow user to set EntityLock func (_options *CreateServiceIDOptions) SetEntityLock(entityLock string) *CreateServiceIDOptions { _options.EntityLock = core.StringPtr(entityLock) @@ -8879,17 +9484,17 @@ type CreateTrustedProfileAssignmentOptions struct { // Constants associated with the CreateTrustedProfileAssignmentOptions.TargetType property. // Type of target to deploy to. const ( - CreateTrustedProfileAssignmentOptionsTargetTypeAccountConst = "Account" + CreateTrustedProfileAssignmentOptionsTargetTypeAccountConst = "Account" CreateTrustedProfileAssignmentOptionsTargetTypeAccountgroupConst = "AccountGroup" ) // NewCreateTrustedProfileAssignmentOptions : Instantiate CreateTrustedProfileAssignmentOptions func (*IamIdentityV1) NewCreateTrustedProfileAssignmentOptions(templateID string, templateVersion int64, targetType string, target string) *CreateTrustedProfileAssignmentOptions { return &CreateTrustedProfileAssignmentOptions{ - TemplateID: core.StringPtr(templateID), + TemplateID: core.StringPtr(templateID), TemplateVersion: core.Int64Ptr(templateVersion), - TargetType: core.StringPtr(targetType), - Target: core.StringPtr(target), + TargetType: core.StringPtr(targetType), + Target: core.StringPtr(target), } } @@ -8967,7 +9572,7 @@ type DeleteAccountSettingsTemplateVersionOptions struct { func (*IamIdentityV1) NewDeleteAccountSettingsTemplateVersionOptions(templateID string, version string) *DeleteAccountSettingsTemplateVersionOptions { return &DeleteAccountSettingsTemplateVersionOptions{ TemplateID: core.StringPtr(templateID), - Version: core.StringPtr(version), + Version: core.StringPtr(version), } } @@ -9089,7 +9694,7 @@ type DeleteClaimRuleOptions struct { func (*IamIdentityV1) NewDeleteClaimRuleOptions(profileID string, ruleID string) *DeleteClaimRuleOptions { return &DeleteClaimRuleOptions{ ProfileID: core.StringPtr(profileID), - RuleID: core.StringPtr(ruleID), + RuleID: core.StringPtr(ruleID), } } @@ -9111,6 +9716,89 @@ func (options *DeleteClaimRuleOptions) SetHeaders(param map[string]string) *Dele return options } +// DeleteLinkByParametersOptions : The DeleteLinkByParameters options. +type DeleteLinkByParametersOptions struct { + // The unique ID of the Trusted Profile. + ProfileID *string `json:"profile-id" validate:"required,ne="` + + // The compute resource type. Valid values are VSI, BMS, IKS_SA, ROKS_SA, CE. + Type *string `json:"type" validate:"required"` + + // CRN of the compute resource (IKS/ROKS/VSI/BMS). + CRN *string `json:"crn,omitempty"` + + // Namespace of the compute resource (IKS/ROKS). + Namespace *string `json:"namespace,omitempty"` + + // Name of the compute resource (IKS/ROKS). + Name *string `json:"name,omitempty"` + + // Component type of the compute resource, only required if type is CE. + ComponentType *string `json:"component_type,omitempty"` + + // Component name of the compute resource, only required if type is CE. + ComponentName *string `json:"component_name,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewDeleteLinkByParametersOptions : Instantiate DeleteLinkByParametersOptions +func (*IamIdentityV1) NewDeleteLinkByParametersOptions(profileID string, typeVar string) *DeleteLinkByParametersOptions { + return &DeleteLinkByParametersOptions{ + ProfileID: core.StringPtr(profileID), + Type: core.StringPtr(typeVar), + } +} + +// SetProfileID : Allow user to set ProfileID +func (_options *DeleteLinkByParametersOptions) SetProfileID(profileID string) *DeleteLinkByParametersOptions { + _options.ProfileID = core.StringPtr(profileID) + return _options +} + +// SetType : Allow user to set Type +func (_options *DeleteLinkByParametersOptions) SetType(typeVar string) *DeleteLinkByParametersOptions { + _options.Type = core.StringPtr(typeVar) + return _options +} + +// SetCRN : Allow user to set CRN +func (_options *DeleteLinkByParametersOptions) SetCRN(crn string) *DeleteLinkByParametersOptions { + _options.CRN = core.StringPtr(crn) + return _options +} + +// SetNamespace : Allow user to set Namespace +func (_options *DeleteLinkByParametersOptions) SetNamespace(namespace string) *DeleteLinkByParametersOptions { + _options.Namespace = core.StringPtr(namespace) + return _options +} + +// SetName : Allow user to set Name +func (_options *DeleteLinkByParametersOptions) SetName(name string) *DeleteLinkByParametersOptions { + _options.Name = core.StringPtr(name) + return _options +} + +// SetComponentType : Allow user to set ComponentType +func (_options *DeleteLinkByParametersOptions) SetComponentType(componentType string) *DeleteLinkByParametersOptions { + _options.ComponentType = core.StringPtr(componentType) + return _options +} + +// SetComponentName : Allow user to set ComponentName +func (_options *DeleteLinkByParametersOptions) SetComponentName(componentName string) *DeleteLinkByParametersOptions { + _options.ComponentName = core.StringPtr(componentName) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *DeleteLinkByParametersOptions) SetHeaders(param map[string]string) *DeleteLinkByParametersOptions { + options.Headers = param + return options +} + // DeleteLinkOptions : The DeleteLink options. type DeleteLinkOptions struct { // ID of the trusted profile. @@ -9127,7 +9815,7 @@ type DeleteLinkOptions struct { func (*IamIdentityV1) NewDeleteLinkOptions(profileID string, linkID string) *DeleteLinkOptions { return &DeleteLinkOptions{ ProfileID: core.StringPtr(profileID), - LinkID: core.StringPtr(linkID), + LinkID: core.StringPtr(linkID), } } @@ -9170,9 +9858,9 @@ type DeletePreferencesOnScopeAccountOptions struct { // NewDeletePreferencesOnScopeAccountOptions : Instantiate DeletePreferencesOnScopeAccountOptions func (*IamIdentityV1) NewDeletePreferencesOnScopeAccountOptions(accountID string, iamID string, service string, preferenceID string) *DeletePreferencesOnScopeAccountOptions { return &DeletePreferencesOnScopeAccountOptions{ - AccountID: core.StringPtr(accountID), - IamID: core.StringPtr(iamID), - Service: core.StringPtr(service), + AccountID: core.StringPtr(accountID), + IamID: core.StringPtr(iamID), + Service: core.StringPtr(service), PreferenceID: core.StringPtr(preferenceID), } } @@ -9225,15 +9913,15 @@ type DeleteProfileIdentityOptions struct { // Constants associated with the DeleteProfileIdentityOptions.IdentityType property. // Type of the identity. const ( - DeleteProfileIdentityOptionsIdentityTypeCRNConst = "crn" + DeleteProfileIdentityOptionsIdentityTypeCRNConst = "crn" DeleteProfileIdentityOptionsIdentityTypeServiceidConst = "serviceid" - DeleteProfileIdentityOptionsIdentityTypeUserConst = "user" + DeleteProfileIdentityOptionsIdentityTypeUserConst = "user" ) // NewDeleteProfileIdentityOptions : Instantiate DeleteProfileIdentityOptions func (*IamIdentityV1) NewDeleteProfileIdentityOptions(profileID string, identityType string, identifierID string) *DeleteProfileIdentityOptions { return &DeleteProfileIdentityOptions{ - ProfileID: core.StringPtr(profileID), + ProfileID: core.StringPtr(profileID), IdentityType: core.StringPtr(identityType), IdentifierID: core.StringPtr(identifierID), } @@ -9307,7 +9995,7 @@ type DeleteProfileTemplateVersionOptions struct { func (*IamIdentityV1) NewDeleteProfileTemplateVersionOptions(templateID string, version string) *DeleteProfileTemplateVersionOptions { return &DeleteProfileTemplateVersionOptions{ TemplateID: core.StringPtr(templateID), - Version: core.StringPtr(version), + Version: core.StringPtr(version), } } @@ -9317,14 +10005,42 @@ func (_options *DeleteProfileTemplateVersionOptions) SetTemplateID(templateID st return _options } -// SetVersion : Allow user to set Version -func (_options *DeleteProfileTemplateVersionOptions) SetVersion(version string) *DeleteProfileTemplateVersionOptions { - _options.Version = core.StringPtr(version) +// SetVersion : Allow user to set Version +func (_options *DeleteProfileTemplateVersionOptions) SetVersion(version string) *DeleteProfileTemplateVersionOptions { + _options.Version = core.StringPtr(version) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *DeleteProfileTemplateVersionOptions) SetHeaders(param map[string]string) *DeleteProfileTemplateVersionOptions { + options.Headers = param + return options +} + +// DeleteServiceIDGroupOptions : The DeleteServiceIDGroup options. +type DeleteServiceIDGroupOptions struct { + // Unique ID of the service ID group. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewDeleteServiceIDGroupOptions : Instantiate DeleteServiceIDGroupOptions +func (*IamIdentityV1) NewDeleteServiceIDGroupOptions(id string) *DeleteServiceIDGroupOptions { + return &DeleteServiceIDGroupOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *DeleteServiceIDGroupOptions) SetID(id string) *DeleteServiceIDGroupOptions { + _options.ID = core.StringPtr(id) return _options } // SetHeaders : Allow user to set Headers -func (options *DeleteProfileTemplateVersionOptions) SetHeaders(param map[string]string) *DeleteProfileTemplateVersionOptions { +func (options *DeleteServiceIDGroupOptions) SetHeaders(param map[string]string) *DeleteServiceIDGroupOptions { options.Headers = param return options } @@ -9491,21 +10207,21 @@ type EffectiveAccountSettingsUserMfa struct { // Constants associated with the EffectiveAccountSettingsUserMfa.Mfa property. // Defines the MFA requirement for the user. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - EffectiveAccountSettingsUserMfaMfaLevel1Const = "LEVEL1" - EffectiveAccountSettingsUserMfaMfaLevel2Const = "LEVEL2" - EffectiveAccountSettingsUserMfaMfaLevel3Const = "LEVEL3" - EffectiveAccountSettingsUserMfaMfaNoneConst = "NONE" + EffectiveAccountSettingsUserMfaMfaLevel1Const = "LEVEL1" + EffectiveAccountSettingsUserMfaMfaLevel2Const = "LEVEL2" + EffectiveAccountSettingsUserMfaMfaLevel3Const = "LEVEL3" + EffectiveAccountSettingsUserMfaMfaNoneConst = "NONE" EffectiveAccountSettingsUserMfaMfaNoneNoRopcConst = "NONE_NO_ROPC" - EffectiveAccountSettingsUserMfaMfaTotpConst = "TOTP" - EffectiveAccountSettingsUserMfaMfaTotp4allConst = "TOTP4ALL" + EffectiveAccountSettingsUserMfaMfaTotpConst = "TOTP" + EffectiveAccountSettingsUserMfaMfaTotp4allConst = "TOTP4ALL" ) // UnmarshalEffectiveAccountSettingsUserMfa unmarshals an instance of EffectiveAccountSettingsUserMfa from the specified map of raw messages. @@ -9844,7 +10560,7 @@ type GetAccountSettingsTemplateVersionOptions struct { func (*IamIdentityV1) NewGetAccountSettingsTemplateVersionOptions(templateID string, version string) *GetAccountSettingsTemplateVersionOptions { return &GetAccountSettingsTemplateVersionOptions{ TemplateID: core.StringPtr(templateID), - Version: core.StringPtr(version), + Version: core.StringPtr(version), } } @@ -9888,7 +10604,7 @@ type GetAllPreferencesOnScopeAccountOptions struct { func (*IamIdentityV1) NewGetAllPreferencesOnScopeAccountOptions(accountID string, iamID string) *GetAllPreferencesOnScopeAccountOptions { return &GetAllPreferencesOnScopeAccountOptions{ AccountID: core.StringPtr(accountID), - IamID: core.StringPtr(iamID), + IamID: core.StringPtr(iamID), } } @@ -10008,7 +10724,7 @@ type GetClaimRuleOptions struct { func (*IamIdentityV1) NewGetClaimRuleOptions(profileID string, ruleID string) *GetClaimRuleOptions { return &GetClaimRuleOptions{ ProfileID: core.StringPtr(profileID), - RuleID: core.StringPtr(ruleID), + RuleID: core.StringPtr(ruleID), } } @@ -10166,7 +10882,7 @@ type GetLinkOptions struct { func (*IamIdentityV1) NewGetLinkOptions(profileID string, linkID string) *GetLinkOptions { return &GetLinkOptions{ ProfileID: core.StringPtr(profileID), - LinkID: core.StringPtr(linkID), + LinkID: core.StringPtr(linkID), } } @@ -10242,7 +10958,7 @@ type GetMfaStatusOptions struct { func (*IamIdentityV1) NewGetMfaStatusOptions(accountID string, iamID string) *GetMfaStatusOptions { return &GetMfaStatusOptions{ AccountID: core.StringPtr(accountID), - IamID: core.StringPtr(iamID), + IamID: core.StringPtr(iamID), } } @@ -10285,9 +11001,9 @@ type GetPreferencesOnScopeAccountOptions struct { // NewGetPreferencesOnScopeAccountOptions : Instantiate GetPreferencesOnScopeAccountOptions func (*IamIdentityV1) NewGetPreferencesOnScopeAccountOptions(accountID string, iamID string, service string, preferenceID string) *GetPreferencesOnScopeAccountOptions { return &GetPreferencesOnScopeAccountOptions{ - AccountID: core.StringPtr(accountID), - IamID: core.StringPtr(iamID), - Service: core.StringPtr(service), + AccountID: core.StringPtr(accountID), + IamID: core.StringPtr(iamID), + Service: core.StringPtr(service), PreferenceID: core.StringPtr(preferenceID), } } @@ -10368,15 +11084,15 @@ type GetProfileIdentityOptions struct { // Constants associated with the GetProfileIdentityOptions.IdentityType property. // Type of the identity. const ( - GetProfileIdentityOptionsIdentityTypeCRNConst = "crn" + GetProfileIdentityOptionsIdentityTypeCRNConst = "crn" GetProfileIdentityOptionsIdentityTypeServiceidConst = "serviceid" - GetProfileIdentityOptionsIdentityTypeUserConst = "user" + GetProfileIdentityOptionsIdentityTypeUserConst = "user" ) // NewGetProfileIdentityOptions : Instantiate GetProfileIdentityOptions func (*IamIdentityV1) NewGetProfileIdentityOptions(profileID string, identityType string, identifierID string) *GetProfileIdentityOptions { return &GetProfileIdentityOptions{ - ProfileID: core.StringPtr(profileID), + ProfileID: core.StringPtr(profileID), IdentityType: core.StringPtr(identityType), IdentifierID: core.StringPtr(identifierID), } @@ -10463,7 +11179,7 @@ type GetProfileTemplateVersionOptions struct { func (*IamIdentityV1) NewGetProfileTemplateVersionOptions(templateID string, version string) *GetProfileTemplateVersionOptions { return &GetProfileTemplateVersionOptions{ TemplateID: core.StringPtr(templateID), - Version: core.StringPtr(version), + Version: core.StringPtr(version), } } @@ -10529,6 +11245,34 @@ func (options *GetReportOptions) SetHeaders(param map[string]string) *GetReportO return options } +// GetServiceIDGroupOptions : The GetServiceIDGroup options. +type GetServiceIDGroupOptions struct { + // Unique ID of the service ID group. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewGetServiceIDGroupOptions : Instantiate GetServiceIDGroupOptions +func (*IamIdentityV1) NewGetServiceIDGroupOptions(id string) *GetServiceIDGroupOptions { + return &GetServiceIDGroupOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *GetServiceIDGroupOptions) SetID(id string) *GetServiceIDGroupOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *GetServiceIDGroupOptions) SetHeaders(param map[string]string) *GetServiceIDGroupOptions { + options.Headers = param + return options +} + // GetServiceIDOptions : The GetServiceID options. type GetServiceIDOptions struct { // Unique ID of the service ID. @@ -10541,6 +11285,9 @@ type GetServiceIDOptions struct { // only request this when needed. IncludeActivity *bool `json:"include_activity,omitempty"` + // Defines if the service ID group ID is included in the response. + ShowGroupID *string `json:"show_group_id,omitempty"` + // Allows users to set headers on API requests. Headers map[string]string } @@ -10570,6 +11317,12 @@ func (_options *GetServiceIDOptions) SetIncludeActivity(includeActivity bool) *G return _options } +// SetShowGroupID : Allow user to set ShowGroupID +func (_options *GetServiceIDOptions) SetShowGroupID(showGroupID string) *GetServiceIDOptions { + _options.ShowGroupID = core.StringPtr(showGroupID) + return _options +} + // SetHeaders : Allow user to set Headers func (options *GetServiceIDOptions) SetHeaders(param map[string]string) *GetServiceIDOptions { options.Headers = param @@ -10658,72 +11411,71 @@ type IDBasedMfaEnrollment struct { // Constants associated with the IDBasedMfaEnrollment.TraitAccountDefault property. // Defines the MFA trait for the account. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - IDBasedMfaEnrollmentTraitAccountDefaultLevel1Const = "LEVEL1" - IDBasedMfaEnrollmentTraitAccountDefaultLevel2Const = "LEVEL2" - IDBasedMfaEnrollmentTraitAccountDefaultLevel3Const = "LEVEL3" - IDBasedMfaEnrollmentTraitAccountDefaultNoneConst = "NONE" + IDBasedMfaEnrollmentTraitAccountDefaultLevel1Const = "LEVEL1" + IDBasedMfaEnrollmentTraitAccountDefaultLevel2Const = "LEVEL2" + IDBasedMfaEnrollmentTraitAccountDefaultLevel3Const = "LEVEL3" + IDBasedMfaEnrollmentTraitAccountDefaultNoneConst = "NONE" IDBasedMfaEnrollmentTraitAccountDefaultNoneNoRopcConst = "NONE_NO_ROPC" - IDBasedMfaEnrollmentTraitAccountDefaultTotpConst = "TOTP" - IDBasedMfaEnrollmentTraitAccountDefaultTotp4allConst = "TOTP4ALL" + IDBasedMfaEnrollmentTraitAccountDefaultTotpConst = "TOTP" + IDBasedMfaEnrollmentTraitAccountDefaultTotp4allConst = "TOTP4ALL" ) // Constants associated with the IDBasedMfaEnrollment.TraitUserSpecific property. // Defines the MFA trait for the account. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - IDBasedMfaEnrollmentTraitUserSpecificLevel1Const = "LEVEL1" - IDBasedMfaEnrollmentTraitUserSpecificLevel2Const = "LEVEL2" - IDBasedMfaEnrollmentTraitUserSpecificLevel3Const = "LEVEL3" - IDBasedMfaEnrollmentTraitUserSpecificNoneConst = "NONE" + IDBasedMfaEnrollmentTraitUserSpecificLevel1Const = "LEVEL1" + IDBasedMfaEnrollmentTraitUserSpecificLevel2Const = "LEVEL2" + IDBasedMfaEnrollmentTraitUserSpecificLevel3Const = "LEVEL3" + IDBasedMfaEnrollmentTraitUserSpecificNoneConst = "NONE" IDBasedMfaEnrollmentTraitUserSpecificNoneNoRopcConst = "NONE_NO_ROPC" - IDBasedMfaEnrollmentTraitUserSpecificTotpConst = "TOTP" - IDBasedMfaEnrollmentTraitUserSpecificTotp4allConst = "TOTP4ALL" + IDBasedMfaEnrollmentTraitUserSpecificTotpConst = "TOTP" + IDBasedMfaEnrollmentTraitUserSpecificTotp4allConst = "TOTP4ALL" ) // Constants associated with the IDBasedMfaEnrollment.TraitEffective property. // Defines the MFA trait for the account. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - IDBasedMfaEnrollmentTraitEffectiveLevel1Const = "LEVEL1" - IDBasedMfaEnrollmentTraitEffectiveLevel2Const = "LEVEL2" - IDBasedMfaEnrollmentTraitEffectiveLevel3Const = "LEVEL3" - IDBasedMfaEnrollmentTraitEffectiveNoneConst = "NONE" + IDBasedMfaEnrollmentTraitEffectiveLevel1Const = "LEVEL1" + IDBasedMfaEnrollmentTraitEffectiveLevel2Const = "LEVEL2" + IDBasedMfaEnrollmentTraitEffectiveLevel3Const = "LEVEL3" + IDBasedMfaEnrollmentTraitEffectiveNoneConst = "NONE" IDBasedMfaEnrollmentTraitEffectiveNoneNoRopcConst = "NONE_NO_ROPC" - IDBasedMfaEnrollmentTraitEffectiveTotpConst = "TOTP" - IDBasedMfaEnrollmentTraitEffectiveTotp4allConst = "TOTP4ALL" + IDBasedMfaEnrollmentTraitEffectiveTotpConst = "TOTP" + IDBasedMfaEnrollmentTraitEffectiveTotp4allConst = "TOTP4ALL" ) // Constants associated with the IDBasedMfaEnrollment.ComplyState property. // Defines comply state for the account. Valid values: -// - NO - User does not comply in the given account. -// - ACCOUNT- User complies in the given account, but does not comply in at least one of the other account -// +// * NO - User does not comply in the given account. +// * ACCOUNT- User complies in the given account, but does not comply in at least one of the other account // memberships. -// - CROSS_ACCOUNT - User complies in the given account and across all other account memberships. +// * CROSS_ACCOUNT - User complies in the given account and across all other account memberships. const ( - IDBasedMfaEnrollmentComplyStateAccountConst = "ACCOUNT" + IDBasedMfaEnrollmentComplyStateAccountConst = "ACCOUNT" IDBasedMfaEnrollmentComplyStateCrossAccountConst = "CROSS_ACCOUNT" - IDBasedMfaEnrollmentComplyStateNoConst = "NO" + IDBasedMfaEnrollmentComplyStateNoConst = "NO" ) // UnmarshalIDBasedMfaEnrollment unmarshals an instance of IDBasedMfaEnrollment from the specified map of raw messages. @@ -10875,22 +11627,22 @@ type ListAccountSettingsAssignmentsOptions struct { // Constants associated with the ListAccountSettingsAssignmentsOptions.TargetType property. // Filter results by the assignment's target type. const ( - ListAccountSettingsAssignmentsOptionsTargetTypeAccountConst = "Account" + ListAccountSettingsAssignmentsOptionsTargetTypeAccountConst = "Account" ListAccountSettingsAssignmentsOptionsTargetTypeAccountgroupConst = "AccountGroup" ) // Constants associated with the ListAccountSettingsAssignmentsOptions.Sort property. // If specified, the items are sorted by the value of this property. const ( - ListAccountSettingsAssignmentsOptionsSortCreatedAtConst = "created_at" + ListAccountSettingsAssignmentsOptionsSortCreatedAtConst = "created_at" ListAccountSettingsAssignmentsOptionsSortLastModifiedAtConst = "last_modified_at" - ListAccountSettingsAssignmentsOptionsSortTemplateIDConst = "template_id" + ListAccountSettingsAssignmentsOptionsSortTemplateIDConst = "template_id" ) // Constants associated with the ListAccountSettingsAssignmentsOptions.Order property. // Sort order. const ( - ListAccountSettingsAssignmentsOptionsOrderAscConst = "asc" + ListAccountSettingsAssignmentsOptionsOrderAscConst = "asc" ListAccountSettingsAssignmentsOptionsOrderDescConst = "desc" ) @@ -10992,15 +11744,15 @@ type ListAccountSettingsTemplatesOptions struct { // Constants associated with the ListAccountSettingsTemplatesOptions.Sort property. // Optional sort property. If specified, the returned templated are sorted according to this property. const ( - ListAccountSettingsTemplatesOptionsSortCreatedAtConst = "created_at" + ListAccountSettingsTemplatesOptionsSortCreatedAtConst = "created_at" ListAccountSettingsTemplatesOptionsSortLastModifiedAtConst = "last_modified_at" - ListAccountSettingsTemplatesOptionsSortNameConst = "name" + ListAccountSettingsTemplatesOptionsSortNameConst = "name" ) // Constants associated with the ListAccountSettingsTemplatesOptions.Order property. // Optional sort order. const ( - ListAccountSettingsTemplatesOptionsOrderAscConst = "asc" + ListAccountSettingsTemplatesOptionsOrderAscConst = "asc" ListAccountSettingsTemplatesOptionsOrderDescConst = "desc" ) @@ -11088,6 +11840,11 @@ type ListAPIKeysOptions struct { // [Filtering list results](#filter-list-results) section. Filter *string `json:"filter,omitempty"` + // Optional group ID of the service ID(s) to which the searched API keys are bound. If this parameter is not provided + // the default group is applied on service ID API keys. For user API keys this parameter is ignored as they always + // belong to the default group. + GroupID *string `json:"group_id,omitempty"` + // Allows users to set headers on API requests. Headers map[string]string } @@ -11096,20 +11853,20 @@ type ListAPIKeysOptions struct { // Optional parameter to define the scope of the queried API keys. Can be 'entity' (default) or 'account'. const ( ListAPIKeysOptionsScopeAccountConst = "account" - ListAPIKeysOptionsScopeEntityConst = "entity" + ListAPIKeysOptionsScopeEntityConst = "entity" ) // Constants associated with the ListAPIKeysOptions.Type property. // Optional parameter to filter the type of the queried API keys. Can be 'user' or 'serviceid'. const ( ListAPIKeysOptionsTypeServiceidConst = "serviceid" - ListAPIKeysOptionsTypeUserConst = "user" + ListAPIKeysOptionsTypeUserConst = "user" ) // Constants associated with the ListAPIKeysOptions.Order property. // Optional sort order, valid values are asc and desc. Default: asc. const ( - ListAPIKeysOptionsOrderAscConst = "asc" + ListAPIKeysOptionsOrderAscConst = "asc" ListAPIKeysOptionsOrderDescConst = "desc" ) @@ -11178,6 +11935,12 @@ func (_options *ListAPIKeysOptions) SetFilter(filter string) *ListAPIKeysOptions return _options } +// SetGroupID : Allow user to set GroupID +func (_options *ListAPIKeysOptions) SetGroupID(groupID string) *ListAPIKeysOptions { + _options.GroupID = core.StringPtr(groupID) + return _options +} + // SetHeaders : Allow user to set Headers func (options *ListAPIKeysOptions) SetHeaders(param map[string]string) *ListAPIKeysOptions { options.Headers = param @@ -11267,15 +12030,15 @@ type ListProfileTemplatesOptions struct { // Constants associated with the ListProfileTemplatesOptions.Sort property. // Optional sort property. If specified, the returned templates are sorted according to this property. const ( - ListProfileTemplatesOptionsSortCreatedAtConst = "created_at" + ListProfileTemplatesOptionsSortCreatedAtConst = "created_at" ListProfileTemplatesOptionsSortLastModifiedAtConst = "last_modified_at" - ListProfileTemplatesOptionsSortNameConst = "name" + ListProfileTemplatesOptionsSortNameConst = "name" ) // Constants associated with the ListProfileTemplatesOptions.Order property. // Optional sort order. const ( - ListProfileTemplatesOptionsOrderAscConst = "asc" + ListProfileTemplatesOptionsOrderAscConst = "asc" ListProfileTemplatesOptionsOrderDescConst = "desc" ) @@ -11361,7 +12124,7 @@ type ListProfilesOptions struct { // Constants associated with the ListProfilesOptions.Order property. // Optional sort order, valid values are asc and desc. Default: asc. const ( - ListProfilesOptionsOrderAscConst = "asc" + ListProfilesOptionsOrderAscConst = "asc" ListProfilesOptionsOrderDescConst = "desc" ) @@ -11426,11 +12189,40 @@ func (options *ListProfilesOptions) SetHeaders(param map[string]string) *ListPro return options } +// ListServiceIDGroupOptions : The ListServiceIDGroup options. +type ListServiceIDGroupOptions struct { + // Account ID of the service ID groups to query. + AccountID *string `json:"account_id,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewListServiceIDGroupOptions : Instantiate ListServiceIDGroupOptions +func (*IamIdentityV1) NewListServiceIDGroupOptions() *ListServiceIDGroupOptions { + return &ListServiceIDGroupOptions{} +} + +// SetAccountID : Allow user to set AccountID +func (_options *ListServiceIDGroupOptions) SetAccountID(accountID string) *ListServiceIDGroupOptions { + _options.AccountID = core.StringPtr(accountID) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *ListServiceIDGroupOptions) SetHeaders(param map[string]string) *ListServiceIDGroupOptions { + options.Headers = param + return options +} + // ListServiceIdsOptions : The ListServiceIds options. type ListServiceIdsOptions struct { // Account ID of the service ID(s) to query. This parameter is required (unless using a pagetoken). AccountID *string `json:"account_id,omitempty"` + // Group ID of the service ID(s) to query. If this parameter is not provided the default group is applied. + GroupID *string `json:"group_id,omitempty"` + // Name of the service ID(s) to query. Optional.20 items per page. Valid range is 1 to 100. Name *string `json:"name,omitempty"` @@ -11454,6 +12246,9 @@ type ListServiceIdsOptions struct { // [Filtering list results](#filter-list-results) section. Filter *string `json:"filter,omitempty"` + // Defines if the service ID group ID is included in the response. + ShowGroupID *string `json:"show_group_id,omitempty"` + // Allows users to set headers on API requests. Headers map[string]string } @@ -11461,7 +12256,7 @@ type ListServiceIdsOptions struct { // Constants associated with the ListServiceIdsOptions.Order property. // Optional sort order, valid values are asc and desc. Default: asc. const ( - ListServiceIdsOptionsOrderAscConst = "asc" + ListServiceIdsOptionsOrderAscConst = "asc" ListServiceIdsOptionsOrderDescConst = "desc" ) @@ -11476,6 +12271,12 @@ func (_options *ListServiceIdsOptions) SetAccountID(accountID string) *ListServi return _options } +// SetGroupID : Allow user to set GroupID +func (_options *ListServiceIdsOptions) SetGroupID(groupID string) *ListServiceIdsOptions { + _options.GroupID = core.StringPtr(groupID) + return _options +} + // SetName : Allow user to set Name func (_options *ListServiceIdsOptions) SetName(name string) *ListServiceIdsOptions { _options.Name = core.StringPtr(name) @@ -11518,6 +12319,12 @@ func (_options *ListServiceIdsOptions) SetFilter(filter string) *ListServiceIdsO return _options } +// SetShowGroupID : Allow user to set ShowGroupID +func (_options *ListServiceIdsOptions) SetShowGroupID(showGroupID string) *ListServiceIdsOptions { + _options.ShowGroupID = core.StringPtr(showGroupID) + return _options +} + // SetHeaders : Allow user to set Headers func (options *ListServiceIdsOptions) SetHeaders(param map[string]string) *ListServiceIdsOptions { options.Headers = param @@ -11563,22 +12370,22 @@ type ListTrustedProfileAssignmentsOptions struct { // Constants associated with the ListTrustedProfileAssignmentsOptions.TargetType property. // Filter results by the assignment's target type. const ( - ListTrustedProfileAssignmentsOptionsTargetTypeAccountConst = "Account" + ListTrustedProfileAssignmentsOptionsTargetTypeAccountConst = "Account" ListTrustedProfileAssignmentsOptionsTargetTypeAccountgroupConst = "AccountGroup" ) // Constants associated with the ListTrustedProfileAssignmentsOptions.Sort property. // If specified, the items are sorted by the value of this property. const ( - ListTrustedProfileAssignmentsOptionsSortCreatedAtConst = "created_at" + ListTrustedProfileAssignmentsOptionsSortCreatedAtConst = "created_at" ListTrustedProfileAssignmentsOptionsSortLastModifiedAtConst = "last_modified_at" - ListTrustedProfileAssignmentsOptionsSortTemplateIDConst = "template_id" + ListTrustedProfileAssignmentsOptionsSortTemplateIDConst = "template_id" ) // Constants associated with the ListTrustedProfileAssignmentsOptions.Order property. // Sort order. const ( - ListTrustedProfileAssignmentsOptionsOrderAscConst = "asc" + ListTrustedProfileAssignmentsOptionsOrderAscConst = "asc" ListTrustedProfileAssignmentsOptionsOrderDescConst = "desc" ) @@ -11680,15 +12487,15 @@ type ListVersionsOfAccountSettingsTemplateOptions struct { // Constants associated with the ListVersionsOfAccountSettingsTemplateOptions.Sort property. // Optional sort property. If specified, the returned templated are sorted according to this property. const ( - ListVersionsOfAccountSettingsTemplateOptionsSortCreatedAtConst = "created_at" + ListVersionsOfAccountSettingsTemplateOptionsSortCreatedAtConst = "created_at" ListVersionsOfAccountSettingsTemplateOptionsSortLastModifiedAtConst = "last_modified_at" - ListVersionsOfAccountSettingsTemplateOptionsSortNameConst = "name" + ListVersionsOfAccountSettingsTemplateOptionsSortNameConst = "name" ) // Constants associated with the ListVersionsOfAccountSettingsTemplateOptions.Order property. // Optional sort order. const ( - ListVersionsOfAccountSettingsTemplateOptionsOrderAscConst = "asc" + ListVersionsOfAccountSettingsTemplateOptionsOrderAscConst = "asc" ListVersionsOfAccountSettingsTemplateOptionsOrderDescConst = "desc" ) @@ -11768,15 +12575,15 @@ type ListVersionsOfProfileTemplateOptions struct { // Constants associated with the ListVersionsOfProfileTemplateOptions.Sort property. // Optional sort property. If specified, the returned templated are sorted according to this property. const ( - ListVersionsOfProfileTemplateOptionsSortCreatedAtConst = "created_at" + ListVersionsOfProfileTemplateOptionsSortCreatedAtConst = "created_at" ListVersionsOfProfileTemplateOptionsSortLastModifiedAtConst = "last_modified_at" - ListVersionsOfProfileTemplateOptionsSortNameConst = "name" + ListVersionsOfProfileTemplateOptionsSortNameConst = "name" ) // Constants associated with the ListVersionsOfProfileTemplateOptions.Order property. // Optional sort order. const ( - ListVersionsOfProfileTemplateOptionsOrderAscConst = "asc" + ListVersionsOfProfileTemplateOptionsOrderAscConst = "asc" ListVersionsOfProfileTemplateOptionsOrderDescConst = "desc" ) @@ -11955,7 +12762,7 @@ type PolicyTemplateReference struct { // NewPolicyTemplateReference : Instantiate PolicyTemplateReference (Generic Model Constructor) func (*IamIdentityV1) NewPolicyTemplateReference(id string, version string) (_model *PolicyTemplateReference, err error) { _model = &PolicyTemplateReference{ - ID: core.StringPtr(id), + ID: core.StringPtr(id), Version: core.StringPtr(version), } err = core.ValidateStruct(_model, "required parameters") @@ -12089,9 +12896,9 @@ type ProfileClaimRuleConditions struct { // NewProfileClaimRuleConditions : Instantiate ProfileClaimRuleConditions (Generic Model Constructor) func (*IamIdentityV1) NewProfileClaimRuleConditions(claim string, operator string, value string) (_model *ProfileClaimRuleConditions, err error) { _model = &ProfileClaimRuleConditions{ - Claim: core.StringPtr(claim), + Claim: core.StringPtr(claim), Operator: core.StringPtr(operator), - Value: core.StringPtr(value), + Value: core.StringPtr(value), } err = core.ValidateStruct(_model, "required parameters") if err != nil { @@ -12196,16 +13003,16 @@ type ProfileIdentityRequest struct { // Constants associated with the ProfileIdentityRequest.Type property. // Type of the identity. const ( - ProfileIdentityRequestTypeCRNConst = "crn" + ProfileIdentityRequestTypeCRNConst = "crn" ProfileIdentityRequestTypeServiceidConst = "serviceid" - ProfileIdentityRequestTypeUserConst = "user" + ProfileIdentityRequestTypeUserConst = "user" ) // NewProfileIdentityRequest : Instantiate ProfileIdentityRequest (Generic Model Constructor) func (*IamIdentityV1) NewProfileIdentityRequest(identifier string, typeVar string) (_model *ProfileIdentityRequest, err error) { _model = &ProfileIdentityRequest{ Identifier: core.StringPtr(identifier), - Type: core.StringPtr(typeVar), + Type: core.StringPtr(typeVar), } err = core.ValidateStruct(_model, "required parameters") if err != nil { @@ -12266,9 +13073,9 @@ type ProfileIdentityResponse struct { // Constants associated with the ProfileIdentityResponse.Type property. // Type of the identity. const ( - ProfileIdentityResponseTypeCRNConst = "crn" + ProfileIdentityResponseTypeCRNConst = "crn" ProfileIdentityResponseTypeServiceidConst = "serviceid" - ProfileIdentityResponseTypeUserConst = "user" + ProfileIdentityResponseTypeUserConst = "user" ) // UnmarshalProfileIdentityResponse unmarshals an instance of ProfileIdentityResponse from the specified map of raw messages. @@ -12320,7 +13127,7 @@ type ProfileLink struct { // Optional name of the Link. Name *string `json:"name,omitempty"` - // The compute resource type. Valid values are VSI, IKS_SA, ROKS_SA. + // The compute resource type. Valid values are VSI, BMS, IKS_SA, ROKS_SA, CE. CrType *string `json:"cr_type" validate:"required"` Link *ProfileLinkLink `json:"link" validate:"required"` @@ -12378,6 +13185,12 @@ type ProfileLinkLink struct { // Name of the compute resource, only required if cr_type is IKS_SA or ROKS_SA. Name *string `json:"name,omitempty"` + + // Component type of the compute resource, only required if cr_type is CE. + ComponentType *string `json:"component_type,omitempty"` + + // Component name of the compute resource, only required if cr_type is CE. + ComponentName *string `json:"component_name,omitempty"` } // UnmarshalProfileLinkLink unmarshals an instance of ProfileLinkLink from the specified map of raw messages. @@ -12398,6 +13211,16 @@ func UnmarshalProfileLinkLink(m map[string]json.RawMessage, result interface{}) err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "component_type", &obj.ComponentType) + if err != nil { + err = core.SDKErrorf(err, "", "component_type-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "component_name", &obj.ComponentName) + if err != nil { + err = core.SDKErrorf(err, "", "component_name-error", common.GetComponentInfo()) + return + } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } @@ -12707,6 +13530,9 @@ type ServiceID struct { // ID of the account the service ID belongs to. AccountID *string `json:"account_id" validate:"required"` + // ID of the group to which the service ID belongs to. Only set if requested via parameter `show_group_id`. + GroupID *string `json:"group_id,omitempty"` + // Name of the Service Id. The name is not checked for uniqueness. Therefore multiple names with the same value can // exist. Access is done via the UUID of the Service Id. Name *string `json:"name" validate:"required"` @@ -12775,6 +13601,11 @@ func UnmarshalServiceID(m map[string]json.RawMessage, result interface{}) (err e err = core.SDKErrorf(err, "", "account_id-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "group_id", &obj.GroupID) + if err != nil { + err = core.SDKErrorf(err, "", "group_id-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) @@ -12809,6 +13640,107 @@ func UnmarshalServiceID(m map[string]json.RawMessage, result interface{}) (err e return } +// ServiceIDGroup : ServiceIDGroup struct +type ServiceIDGroup struct { + // ID of the the service ID group. + ID *string `json:"id" validate:"required"` + + // Version of the service ID group details object. You need to specify this value when updating the service ID group to + // avoid stale updates. + EntityTag *string `json:"entity_tag,omitempty"` + + // ID of the account the service ID group belongs to. + AccountID *string `json:"account_id" validate:"required"` + + // Cloud Resource Name of the item. + CRN *string `json:"crn" validate:"required"` + + // Name of the service ID group. Unique in the account. + Name *string `json:"name" validate:"required"` + + // Description of the service ID group. + Description *string `json:"description,omitempty"` + + // Timestamp of when the service ID group was created. + CreatedAt *string `json:"created_at,omitempty"` + + // IAM ID of the user or service which created the Service Id group. + CreatedBy *string `json:"created_by" validate:"required"` + + // Timestamp of when the service ID group was modified. + ModifiedAt *string `json:"modified_at,omitempty"` +} + +// UnmarshalServiceIDGroup unmarshals an instance of ServiceIDGroup from the specified map of raw messages. +func UnmarshalServiceIDGroup(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ServiceIDGroup) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "entity_tag", &obj.EntityTag) + if err != nil { + err = core.SDKErrorf(err, "", "entity_tag-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "account_id", &obj.AccountID) + if err != nil { + err = core.SDKErrorf(err, "", "account_id-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "description", &obj.Description) + if err != nil { + err = core.SDKErrorf(err, "", "description-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) + if err != nil { + err = core.SDKErrorf(err, "", "created_at-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "created_by", &obj.CreatedBy) + if err != nil { + err = core.SDKErrorf(err, "", "created_by-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "modified_at", &obj.ModifiedAt) + if err != nil { + err = core.SDKErrorf(err, "", "modified_at-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ServiceIDGroupList : ServiceIDGroupList struct +type ServiceIDGroupList struct { + // List of Service ID groups based on the query parameter. + ServiceidGroups []ServiceIDGroup `json:"serviceid_groups" validate:"required"` +} + +// UnmarshalServiceIDGroupList unmarshals an instance of ServiceIDGroupList from the specified map of raw messages. +func UnmarshalServiceIDGroupList(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ServiceIDGroupList) + err = core.UnmarshalModel(m, "serviceid_groups", &obj.ServiceidGroups, UnmarshalServiceIDGroup) + if err != nil { + err = core.SDKErrorf(err, "", "serviceid_groups-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // ServiceIDList : Response body format for the list service ID V1 REST request. type ServiceIDList struct { // Context with key properties for problem determination. @@ -12898,7 +13830,7 @@ type SetProfileIdentitiesOptions struct { func (*IamIdentityV1) NewSetProfileIdentitiesOptions(profileID string, ifMatch string) *SetProfileIdentitiesOptions { return &SetProfileIdentitiesOptions{ ProfileID: core.StringPtr(profileID), - IfMatch: core.StringPtr(ifMatch), + IfMatch: core.StringPtr(ifMatch), } } @@ -12957,26 +13889,26 @@ type SetProfileIdentityOptions struct { // Constants associated with the SetProfileIdentityOptions.IdentityType property. // Type of the identity. const ( - SetProfileIdentityOptionsIdentityTypeCRNConst = "crn" + SetProfileIdentityOptionsIdentityTypeCRNConst = "crn" SetProfileIdentityOptionsIdentityTypeServiceidConst = "serviceid" - SetProfileIdentityOptionsIdentityTypeUserConst = "user" + SetProfileIdentityOptionsIdentityTypeUserConst = "user" ) // Constants associated with the SetProfileIdentityOptions.Type property. // Type of the identity. const ( - SetProfileIdentityOptionsTypeCRNConst = "crn" + SetProfileIdentityOptionsTypeCRNConst = "crn" SetProfileIdentityOptionsTypeServiceidConst = "serviceid" - SetProfileIdentityOptionsTypeUserConst = "user" + SetProfileIdentityOptionsTypeUserConst = "user" ) // NewSetProfileIdentityOptions : Instantiate SetProfileIdentityOptions func (*IamIdentityV1) NewSetProfileIdentityOptions(profileID string, identityType string, identifier string, typeVar string) *SetProfileIdentityOptions { return &SetProfileIdentityOptions{ - ProfileID: core.StringPtr(profileID), + ProfileID: core.StringPtr(profileID), IdentityType: core.StringPtr(identityType), - Identifier: core.StringPtr(identifier), - Type: core.StringPtr(typeVar), + Identifier: core.StringPtr(identifier), + Type: core.StringPtr(typeVar), } } @@ -13300,7 +14232,7 @@ type TemplateAssignmentResponseResource struct { AccountSettings *TemplateAssignmentResponseResourceDetail `json:"account_settings,omitempty"` // Policy resource(s) included only for trusted profile assignments with policy references. - PolicyTemplateRefs []TemplateAssignmentResponseResourceDetail `json:"policy_template_refs,omitempty"` + PolicyTemplateReferences []TemplateAssignmentResponseResourceDetail `json:"policy_template_references,omitempty"` } // UnmarshalTemplateAssignmentResponseResource unmarshals an instance of TemplateAssignmentResponseResource from the specified map of raw messages. @@ -13321,9 +14253,9 @@ func UnmarshalTemplateAssignmentResponseResource(m map[string]json.RawMessage, r err = core.SDKErrorf(err, "", "account_settings-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "policy_template_refs", &obj.PolicyTemplateRefs, UnmarshalTemplateAssignmentResponseResourceDetail) + err = core.UnmarshalModel(m, "policy_template_references", &obj.PolicyTemplateReferences, UnmarshalTemplateAssignmentResponseResourceDetail) if err != nil { - err = core.SDKErrorf(err, "", "policy_template_refs-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "policy_template_references-error", common.GetComponentInfo()) return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) @@ -13383,11 +14315,32 @@ func UnmarshalTemplateAssignmentResponseResourceDetail(m map[string]json.RawMess // TemplateProfileComponentRequest : Input body parameters for the TemplateProfileComponent. type TemplateProfileComponentRequest struct { // Name of the Profile. + // + // You can use replacement variables in the profile name to adjust the name per account. + // + // The following variables are supported: + // + // - `${template_id}` will be replaced by a unique identifier representing the trusted profile template + // + // - `${template_name}` will be replaced by the current name of the trusted profile template + // + // - `${template_version}` will be replaced by the current version of the trusted profile template + // + // - `${account_id}` will be replaced by the account identifier to which this trusted profile template is assigned to + // + // - `${account_name}` will be replaced by the account name to which this trusted profile template is assigned to + // + // Changes to e.g. the name of the account will NOT cause an update of the trusted profile name. The profile name is + // processed during account assignment and any template version upgrade, i.e. during that operation, the updated + // account name would be used. Name *string `json:"name" validate:"required"` // Description of the Profile. Description *string `json:"description,omitempty"` + // Email of the trusted profile. + Email *string `json:"email,omitempty"` + // Rules for the Profile. Rules []TrustedProfileTemplateClaimRule `json:"rules,omitempty"` @@ -13420,6 +14373,11 @@ func UnmarshalTemplateProfileComponentRequest(m map[string]json.RawMessage, resu err = core.SDKErrorf(err, "", "description-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "email", &obj.Email) + if err != nil { + err = core.SDKErrorf(err, "", "email-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "rules", &obj.Rules, UnmarshalTrustedProfileTemplateClaimRule) if err != nil { err = core.SDKErrorf(err, "", "rules-error", common.GetComponentInfo()) @@ -13445,6 +14403,9 @@ type TemplateProfileComponentResponse struct { // Rules for the Profile. Rules []TrustedProfileTemplateClaimRule `json:"rules,omitempty"` + // Email of the trusted profile. + Email *string `json:"email,omitempty"` + // Identities for the Profile. Identities []ProfileIdentityResponse `json:"identities,omitempty"` } @@ -13467,6 +14428,11 @@ func UnmarshalTemplateProfileComponentResponse(m map[string]json.RawMessage, res err = core.SDKErrorf(err, "", "rules-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "email", &obj.Email) + if err != nil { + err = core.SDKErrorf(err, "", "email-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "identities", &obj.Identities, UnmarshalProfileIdentityResponse) if err != nil { err = core.SDKErrorf(err, "", "identities-error", common.GetComponentInfo()) @@ -13500,6 +14466,10 @@ type TrustedProfile struct { // provided during a create of a trusted profile. Description *string `json:"description,omitempty"` + // The optional email of the trusted profile. The 'email' property is only available if an email was provided during a + // create of a trusted profile. + Email *string `json:"email,omitempty"` + // If set contains a date time string of the creation date in ISO format. CreatedAt *strfmt.DateTime `json:"created_at,omitempty"` @@ -13565,6 +14535,11 @@ func UnmarshalTrustedProfile(m map[string]json.RawMessage, result interface{}) ( err = core.SDKErrorf(err, "", "description-error", common.GetComponentInfo()) return } + err = core.UnmarshalPrimitive(m, "email", &obj.Email) + if err != nil { + err = core.SDKErrorf(err, "", "email-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) if err != nil { err = core.SDKErrorf(err, "", "created_at-error", common.GetComponentInfo()) @@ -13647,7 +14622,7 @@ const ( // NewTrustedProfileTemplateClaimRule : Instantiate TrustedProfileTemplateClaimRule (Generic Model Constructor) func (*IamIdentityV1) NewTrustedProfileTemplateClaimRule(typeVar string, conditions []ProfileClaimRuleConditions) (_model *TrustedProfileTemplateClaimRule, err error) { _model = &TrustedProfileTemplateClaimRule{ - Type: core.StringPtr(typeVar), + Type: core.StringPtr(typeVar), Conditions: conditions, } err = core.ValidateStruct(_model, "required parameters") @@ -14038,8 +15013,8 @@ type UpdateAccountSettingsAssignmentOptions struct { // NewUpdateAccountSettingsAssignmentOptions : Instantiate UpdateAccountSettingsAssignmentOptions func (*IamIdentityV1) NewUpdateAccountSettingsAssignmentOptions(assignmentID string, ifMatch string, templateVersion int64) *UpdateAccountSettingsAssignmentOptions { return &UpdateAccountSettingsAssignmentOptions{ - AssignmentID: core.StringPtr(assignmentID), - IfMatch: core.StringPtr(ifMatch), + AssignmentID: core.StringPtr(assignmentID), + IfMatch: core.StringPtr(ifMatch), TemplateVersion: core.Int64Ptr(templateVersion), } } @@ -14139,53 +15114,51 @@ type UpdateAccountSettingsOptions struct { // Constants associated with the UpdateAccountSettingsOptions.RestrictCreateServiceID property. // Defines whether or not creating a service ID is access controlled. Valid values: -// - RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service -// +// * RESTRICTED - only users assigned the 'Service ID creator' role on the IAM Identity Service can create service // IDs, including the account owner -// - NOT_RESTRICTED - all members of an account can create service IDs -// - NOT_SET - to 'unset' a previous set value. +// * NOT_RESTRICTED - all members of an account can create service IDs +// * NOT_SET - to 'unset' a previous set value. const ( UpdateAccountSettingsOptionsRestrictCreateServiceIDNotRestrictedConst = "NOT_RESTRICTED" - UpdateAccountSettingsOptionsRestrictCreateServiceIDNotSetConst = "NOT_SET" - UpdateAccountSettingsOptionsRestrictCreateServiceIDRestrictedConst = "RESTRICTED" + UpdateAccountSettingsOptionsRestrictCreateServiceIDNotSetConst = "NOT_SET" + UpdateAccountSettingsOptionsRestrictCreateServiceIDRestrictedConst = "RESTRICTED" ) // Constants associated with the UpdateAccountSettingsOptions.RestrictCreatePlatformApikey property. // Defines whether or not creating platform API keys is access controlled. Valid values: -// - RESTRICTED - only users assigned the 'User API key creator' role on the IAM Identity Service can create API keys, -// +// * RESTRICTED - only users assigned the 'User API key creator' role on the IAM Identity Service can create API keys, // including the account owner -// - NOT_RESTRICTED - all members of an account can create platform API keys -// - NOT_SET - to 'unset' a previous set value. +// * NOT_RESTRICTED - all members of an account can create platform API keys +// * NOT_SET - to 'unset' a previous set value. const ( UpdateAccountSettingsOptionsRestrictCreatePlatformApikeyNotRestrictedConst = "NOT_RESTRICTED" - UpdateAccountSettingsOptionsRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" - UpdateAccountSettingsOptionsRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" + UpdateAccountSettingsOptionsRestrictCreatePlatformApikeyNotSetConst = "NOT_SET" + UpdateAccountSettingsOptionsRestrictCreatePlatformApikeyRestrictedConst = "RESTRICTED" ) // Constants associated with the UpdateAccountSettingsOptions.Mfa property. // Defines the MFA trait for the account. Valid values: -// - NONE - No MFA trait set -// - NONE_NO_ROPC- No MFA, disable CLI logins with only a password -// - TOTP - For all non-federated IBMId users -// - TOTP4ALL - For all users -// - LEVEL1 - Email-based MFA for all users -// - LEVEL2 - TOTP-based MFA for all users -// - LEVEL3 - U2F MFA for all users. +// * NONE - No MFA trait set +// * NONE_NO_ROPC- No MFA, disable CLI logins with only a password +// * TOTP - For all non-federated IBMId users +// * TOTP4ALL - For all users +// * LEVEL1 - Email-based MFA for all users +// * LEVEL2 - TOTP-based MFA for all users +// * LEVEL3 - U2F MFA for all users. const ( - UpdateAccountSettingsOptionsMfaLevel1Const = "LEVEL1" - UpdateAccountSettingsOptionsMfaLevel2Const = "LEVEL2" - UpdateAccountSettingsOptionsMfaLevel3Const = "LEVEL3" - UpdateAccountSettingsOptionsMfaNoneConst = "NONE" + UpdateAccountSettingsOptionsMfaLevel1Const = "LEVEL1" + UpdateAccountSettingsOptionsMfaLevel2Const = "LEVEL2" + UpdateAccountSettingsOptionsMfaLevel3Const = "LEVEL3" + UpdateAccountSettingsOptionsMfaNoneConst = "NONE" UpdateAccountSettingsOptionsMfaNoneNoRopcConst = "NONE_NO_ROPC" - UpdateAccountSettingsOptionsMfaTotpConst = "TOTP" - UpdateAccountSettingsOptionsMfaTotp4allConst = "TOTP4ALL" + UpdateAccountSettingsOptionsMfaTotpConst = "TOTP" + UpdateAccountSettingsOptionsMfaTotp4allConst = "TOTP4ALL" ) // NewUpdateAccountSettingsOptions : Instantiate UpdateAccountSettingsOptions func (*IamIdentityV1) NewUpdateAccountSettingsOptions(ifMatch string, accountID string) *UpdateAccountSettingsOptions { return &UpdateAccountSettingsOptions{ - IfMatch: core.StringPtr(ifMatch), + IfMatch: core.StringPtr(ifMatch), AccountID: core.StringPtr(accountID), } } @@ -14299,9 +15272,9 @@ type UpdateAccountSettingsTemplateVersionOptions struct { // NewUpdateAccountSettingsTemplateVersionOptions : Instantiate UpdateAccountSettingsTemplateVersionOptions func (*IamIdentityV1) NewUpdateAccountSettingsTemplateVersionOptions(ifMatch string, templateID string, version string) *UpdateAccountSettingsTemplateVersionOptions { return &UpdateAccountSettingsTemplateVersionOptions{ - IfMatch: core.StringPtr(ifMatch), + IfMatch: core.StringPtr(ifMatch), TemplateID: core.StringPtr(templateID), - Version: core.StringPtr(version), + Version: core.StringPtr(version), } } @@ -14386,7 +15359,7 @@ type UpdateAPIKeyOptions struct { // NewUpdateAPIKeyOptions : Instantiate UpdateAPIKeyOptions func (*IamIdentityV1) NewUpdateAPIKeyOptions(id string, ifMatch string) *UpdateAPIKeyOptions { return &UpdateAPIKeyOptions{ - ID: core.StringPtr(id), + ID: core.StringPtr(id), IfMatch: core.StringPtr(ifMatch), } } @@ -14476,10 +15449,10 @@ type UpdateClaimRuleOptions struct { // NewUpdateClaimRuleOptions : Instantiate UpdateClaimRuleOptions func (*IamIdentityV1) NewUpdateClaimRuleOptions(profileID string, ruleID string, ifMatch string, typeVar string, conditions []ProfileClaimRuleConditions) *UpdateClaimRuleOptions { return &UpdateClaimRuleOptions{ - ProfileID: core.StringPtr(profileID), - RuleID: core.StringPtr(ruleID), - IfMatch: core.StringPtr(ifMatch), - Type: core.StringPtr(typeVar), + ProfileID: core.StringPtr(profileID), + RuleID: core.StringPtr(ruleID), + IfMatch: core.StringPtr(ifMatch), + Type: core.StringPtr(typeVar), Conditions: conditions, } } @@ -14579,11 +15552,11 @@ type UpdatePreferenceOnScopeAccountOptions struct { // NewUpdatePreferenceOnScopeAccountOptions : Instantiate UpdatePreferenceOnScopeAccountOptions func (*IamIdentityV1) NewUpdatePreferenceOnScopeAccountOptions(accountID string, iamID string, service string, preferenceID string, valueString string) *UpdatePreferenceOnScopeAccountOptions { return &UpdatePreferenceOnScopeAccountOptions{ - AccountID: core.StringPtr(accountID), - IamID: core.StringPtr(iamID), - Service: core.StringPtr(service), + AccountID: core.StringPtr(accountID), + IamID: core.StringPtr(iamID), + Service: core.StringPtr(service), PreferenceID: core.StringPtr(preferenceID), - ValueString: core.StringPtr(valueString), + ValueString: core.StringPtr(valueString), } } @@ -14647,6 +15620,10 @@ type UpdateProfileOptions struct { // the trusted profile. If a non empty value is provided the trusted profile will be updated. Description *string `json:"description,omitempty"` + // The email of the profile to update. If specified an empty email will clear the email of the profile. If an non empty + // value is provided the trusted profile will be updated. + Email *string `json:"email,omitempty"` + // Allows users to set headers on API requests. Headers map[string]string } @@ -14655,7 +15632,7 @@ type UpdateProfileOptions struct { func (*IamIdentityV1) NewUpdateProfileOptions(profileID string, ifMatch string) *UpdateProfileOptions { return &UpdateProfileOptions{ ProfileID: core.StringPtr(profileID), - IfMatch: core.StringPtr(ifMatch), + IfMatch: core.StringPtr(ifMatch), } } @@ -14683,6 +15660,12 @@ func (_options *UpdateProfileOptions) SetDescription(description string) *Update return _options } +// SetEmail : Allow user to set Email +func (_options *UpdateProfileOptions) SetEmail(email string) *UpdateProfileOptions { + _options.Email = core.StringPtr(email) + return _options +} + // SetHeaders : Allow user to set Headers func (options *UpdateProfileOptions) SetHeaders(param map[string]string) *UpdateProfileOptions { options.Headers = param @@ -14728,9 +15711,9 @@ type UpdateProfileTemplateVersionOptions struct { // NewUpdateProfileTemplateVersionOptions : Instantiate UpdateProfileTemplateVersionOptions func (*IamIdentityV1) NewUpdateProfileTemplateVersionOptions(ifMatch string, templateID string, version string) *UpdateProfileTemplateVersionOptions { return &UpdateProfileTemplateVersionOptions{ - IfMatch: core.StringPtr(ifMatch), + IfMatch: core.StringPtr(ifMatch), TemplateID: core.StringPtr(templateID), - Version: core.StringPtr(version), + Version: core.StringPtr(version), } } @@ -14794,6 +15777,65 @@ func (options *UpdateProfileTemplateVersionOptions) SetHeaders(param map[string] return options } +// UpdateServiceIDGroupOptions : The UpdateServiceIDGroup options. +type UpdateServiceIDGroupOptions struct { + // Unique ID of the service ID group to be updated. + ID *string `json:"id" validate:"required,ne="` + + // Version of the service ID gorup to be updated. Specify the version that you retrieved when reading service ID group. + // This value helps identifying parallel usage of this API. Pass * to indicate to update any version available. This + // might result in stale updates. + IfMatch *string `json:"If-Match" validate:"required"` + + // Name of the service ID group. Unique in the account. + Name *string `json:"name" validate:"required"` + + // Description of the service ID group. + Description *string `json:"description,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewUpdateServiceIDGroupOptions : Instantiate UpdateServiceIDGroupOptions +func (*IamIdentityV1) NewUpdateServiceIDGroupOptions(id string, ifMatch string, name string) *UpdateServiceIDGroupOptions { + return &UpdateServiceIDGroupOptions{ + ID: core.StringPtr(id), + IfMatch: core.StringPtr(ifMatch), + Name: core.StringPtr(name), + } +} + +// SetID : Allow user to set ID +func (_options *UpdateServiceIDGroupOptions) SetID(id string) *UpdateServiceIDGroupOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetIfMatch : Allow user to set IfMatch +func (_options *UpdateServiceIDGroupOptions) SetIfMatch(ifMatch string) *UpdateServiceIDGroupOptions { + _options.IfMatch = core.StringPtr(ifMatch) + return _options +} + +// SetName : Allow user to set Name +func (_options *UpdateServiceIDGroupOptions) SetName(name string) *UpdateServiceIDGroupOptions { + _options.Name = core.StringPtr(name) + return _options +} + +// SetDescription : Allow user to set Description +func (_options *UpdateServiceIDGroupOptions) SetDescription(description string) *UpdateServiceIDGroupOptions { + _options.Description = core.StringPtr(description) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *UpdateServiceIDGroupOptions) SetHeaders(param map[string]string) *UpdateServiceIDGroupOptions { + options.Headers = param + return options +} + // UpdateServiceIDOptions : The UpdateServiceID options. type UpdateServiceIDOptions struct { // Unique ID of the service ID to be updated. @@ -14816,6 +15858,9 @@ type UpdateServiceIDOptions struct { // existing unique instance crns of the service ID. UniqueInstanceCrns []string `json:"unique_instance_crns,omitempty"` + // Defines if the service ID group ID is included in the response. + ShowGroupID *string `json:"show_group_id,omitempty"` + // Allows users to set headers on API requests. Headers map[string]string } @@ -14823,7 +15868,7 @@ type UpdateServiceIDOptions struct { // NewUpdateServiceIDOptions : Instantiate UpdateServiceIDOptions func (*IamIdentityV1) NewUpdateServiceIDOptions(id string, ifMatch string) *UpdateServiceIDOptions { return &UpdateServiceIDOptions{ - ID: core.StringPtr(id), + ID: core.StringPtr(id), IfMatch: core.StringPtr(ifMatch), } } @@ -14858,6 +15903,12 @@ func (_options *UpdateServiceIDOptions) SetUniqueInstanceCrns(uniqueInstanceCrns return _options } +// SetShowGroupID : Allow user to set ShowGroupID +func (_options *UpdateServiceIDOptions) SetShowGroupID(showGroupID string) *UpdateServiceIDOptions { + _options.ShowGroupID = core.StringPtr(showGroupID) + return _options +} + // SetHeaders : Allow user to set Headers func (options *UpdateServiceIDOptions) SetHeaders(param map[string]string) *UpdateServiceIDOptions { options.Headers = param @@ -14885,8 +15936,8 @@ type UpdateTrustedProfileAssignmentOptions struct { // NewUpdateTrustedProfileAssignmentOptions : Instantiate UpdateTrustedProfileAssignmentOptions func (*IamIdentityV1) NewUpdateTrustedProfileAssignmentOptions(assignmentID string, ifMatch string, templateVersion int64) *UpdateTrustedProfileAssignmentOptions { return &UpdateTrustedProfileAssignmentOptions{ - AssignmentID: core.StringPtr(assignmentID), - IfMatch: core.StringPtr(ifMatch), + AssignmentID: core.StringPtr(assignmentID), + IfMatch: core.StringPtr(ifMatch), TemplateVersion: core.Int64Ptr(templateVersion), } } diff --git a/vendor/github.com/IBM/platform-services-go-sdk/iampolicymanagementv1/iam_policy_management_v1.go b/vendor/github.com/IBM/platform-services-go-sdk/iampolicymanagementv1/iam_policy_management_v1.go index 1856e4e657eb..4386dca177e5 100644 --- a/vendor/github.com/IBM/platform-services-go-sdk/iampolicymanagementv1/iam_policy_management_v1.go +++ b/vendor/github.com/IBM/platform-services-go-sdk/iampolicymanagementv1/iam_policy_management_v1.go @@ -15,7 +15,7 @@ */ /* - * IBM OpenAPI SDK Code Generator Version: 3.103.0-e8b84313-20250402-201816 + * IBM OpenAPI SDK Code Generator Version: 3.106.0-09823488-20250707-071701 */ // Package iampolicymanagementv1 : Operations and models for the IamPolicyManagementV1 service @@ -204,12 +204,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListPoliciesWithContext(ctx co return } - for headerName, headerValue := range listPoliciesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListPolicies") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListPolicies") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPoliciesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -349,12 +349,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreatePolicyWithContext(ctx co return } - for headerName, headerValue := range createPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreatePolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreatePolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -481,12 +481,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ReplacePolicyWithContext(ctx c return } - for headerName, headerValue := range replacePolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplacePolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplacePolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range replacePolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -576,12 +576,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetPolicyWithContext(ctx conte return } - for headerName, headerValue := range getPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -646,12 +646,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeletePolicyWithContext(ctx co return } - for headerName, headerValue := range deletePolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeletePolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeletePolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -706,12 +706,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) UpdatePolicyStateWithContext(c return } - for headerName, headerValue := range updatePolicyStateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "UpdatePolicyState") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "UpdatePolicyState") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updatePolicyStateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -784,12 +784,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListRolesWithContext(ctx conte return } - for headerName, headerValue := range listRolesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListRoles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListRoles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listRolesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -871,12 +871,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreateRoleWithContext(ctx cont return } - for headerName, headerValue := range createRoleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateRole") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateRole") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createRoleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -970,12 +970,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ReplaceRoleWithContext(ctx con return } - for headerName, headerValue := range replaceRoleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplaceRole") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplaceRole") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range replaceRoleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1059,12 +1059,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetRoleWithContext(ctx context return } - for headerName, headerValue := range getRoleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetRole") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetRole") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getRoleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1128,12 +1128,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeleteRoleWithContext(ctx cont return } - for headerName, headerValue := range deleteRoleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteRole") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteRole") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteRoleOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -1187,12 +1187,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListV2PoliciesWithContext(ctx return } - for headerName, headerValue := range listV2PoliciesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListV2Policies") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListV2Policies") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listV2PoliciesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1408,12 +1408,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreateV2PolicyWithContext(ctx return } - for headerName, headerValue := range createV2PolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateV2Policy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateV2Policy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createV2PolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1623,12 +1623,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ReplaceV2PolicyWithContext(ctx return } - for headerName, headerValue := range replaceV2PolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplaceV2Policy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplaceV2Policy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range replaceV2PolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1724,12 +1724,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetV2PolicyWithContext(ctx con return } - for headerName, headerValue := range getV2PolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetV2Policy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetV2Policy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getV2PolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1798,12 +1798,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeleteV2PolicyWithContext(ctx return } - for headerName, headerValue := range deleteV2PolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteV2Policy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteV2Policy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteV2PolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -1858,12 +1858,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListPolicyTemplatesWithContext return } - for headerName, headerValue := range listPolicyTemplatesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListPolicyTemplates") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListPolicyTemplates") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPolicyTemplatesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -1953,12 +1953,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreatePolicyTemplateWithContex return } - for headerName, headerValue := range createPolicyTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreatePolicyTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreatePolicyTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPolicyTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2048,12 +2048,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetPolicyTemplateWithContext(c return } - for headerName, headerValue := range getPolicyTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetPolicyTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetPolicyTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPolicyTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2123,12 +2123,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeletePolicyTemplateWithContex return } - for headerName, headerValue := range deletePolicyTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeletePolicyTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeletePolicyTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePolicyTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -2183,12 +2183,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreatePolicyTemplateVersionWit return } - for headerName, headerValue := range createPolicyTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreatePolicyTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreatePolicyTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPolicyTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2272,12 +2272,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListPolicyTemplateVersionsWith return } - for headerName, headerValue := range listPolicyTemplateVersionsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListPolicyTemplateVersions") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListPolicyTemplateVersions") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPolicyTemplateVersionsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2352,12 +2352,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ReplacePolicyTemplateWithConte return } - for headerName, headerValue := range replacePolicyTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplacePolicyTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplacePolicyTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range replacePolicyTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2447,12 +2447,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeletePolicyTemplateVersionWit return } - for headerName, headerValue := range deletePolicyTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeletePolicyTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeletePolicyTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePolicyTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -2507,12 +2507,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetPolicyTemplateVersionWithCo return } - for headerName, headerValue := range getPolicyTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetPolicyTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetPolicyTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPolicyTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2578,12 +2578,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CommitPolicyTemplateWithContex return } - for headerName, headerValue := range commitPolicyTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CommitPolicyTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CommitPolicyTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range commitPolicyTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -2637,12 +2637,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListPolicyAssignmentsWithConte return } - for headerName, headerValue := range listPolicyAssignmentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListPolicyAssignments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListPolicyAssignments") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPolicyAssignmentsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2721,12 +2721,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreatePolicyTemplateAssignment return } - for headerName, headerValue := range createPolicyTemplateAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreatePolicyTemplateAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreatePolicyTemplateAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPolicyTemplateAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2809,12 +2809,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetPolicyAssignmentWithContext return } - for headerName, headerValue := range getPolicyAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetPolicyAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetPolicyAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPolicyAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2880,12 +2880,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) UpdatePolicyAssignmentWithCont return } - for headerName, headerValue := range updatePolicyAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "UpdatePolicyAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "UpdatePolicyAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updatePolicyAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2966,12 +2966,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeletePolicyAssignmentWithCont return } - for headerName, headerValue := range deletePolicyAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeletePolicyAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeletePolicyAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePolicyAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -3025,12 +3025,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetSettingsWithContext(ctx con return } - for headerName, headerValue := range getSettingsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetSettings") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetSettings") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSettingsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3123,12 +3123,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) UpdateSettingsWithContext(ctx return } - for headerName, headerValue := range updateSettingsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "UpdateSettings") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "UpdateSettings") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateSettingsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3210,12 +3210,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListActionControlTemplatesWith return } - for headerName, headerValue := range listActionControlTemplatesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListActionControlTemplates") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListActionControlTemplates") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listActionControlTemplatesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3286,12 +3286,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreateActionControlTemplateWit return } - for headerName, headerValue := range createActionControlTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateActionControlTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateActionControlTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createActionControlTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3381,12 +3381,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetActionControlTemplateWithCo return } - for headerName, headerValue := range getActionControlTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetActionControlTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetActionControlTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getActionControlTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3456,12 +3456,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeleteActionControlTemplateWit return } - for headerName, headerValue := range deleteActionControlTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteActionControlTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteActionControlTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteActionControlTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -3516,12 +3516,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreateActionControlTemplateVer return } - for headerName, headerValue := range createActionControlTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateActionControlTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateActionControlTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createActionControlTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3605,12 +3605,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListActionControlTemplateVersi return } - for headerName, headerValue := range listActionControlTemplateVersionsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListActionControlTemplateVersions") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListActionControlTemplateVersions") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listActionControlTemplateVersionsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3685,12 +3685,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ReplaceActionControlTemplateWi return } - for headerName, headerValue := range replaceActionControlTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplaceActionControlTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ReplaceActionControlTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range replaceActionControlTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3780,12 +3780,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeleteActionControlTemplateVer return } - for headerName, headerValue := range deleteActionControlTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteActionControlTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteActionControlTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteActionControlTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -3840,12 +3840,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetActionControlTemplateVersio return } - for headerName, headerValue := range getActionControlTemplateVersionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetActionControlTemplateVersion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetActionControlTemplateVersion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getActionControlTemplateVersionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3911,12 +3911,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CommitActionControlTemplateWit return } - for headerName, headerValue := range commitActionControlTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CommitActionControlTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CommitActionControlTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range commitActionControlTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -3970,12 +3970,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) ListActionControlAssignmentsWi return } - for headerName, headerValue := range listActionControlAssignmentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListActionControlAssignments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "ListActionControlAssignments") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listActionControlAssignmentsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -4053,12 +4053,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) CreateActionControlTemplateAss return } - for headerName, headerValue := range createActionControlTemplateAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateActionControlTemplateAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "CreateActionControlTemplateAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createActionControlTemplateAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -4139,12 +4139,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) GetActionControlAssignmentWith return } - for headerName, headerValue := range getActionControlAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetActionControlAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "GetActionControlAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getActionControlAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -4208,12 +4208,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) UpdateActionControlAssignmentW return } - for headerName, headerValue := range updateActionControlAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "UpdateActionControlAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "UpdateActionControlAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateActionControlAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -4292,12 +4292,12 @@ func (iamPolicyManagement *IamPolicyManagementV1) DeleteActionControlAssignmentW return } - for headerName, headerValue := range deleteActionControlAssignmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteActionControlAssignment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("iam_policy_management", "V1", "DeleteActionControlAssignment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteActionControlAssignmentOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -4551,8 +4551,8 @@ type ActionControlAssignmentResourceActionControl struct { // On success, it includes the action control assigned. ResourceCreated *ActionControlAssignmentResourceCreated `json:"resource_created,omitempty"` - // The error response from API. - ErrorMessage *ErrorResponse `json:"error_message,omitempty"` + // Body parameters for assignment error. + ErrorMessage *AssignmentResourceError `json:"error_message,omitempty"` } // UnmarshalActionControlAssignmentResourceActionControl unmarshals an instance of ActionControlAssignmentResourceActionControl from the specified map of raw messages. @@ -4563,7 +4563,7 @@ func UnmarshalActionControlAssignmentResourceActionControl(m map[string]json.Raw err = core.SDKErrorf(err, "", "resource_created-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "error_message", &obj.ErrorMessage, UnmarshalErrorResponse) + err = core.UnmarshalModel(m, "error_message", &obj.ErrorMessage, UnmarshalAssignmentResourceError) if err != nil { err = core.SDKErrorf(err, "", "error_message-error", common.GetComponentInfo()) return @@ -4886,6 +4886,56 @@ func UnmarshalAssignmentResourceCreated(m map[string]json.RawMessage, result int return } +// AssignmentResourceError : Body parameters for assignment error. +type AssignmentResourceError struct { + // Name of the error. + Name *string `json:"name,omitempty"` + + // error code. + ErrorCode *string `json:"errorCode,omitempty"` + + // Error message detailing the nature of the error. + Message *string `json:"message,omitempty"` + + // Internal status code for the error. + Code *string `json:"code,omitempty"` + + // The errors encountered during the response. + Errors []ErrorObject `json:"errors,omitempty"` +} + +// UnmarshalAssignmentResourceError unmarshals an instance of AssignmentResourceError from the specified map of raw messages. +func UnmarshalAssignmentResourceError(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(AssignmentResourceError) + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "errorCode", &obj.ErrorCode) + if err != nil { + err = core.SDKErrorf(err, "", "errorCode-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "message", &obj.Message) + if err != nil { + err = core.SDKErrorf(err, "", "message-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "code", &obj.Code) + if err != nil { + err = core.SDKErrorf(err, "", "code-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "errors", &obj.Errors, UnmarshalErrorObject) + if err != nil { + err = core.SDKErrorf(err, "", "errors-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // AssignmentTargetDetails : assignment target account and type. type AssignmentTargetDetails struct { // Assignment target type. @@ -6373,40 +6423,6 @@ func UnmarshalErrorObject(m map[string]json.RawMessage, result interface{}) (err return } -// ErrorResponse : The error response from API. -type ErrorResponse struct { - // The unique transaction ID for the request. - Trace *string `json:"trace" validate:"required"` - - // The errors encountered during the response. - Errors []ErrorObject `json:"errors" validate:"required"` - - // The HTTP error code of the response. - StatusCode *int64 `json:"status_code" validate:"required"` -} - -// UnmarshalErrorResponse unmarshals an instance of ErrorResponse from the specified map of raw messages. -func UnmarshalErrorResponse(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(ErrorResponse) - err = core.UnmarshalPrimitive(m, "trace", &obj.Trace) - if err != nil { - err = core.SDKErrorf(err, "", "trace-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalModel(m, "errors", &obj.Errors, UnmarshalErrorObject) - if err != nil { - err = core.SDKErrorf(err, "", "errors-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "status_code", &obj.StatusCode) - if err != nil { - err = core.SDKErrorf(err, "", "status_code-error", common.GetComponentInfo()) - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - // ExternalAccountIdentityInteraction : How external accounts can interact in relation to the requested account. type ExternalAccountIdentityInteraction struct { // The settings for each identity type. @@ -8252,8 +8268,8 @@ type PolicyAssignmentResourcePolicy struct { // policy status. Status *string `json:"status,omitempty"` - // The error response from API. - ErrorMessage *ErrorResponse `json:"error_message,omitempty"` + // Body parameters for assignment error. + ErrorMessage *AssignmentResourceError `json:"error_message,omitempty"` } // UnmarshalPolicyAssignmentResourcePolicy unmarshals an instance of PolicyAssignmentResourcePolicy from the specified map of raw messages. @@ -8269,7 +8285,7 @@ func UnmarshalPolicyAssignmentResourcePolicy(m map[string]json.RawMessage, resul err = core.SDKErrorf(err, "", "status-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "error_message", &obj.ErrorMessage, UnmarshalErrorResponse) + err = core.UnmarshalModel(m, "error_message", &obj.ErrorMessage, UnmarshalAssignmentResourceError) if err != nil { err = core.SDKErrorf(err, "", "error_message-error", common.GetComponentInfo()) return diff --git a/vendor/github.com/IBM/vpc-go-sdk/common/version.go b/vendor/github.com/IBM/vpc-go-sdk/common/version.go index 040a7c635c36..f4a88168c839 100644 --- a/vendor/github.com/IBM/vpc-go-sdk/common/version.go +++ b/vendor/github.com/IBM/vpc-go-sdk/common/version.go @@ -1,4 +1,4 @@ package common // Version of the SDK -const Version = "0.68.0" +const Version = "0.71.1" diff --git a/vendor/github.com/IBM/vpc-go-sdk/vpcv1/vpc_v1.go b/vendor/github.com/IBM/vpc-go-sdk/vpcv1/vpc_v1.go index 16bbc888f827..ee4742fca3e9 100644 --- a/vendor/github.com/IBM/vpc-go-sdk/vpcv1/vpc_v1.go +++ b/vendor/github.com/IBM/vpc-go-sdk/vpcv1/vpc_v1.go @@ -15,7 +15,7 @@ */ /* - * IBM OpenAPI SDK Code Generator Version: 3.102.0-615ec964-20250307-203034 + * IBM OpenAPI SDK Code Generator Version: 3.105.1-067d600b-20250616-154447 */ // Package vpcv1 : Operations and models for the VpcV1 service @@ -38,7 +38,7 @@ import ( // VpcV1 : The IBM Cloud Virtual Private Cloud (VPC) API can be used to programmatically provision and manage virtual // server instances, along with subnets, volumes, load balancers, and more. // -// API Version: 2025-04-22 +// API Version: 2025-09-01 type VpcV1 struct { Service *core.BaseService @@ -46,8 +46,8 @@ type VpcV1 struct { // `2`. Generation *int64 - // The API version, in format `YYYY-MM-DD`. For the API behavior documented here, specify any date between `2025-04-08` - // and `2025-04-10`. + // The API version, in format `YYYY-MM-DD`. For the API behavior documented here, specify any date between `2025-08-26` + // and `2025-09-01`. Version *string } @@ -67,8 +67,8 @@ type VpcV1Options struct { // `2`. Generation *int64 - // The API version, in format `YYYY-MM-DD`. For the API behavior documented here, specify any date between `2025-04-08` - // and `2025-04-23`. + // The API version, in format `YYYY-MM-DD`. For the API behavior documented here, specify any date between `2025-08-26` + // and `2025-09-01`. Version *string } @@ -133,7 +133,7 @@ func NewVpcV1(options *VpcV1Options) (service *VpcV1, err error) { } if options.Version == nil { - options.Version = core.StringPtr("2025-04-22") + options.Version = core.StringPtr("2025-08-26") } service = &VpcV1{ @@ -221,19 +221,18 @@ func (vpc *VpcV1) DisableRetries() { vpc.Service.DisableRetries() } -// ListVpcs : List VPCs -// This request lists VPCs in the region. A VPC is a virtual network that belongs to an account and provides logical -// isolation from other networks. A VPC is made up of resources in one or more zones. VPCs are regional, and each VPC -// can contain resources in multiple zones in a region. -func (vpc *VpcV1) ListVpcs(listVpcsOptions *ListVpcsOptions) (result *VPCCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVpcsWithContext(context.Background(), listVpcsOptions) +// ListBackupPolicies : List backup policies +// This request lists backup policies in the region. Backup policies control which sources are selected for backup and +// include a set of backup policy plans that provide the backup schedules and deletion triggers. +func (vpc *VpcV1) ListBackupPolicies(listBackupPoliciesOptions *ListBackupPoliciesOptions) (result *BackupPolicyCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBackupPoliciesWithContext(context.Background(), listBackupPoliciesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVpcsWithContext is an alternate form of the ListVpcs method which supports a Context parameter -func (vpc *VpcV1) ListVpcsWithContext(ctx context.Context, listVpcsOptions *ListVpcsOptions) (result *VPCCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listVpcsOptions, "listVpcsOptions") +// ListBackupPoliciesWithContext is an alternate form of the ListBackupPolicies method which supports a Context parameter +func (vpc *VpcV1) ListBackupPoliciesWithContext(ctx context.Context, listBackupPoliciesOptions *ListBackupPoliciesOptions) (result *BackupPolicyCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listBackupPoliciesOptions, "listBackupPoliciesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -242,35 +241,38 @@ func (vpc *VpcV1) ListVpcsWithContext(ctx context.Context, listVpcsOptions *List builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVpcsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBackupPolicies") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVpcs") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBackupPoliciesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVpcsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVpcsOptions.Start)) + if listBackupPoliciesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listBackupPoliciesOptions.Start)) } - if listVpcsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVpcsOptions.Limit)) + if listBackupPoliciesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listBackupPoliciesOptions.Limit)) } - if listVpcsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listVpcsOptions.ResourceGroupID)) + if listBackupPoliciesOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listBackupPoliciesOptions.ResourceGroupID)) } - if listVpcsOptions.ClassicAccess != nil { - builder.AddQuery("classic_access", fmt.Sprint(*listVpcsOptions.ClassicAccess)) + if listBackupPoliciesOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listBackupPoliciesOptions.Name)) + } + if listBackupPoliciesOptions.Tag != nil { + builder.AddQuery("tag", fmt.Sprint(*listBackupPoliciesOptions.Tag)) } request, err := builder.Build() @@ -282,12 +284,12 @@ func (vpc *VpcV1) ListVpcsWithContext(ctx context.Context, listVpcsOptions *List var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpcs", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_backup_policies", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPCCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -298,18 +300,23 @@ func (vpc *VpcV1) ListVpcsWithContext(ctx context.Context, listVpcsOptions *List return } -// CreateVPC : Create a VPC -// This request creates a new VPC from a VPC prototype object. The prototype object is structured in the same way as a -// retrieved VPC, and contains the information necessary to create the new VPC. -func (vpc *VpcV1) CreateVPC(createVPCOptions *CreateVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPCWithContext(context.Background(), createVPCOptions) +// CreateBackupPolicy : Create a backup policy +// This request creates a new backup policy from a backup policy prototype object. The prototype object is structured in +// the same way as a retrieved backup policy, and contains the information necessary to create the new backup policy. +func (vpc *VpcV1) CreateBackupPolicy(createBackupPolicyOptions *CreateBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateBackupPolicyWithContext(context.Background(), createBackupPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPCWithContext is an alternate form of the CreateVPC method which supports a Context parameter -func (vpc *VpcV1) CreateVPCWithContext(ctx context.Context, createVPCOptions *CreateVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(createVPCOptions, "createVPCOptions") +// CreateBackupPolicyWithContext is an alternate form of the CreateBackupPolicy method which supports a Context parameter +func (vpc *VpcV1) CreateBackupPolicyWithContext(ctx context.Context, createBackupPolicyOptions *CreateBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createBackupPolicyOptions, "createBackupPolicyOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(createBackupPolicyOptions, "createBackupPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -318,18 +325,18 @@ func (vpc *VpcV1) CreateVPCWithContext(ctx context.Context, createVPCOptions *Cr builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPCOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBackupPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPC") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createBackupPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -338,23 +345,7 @@ func (vpc *VpcV1) CreateVPCWithContext(ctx context.Context, createVPCOptions *Cr builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createVPCOptions.AddressPrefixManagement != nil { - body["address_prefix_management"] = createVPCOptions.AddressPrefixManagement - } - if createVPCOptions.ClassicAccess != nil { - body["classic_access"] = createVPCOptions.ClassicAccess - } - if createVPCOptions.Dns != nil { - body["dns"] = createVPCOptions.Dns - } - if createVPCOptions.Name != nil { - body["name"] = createVPCOptions.Name - } - if createVPCOptions.ResourceGroup != nil { - body["resource_group"] = createVPCOptions.ResourceGroup - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(createBackupPolicyOptions.BackupPolicyPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -369,12 +360,12 @@ func (vpc *VpcV1) CreateVPCWithContext(ctx context.Context, createVPCOptions *Cr var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpc", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_backup_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPC) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -385,63 +376,77 @@ func (vpc *VpcV1) CreateVPCWithContext(ctx context.Context, createVPCOptions *Cr return } -// DeleteVPC : Delete a VPC -// This request deletes a VPC. This operation cannot be reversed. -// -// For this request to succeed: -// - Instances, subnets, public gateways, endpoint gateways, and private path service -// gateways must not reside in this VPC -// - The VPC must not be providing DNS resolution for any other VPCs -// - If `dns.enable_hub` is `true`, `dns.resolution_binding_count` must be zero -// -// All security groups and network ACLs associated with the VPC are automatically deleted. All flow log collectors with -// `auto_delete` set to `true` targeting the VPC or any resource in the VPC are automatically deleted. -func (vpc *VpcV1) DeleteVPC(deleteVPCOptions *DeleteVPCOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPCWithContext(context.Background(), deleteVPCOptions) +// ListBackupPolicyJobs : List jobs for a backup policy +// This request retrieves jobs for a backup policy. A backup job represents the execution of a backup policy plan for a +// resource matching the policy's criteria. +func (vpc *VpcV1) ListBackupPolicyJobs(listBackupPolicyJobsOptions *ListBackupPolicyJobsOptions) (result *BackupPolicyJobCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBackupPolicyJobsWithContext(context.Background(), listBackupPolicyJobsOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPCWithContext is an alternate form of the DeleteVPC method which supports a Context parameter -func (vpc *VpcV1) DeleteVPCWithContext(ctx context.Context, deleteVPCOptions *DeleteVPCOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPCOptions, "deleteVPCOptions cannot be nil") +// ListBackupPolicyJobsWithContext is an alternate form of the ListBackupPolicyJobs method which supports a Context parameter +func (vpc *VpcV1) ListBackupPolicyJobsWithContext(ctx context.Context, listBackupPolicyJobsOptions *ListBackupPolicyJobsOptions) (result *BackupPolicyJobCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listBackupPolicyJobsOptions, "listBackupPolicyJobsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPCOptions, "deleteVPCOptions") + err = core.ValidateStruct(listBackupPolicyJobsOptions, "listBackupPolicyJobsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteVPCOptions.ID, + "backup_policy_id": *listBackupPolicyJobsOptions.BackupPolicyID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/jobs`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPCOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBackupPolicyJobs") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPC") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBackupPolicyJobsOptions.Headers { builder.AddHeader(headerName, headerValue) } - if deleteVPCOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteVPCOptions.IfMatch)) - } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listBackupPolicyJobsOptions.Status != nil { + builder.AddQuery("status", fmt.Sprint(*listBackupPolicyJobsOptions.Status)) + } + if listBackupPolicyJobsOptions.BackupPolicyPlanID != nil { + builder.AddQuery("backup_policy_plan.id", fmt.Sprint(*listBackupPolicyJobsOptions.BackupPolicyPlanID)) + } + if listBackupPolicyJobsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listBackupPolicyJobsOptions.Start)) + } + if listBackupPolicyJobsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listBackupPolicyJobsOptions.Limit)) + } + if listBackupPolicyJobsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listBackupPolicyJobsOptions.Sort)) + } + if listBackupPolicyJobsOptions.SourceID != nil { + builder.AddQuery("source.id", fmt.Sprint(*listBackupPolicyJobsOptions.SourceID)) + } + if listBackupPolicyJobsOptions.TargetSnapshotsID != nil { + builder.AddQuery("target_snapshots[].id", fmt.Sprint(*listBackupPolicyJobsOptions.TargetSnapshotsID)) + } + if listBackupPolicyJobsOptions.TargetSnapshotsCRN != nil { + builder.AddQuery("target_snapshots[].crn", fmt.Sprint(*listBackupPolicyJobsOptions.TargetSnapshotsCRN)) + } request, err := builder.Build() if err != nil { @@ -449,56 +454,66 @@ func (vpc *VpcV1) DeleteVPCWithContext(ctx context.Context, deleteVPCOptions *De return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpc", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_backup_policy_jobs", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyJobCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetVPC : Retrieve a VPC -// This request retrieves a single VPC specified by the identifier in the URL. -func (vpc *VpcV1) GetVPC(getVPCOptions *GetVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCWithContext(context.Background(), getVPCOptions) +// GetBackupPolicyJob : Retrieve a backup policy job +// This request retrieves a single backup policy job specified by the identifier in the URL. +func (vpc *VpcV1) GetBackupPolicyJob(getBackupPolicyJobOptions *GetBackupPolicyJobOptions) (result *BackupPolicyJob, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBackupPolicyJobWithContext(context.Background(), getBackupPolicyJobOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCWithContext is an alternate form of the GetVPC method which supports a Context parameter -func (vpc *VpcV1) GetVPCWithContext(ctx context.Context, getVPCOptions *GetVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPCOptions, "getVPCOptions cannot be nil") +// GetBackupPolicyJobWithContext is an alternate form of the GetBackupPolicyJob method which supports a Context parameter +func (vpc *VpcV1) GetBackupPolicyJobWithContext(ctx context.Context, getBackupPolicyJobOptions *GetBackupPolicyJobOptions) (result *BackupPolicyJob, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBackupPolicyJobOptions, "getBackupPolicyJobOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCOptions, "getVPCOptions") + err = core.ValidateStruct(getBackupPolicyJobOptions, "getBackupPolicyJobOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getVPCOptions.ID, + "backup_policy_id": *getBackupPolicyJobOptions.BackupPolicyID, + "id": *getBackupPolicyJobOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/jobs/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBackupPolicyJob") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPC") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBackupPolicyJobOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -515,12 +530,12 @@ func (vpc *VpcV1) GetVPCWithContext(ctx context.Context, getVPCOptions *GetVPCOp var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_backup_policy_job", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPC) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyJob) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -531,62 +546,54 @@ func (vpc *VpcV1) GetVPCWithContext(ctx context.Context, getVPCOptions *GetVPCOp return } -// UpdateVPC : Update a VPC -// This request updates a VPC with the information provided in a VPC patch object. The patch object is structured in the -// same way as a retrieved VPC and needs to contain only the information to be updated. -func (vpc *VpcV1) UpdateVPC(updateVPCOptions *UpdateVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPCWithContext(context.Background(), updateVPCOptions) +// ListBackupPolicyPlans : List plans for a backup policy +// This request retrieves plans for a backup policy. Backup plans provide the backup schedule and deletion triggers. +func (vpc *VpcV1) ListBackupPolicyPlans(listBackupPolicyPlansOptions *ListBackupPolicyPlansOptions) (result *BackupPolicyPlanCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBackupPolicyPlansWithContext(context.Background(), listBackupPolicyPlansOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPCWithContext is an alternate form of the UpdateVPC method which supports a Context parameter -func (vpc *VpcV1) UpdateVPCWithContext(ctx context.Context, updateVPCOptions *UpdateVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPCOptions, "updateVPCOptions cannot be nil") +// ListBackupPolicyPlansWithContext is an alternate form of the ListBackupPolicyPlans method which supports a Context parameter +func (vpc *VpcV1) ListBackupPolicyPlansWithContext(ctx context.Context, listBackupPolicyPlansOptions *ListBackupPolicyPlansOptions) (result *BackupPolicyPlanCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listBackupPolicyPlansOptions, "listBackupPolicyPlansOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPCOptions, "updateVPCOptions") + err = core.ValidateStruct(listBackupPolicyPlansOptions, "listBackupPolicyPlansOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateVPCOptions.ID, + "backup_policy_id": *listBackupPolicyPlansOptions.BackupPolicyID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPCOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBackupPolicyPlans") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPC") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBackupPolicyPlansOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateVPCOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateVPCOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - _, err = builder.SetBodyContentJSON(updateVPCOptions.VPCPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listBackupPolicyPlansOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listBackupPolicyPlansOptions.Name)) } request, err := builder.Build() @@ -598,12 +605,12 @@ func (vpc *VpcV1) UpdateVPCWithContext(ctx context.Context, updateVPCOptions *Up var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_vpc", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_backup_policy_plans", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPC) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlanCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -614,54 +621,92 @@ func (vpc *VpcV1) UpdateVPCWithContext(ctx context.Context, updateVPCOptions *Up return } -// GetVPCDefaultNetworkACL : Retrieve a VPC's default network ACL -// This request retrieves the default network ACL for the VPC specified by the identifier in the URL. The default -// network ACL is applied to any new subnets in the VPC which do not specify a network ACL. -func (vpc *VpcV1) GetVPCDefaultNetworkACL(getVPCDefaultNetworkACLOptions *GetVPCDefaultNetworkACLOptions) (result *DefaultNetworkACL, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCDefaultNetworkACLWithContext(context.Background(), getVPCDefaultNetworkACLOptions) +// CreateBackupPolicyPlan : Create a plan for a backup policy +// This request creates a new backup policy plan from a backup policy plan prototype object. The prototype object is +// structured in the same way as a retrieved backup policy plan, and contains the information necessary to create the +// new backup policy plan. +// +// Backups created by this plan will use the resource group of the source being backed up. +// +// Backups created by this plan will use the plan's name truncated to 46 characters, followed by a unique 16-character +// suffix. +func (vpc *VpcV1) CreateBackupPolicyPlan(createBackupPolicyPlanOptions *CreateBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateBackupPolicyPlanWithContext(context.Background(), createBackupPolicyPlanOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCDefaultNetworkACLWithContext is an alternate form of the GetVPCDefaultNetworkACL method which supports a Context parameter -func (vpc *VpcV1) GetVPCDefaultNetworkACLWithContext(ctx context.Context, getVPCDefaultNetworkACLOptions *GetVPCDefaultNetworkACLOptions) (result *DefaultNetworkACL, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPCDefaultNetworkACLOptions, "getVPCDefaultNetworkACLOptions cannot be nil") +// CreateBackupPolicyPlanWithContext is an alternate form of the CreateBackupPolicyPlan method which supports a Context parameter +func (vpc *VpcV1) CreateBackupPolicyPlanWithContext(ctx context.Context, createBackupPolicyPlanOptions *CreateBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createBackupPolicyPlanOptions, "createBackupPolicyPlanOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCDefaultNetworkACLOptions, "getVPCDefaultNetworkACLOptions") + err = core.ValidateStruct(createBackupPolicyPlanOptions, "createBackupPolicyPlanOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getVPCDefaultNetworkACLOptions.ID, + "backup_policy_id": *createBackupPolicyPlanOptions.BackupPolicyID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}/default_network_acl`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCDefaultNetworkACLOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBackupPolicyPlan") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCDefaultNetworkACL") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createBackupPolicyPlanOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createBackupPolicyPlanOptions.CronSpec != nil { + body["cron_spec"] = createBackupPolicyPlanOptions.CronSpec + } + if createBackupPolicyPlanOptions.Active != nil { + body["active"] = createBackupPolicyPlanOptions.Active + } + if createBackupPolicyPlanOptions.AttachUserTags != nil { + body["attach_user_tags"] = createBackupPolicyPlanOptions.AttachUserTags + } + if createBackupPolicyPlanOptions.ClonePolicy != nil { + body["clone_policy"] = createBackupPolicyPlanOptions.ClonePolicy + } + if createBackupPolicyPlanOptions.CopyUserTags != nil { + body["copy_user_tags"] = createBackupPolicyPlanOptions.CopyUserTags + } + if createBackupPolicyPlanOptions.DeletionTrigger != nil { + body["deletion_trigger"] = createBackupPolicyPlanOptions.DeletionTrigger + } + if createBackupPolicyPlanOptions.Name != nil { + body["name"] = createBackupPolicyPlanOptions.Name + } + if createBackupPolicyPlanOptions.RemoteRegionPolicies != nil { + body["remote_region_policies"] = createBackupPolicyPlanOptions.RemoteRegionPolicies + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -671,12 +716,12 @@ func (vpc *VpcV1) GetVPCDefaultNetworkACLWithContext(ctx context.Context, getVPC var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc_default_network_acl", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_backup_policy_plan", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDefaultNetworkACL) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlan) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -687,51 +732,58 @@ func (vpc *VpcV1) GetVPCDefaultNetworkACLWithContext(ctx context.Context, getVPC return } -// GetVPCDefaultRoutingTable : Retrieve a VPC's default routing table -// This request retrieves the default routing table for the VPC specified by the identifier in the URL. The default -// routing table is associated with any subnets in the VPC which have not been explicitly associated with another -// routing table. -func (vpc *VpcV1) GetVPCDefaultRoutingTable(getVPCDefaultRoutingTableOptions *GetVPCDefaultRoutingTableOptions) (result *DefaultRoutingTable, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCDefaultRoutingTableWithContext(context.Background(), getVPCDefaultRoutingTableOptions) +// DeleteBackupPolicyPlan : Delete a backup policy plan +// This request deletes a backup policy plan. This operation cannot be reversed. Any backups that have been created by +// the plan will remain but will no longer be subject to the plan's deletion trigger. Any running jobs associated with +// the plan will run to completion before the plan is deleted. +// +// If the request is accepted, the backup policy plan `status` will be set to `deleting`. Once deletion processing +// completes, the backup policy plan will no longer be retrievable. +func (vpc *VpcV1) DeleteBackupPolicyPlan(deleteBackupPolicyPlanOptions *DeleteBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteBackupPolicyPlanWithContext(context.Background(), deleteBackupPolicyPlanOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCDefaultRoutingTableWithContext is an alternate form of the GetVPCDefaultRoutingTable method which supports a Context parameter -func (vpc *VpcV1) GetVPCDefaultRoutingTableWithContext(ctx context.Context, getVPCDefaultRoutingTableOptions *GetVPCDefaultRoutingTableOptions) (result *DefaultRoutingTable, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPCDefaultRoutingTableOptions, "getVPCDefaultRoutingTableOptions cannot be nil") +// DeleteBackupPolicyPlanWithContext is an alternate form of the DeleteBackupPolicyPlan method which supports a Context parameter +func (vpc *VpcV1) DeleteBackupPolicyPlanWithContext(ctx context.Context, deleteBackupPolicyPlanOptions *DeleteBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteBackupPolicyPlanOptions, "deleteBackupPolicyPlanOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCDefaultRoutingTableOptions, "getVPCDefaultRoutingTableOptions") + err = core.ValidateStruct(deleteBackupPolicyPlanOptions, "deleteBackupPolicyPlanOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getVPCDefaultRoutingTableOptions.ID, + "backup_policy_id": *deleteBackupPolicyPlanOptions.BackupPolicyID, + "id": *deleteBackupPolicyPlanOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}/default_routing_table`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCDefaultRoutingTableOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBackupPolicyPlan") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCDefaultRoutingTable") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteBackupPolicyPlanOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + if deleteBackupPolicyPlanOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteBackupPolicyPlanOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -745,12 +797,12 @@ func (vpc *VpcV1) GetVPCDefaultRoutingTableWithContext(ctx context.Context, getV var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc_default_routing_table", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_backup_policy_plan", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDefaultRoutingTable) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlan) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -761,47 +813,47 @@ func (vpc *VpcV1) GetVPCDefaultRoutingTableWithContext(ctx context.Context, getV return } -// GetVPCDefaultSecurityGroup : Retrieve a VPC's default security group -// This request retrieves the default security group for the VPC specified by the identifier in the URL. Resources -// created in this VPC that allow a security group to be optionally specified will use this security group by default. -func (vpc *VpcV1) GetVPCDefaultSecurityGroup(getVPCDefaultSecurityGroupOptions *GetVPCDefaultSecurityGroupOptions) (result *DefaultSecurityGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCDefaultSecurityGroupWithContext(context.Background(), getVPCDefaultSecurityGroupOptions) +// GetBackupPolicyPlan : Retrieve a backup policy plan +// This request retrieves a single backup policy plan specified by the identifier in the URL. +func (vpc *VpcV1) GetBackupPolicyPlan(getBackupPolicyPlanOptions *GetBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBackupPolicyPlanWithContext(context.Background(), getBackupPolicyPlanOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCDefaultSecurityGroupWithContext is an alternate form of the GetVPCDefaultSecurityGroup method which supports a Context parameter -func (vpc *VpcV1) GetVPCDefaultSecurityGroupWithContext(ctx context.Context, getVPCDefaultSecurityGroupOptions *GetVPCDefaultSecurityGroupOptions) (result *DefaultSecurityGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPCDefaultSecurityGroupOptions, "getVPCDefaultSecurityGroupOptions cannot be nil") +// GetBackupPolicyPlanWithContext is an alternate form of the GetBackupPolicyPlan method which supports a Context parameter +func (vpc *VpcV1) GetBackupPolicyPlanWithContext(ctx context.Context, getBackupPolicyPlanOptions *GetBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBackupPolicyPlanOptions, "getBackupPolicyPlanOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCDefaultSecurityGroupOptions, "getVPCDefaultSecurityGroupOptions") + err = core.ValidateStruct(getBackupPolicyPlanOptions, "getBackupPolicyPlanOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getVPCDefaultSecurityGroupOptions.ID, + "backup_policy_id": *getBackupPolicyPlanOptions.BackupPolicyID, + "id": *getBackupPolicyPlanOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}/default_security_group`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCDefaultSecurityGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBackupPolicyPlan") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCDefaultSecurityGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBackupPolicyPlanOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -818,12 +870,12 @@ func (vpc *VpcV1) GetVPCDefaultSecurityGroupWithContext(ctx context.Context, get var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc_default_security_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_backup_policy_plan", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDefaultSecurityGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlan) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -834,57 +886,63 @@ func (vpc *VpcV1) GetVPCDefaultSecurityGroupWithContext(ctx context.Context, get return } -// ListVPCAddressPrefixes : List address prefixes for a VPC -// This request lists address pool prefixes for a VPC. -func (vpc *VpcV1) ListVPCAddressPrefixes(listVPCAddressPrefixesOptions *ListVPCAddressPrefixesOptions) (result *AddressPrefixCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPCAddressPrefixesWithContext(context.Background(), listVPCAddressPrefixesOptions) +// UpdateBackupPolicyPlan : Update a backup policy plan +// This request updates a backup policy plan with the information in a provided plan patch. The plan patch object is +// structured in the same way as a retrieved backup policy plan and can contains only the information to be updated. +func (vpc *VpcV1) UpdateBackupPolicyPlan(updateBackupPolicyPlanOptions *UpdateBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateBackupPolicyPlanWithContext(context.Background(), updateBackupPolicyPlanOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPCAddressPrefixesWithContext is an alternate form of the ListVPCAddressPrefixes method which supports a Context parameter -func (vpc *VpcV1) ListVPCAddressPrefixesWithContext(ctx context.Context, listVPCAddressPrefixesOptions *ListVPCAddressPrefixesOptions) (result *AddressPrefixCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPCAddressPrefixesOptions, "listVPCAddressPrefixesOptions cannot be nil") +// UpdateBackupPolicyPlanWithContext is an alternate form of the UpdateBackupPolicyPlan method which supports a Context parameter +func (vpc *VpcV1) UpdateBackupPolicyPlanWithContext(ctx context.Context, updateBackupPolicyPlanOptions *UpdateBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateBackupPolicyPlanOptions, "updateBackupPolicyPlanOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPCAddressPrefixesOptions, "listVPCAddressPrefixesOptions") + err = core.ValidateStruct(updateBackupPolicyPlanOptions, "updateBackupPolicyPlanOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *listVPCAddressPrefixesOptions.VPCID, + "backup_policy_id": *updateBackupPolicyPlanOptions.BackupPolicyID, + "id": *updateBackupPolicyPlanOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPCAddressPrefixesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBackupPolicyPlan") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCAddressPrefixes") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateBackupPolicyPlanOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateBackupPolicyPlanOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateBackupPolicyPlanOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPCAddressPrefixesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPCAddressPrefixesOptions.Start)) - } - if listVPCAddressPrefixesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPCAddressPrefixesOptions.Limit)) + + _, err = builder.SetBodyContentJSON(updateBackupPolicyPlanOptions.BackupPolicyPlanPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -896,12 +954,12 @@ func (vpc *VpcV1) ListVPCAddressPrefixesWithContext(ctx context.Context, listVPC var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpc_address_prefixes", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_backup_policy_plan", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddressPrefixCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlan) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -912,74 +970,59 @@ func (vpc *VpcV1) ListVPCAddressPrefixesWithContext(ctx context.Context, listVPC return } -// CreateVPCAddressPrefix : Create an address prefix for a VPC -// This request creates a new prefix from a prefix prototype object. The prototype object is structured in the same way -// as a retrieved prefix, and contains the information necessary to create the new prefix. -func (vpc *VpcV1) CreateVPCAddressPrefix(createVPCAddressPrefixOptions *CreateVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPCAddressPrefixWithContext(context.Background(), createVPCAddressPrefixOptions) +// DeleteBackupPolicy : Delete a backup policy +// This request deletes a backup policy. This operation cannot be reversed. +// +// If the request is accepted, the backup policy `status` will be set to `deleting`. Once deletion processing completes, +// the backup policy will no longer be retrievable. +func (vpc *VpcV1) DeleteBackupPolicy(deleteBackupPolicyOptions *DeleteBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteBackupPolicyWithContext(context.Background(), deleteBackupPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPCAddressPrefixWithContext is an alternate form of the CreateVPCAddressPrefix method which supports a Context parameter -func (vpc *VpcV1) CreateVPCAddressPrefixWithContext(ctx context.Context, createVPCAddressPrefixOptions *CreateVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVPCAddressPrefixOptions, "createVPCAddressPrefixOptions cannot be nil") +// DeleteBackupPolicyWithContext is an alternate form of the DeleteBackupPolicy method which supports a Context parameter +func (vpc *VpcV1) DeleteBackupPolicyWithContext(ctx context.Context, deleteBackupPolicyOptions *DeleteBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteBackupPolicyOptions, "deleteBackupPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVPCAddressPrefixOptions, "createVPCAddressPrefixOptions") + err = core.ValidateStruct(deleteBackupPolicyOptions, "deleteBackupPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *createVPCAddressPrefixOptions.VPCID, + "id": *deleteBackupPolicyOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPCAddressPrefixOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBackupPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCAddressPrefix") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteBackupPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + if deleteBackupPolicyOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteBackupPolicyOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createVPCAddressPrefixOptions.CIDR != nil { - body["cidr"] = createVPCAddressPrefixOptions.CIDR - } - if createVPCAddressPrefixOptions.Zone != nil { - body["zone"] = createVPCAddressPrefixOptions.Zone - } - if createVPCAddressPrefixOptions.IsDefault != nil { - body["is_default"] = createVPCAddressPrefixOptions.IsDefault - } - if createVPCAddressPrefixOptions.Name != nil { - body["name"] = createVPCAddressPrefixOptions.Name - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -989,12 +1032,12 @@ func (vpc *VpcV1) CreateVPCAddressPrefixWithContext(ctx context.Context, createV var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpc_address_prefix", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_backup_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddressPrefix) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1005,50 +1048,49 @@ func (vpc *VpcV1) CreateVPCAddressPrefixWithContext(ctx context.Context, createV return } -// DeleteVPCAddressPrefix : Delete an address prefix -// This request deletes a prefix. This operation cannot be reversed. The request will fail if any subnets use addresses -// from this prefix. -func (vpc *VpcV1) DeleteVPCAddressPrefix(deleteVPCAddressPrefixOptions *DeleteVPCAddressPrefixOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPCAddressPrefixWithContext(context.Background(), deleteVPCAddressPrefixOptions) +// GetBackupPolicy : Retrieve a backup policy +// This request retrieves a single backup policy specified by the identifier in the URL. +func (vpc *VpcV1) GetBackupPolicy(getBackupPolicyOptions *GetBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBackupPolicyWithContext(context.Background(), getBackupPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPCAddressPrefixWithContext is an alternate form of the DeleteVPCAddressPrefix method which supports a Context parameter -func (vpc *VpcV1) DeleteVPCAddressPrefixWithContext(ctx context.Context, deleteVPCAddressPrefixOptions *DeleteVPCAddressPrefixOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPCAddressPrefixOptions, "deleteVPCAddressPrefixOptions cannot be nil") +// GetBackupPolicyWithContext is an alternate form of the GetBackupPolicy method which supports a Context parameter +func (vpc *VpcV1) GetBackupPolicyWithContext(ctx context.Context, getBackupPolicyOptions *GetBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBackupPolicyOptions, "getBackupPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPCAddressPrefixOptions, "deleteVPCAddressPrefixOptions") + err = core.ValidateStruct(getBackupPolicyOptions, "getBackupPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *deleteVPCAddressPrefixOptions.VPCID, - "id": *deleteVPCAddressPrefixOptions.ID, + "id": *getBackupPolicyOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPCAddressPrefixOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBackupPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCAddressPrefix") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBackupPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -1059,64 +1101,83 @@ func (vpc *VpcV1) DeleteVPCAddressPrefixWithContext(ctx context.Context, deleteV return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpc_address_prefix", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_backup_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicy) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetVPCAddressPrefix : Retrieve an address prefix -// This request retrieves a single prefix specified by the identifier in the URL. -func (vpc *VpcV1) GetVPCAddressPrefix(getVPCAddressPrefixOptions *GetVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCAddressPrefixWithContext(context.Background(), getVPCAddressPrefixOptions) +// UpdateBackupPolicy : Update a backup policy +// This request updates a backup policy with the information in a provided backup policy patch. The backup policy patch +// object is structured in the same way as a retrieved backup policy and contains only the information to be updated. +func (vpc *VpcV1) UpdateBackupPolicy(updateBackupPolicyOptions *UpdateBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateBackupPolicyWithContext(context.Background(), updateBackupPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCAddressPrefixWithContext is an alternate form of the GetVPCAddressPrefix method which supports a Context parameter -func (vpc *VpcV1) GetVPCAddressPrefixWithContext(ctx context.Context, getVPCAddressPrefixOptions *GetVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPCAddressPrefixOptions, "getVPCAddressPrefixOptions cannot be nil") +// UpdateBackupPolicyWithContext is an alternate form of the UpdateBackupPolicy method which supports a Context parameter +func (vpc *VpcV1) UpdateBackupPolicyWithContext(ctx context.Context, updateBackupPolicyOptions *UpdateBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateBackupPolicyOptions, "updateBackupPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCAddressPrefixOptions, "getVPCAddressPrefixOptions") + err = core.ValidateStruct(updateBackupPolicyOptions, "updateBackupPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *getVPCAddressPrefixOptions.VPCID, - "id": *getVPCAddressPrefixOptions.ID, + "id": *updateBackupPolicyOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCAddressPrefixOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBackupPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCAddressPrefix") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateBackupPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateBackupPolicyOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateBackupPolicyOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateBackupPolicyOptions.BackupPolicyPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -1126,12 +1187,12 @@ func (vpc *VpcV1) GetVPCAddressPrefixWithContext(ctx context.Context, getVPCAddr var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc_address_prefix", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_backup_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddressPrefix) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1142,60 +1203,50 @@ func (vpc *VpcV1) GetVPCAddressPrefixWithContext(ctx context.Context, getVPCAddr return } -// UpdateVPCAddressPrefix : Update an address prefix -// This request updates a prefix with the information in a provided prefix patch. The prefix patch object is structured -// in the same way as a retrieved prefix and contains only the information to be updated. -func (vpc *VpcV1) UpdateVPCAddressPrefix(updateVPCAddressPrefixOptions *UpdateVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPCAddressPrefixWithContext(context.Background(), updateVPCAddressPrefixOptions) +// ListBareMetalServerProfiles : List bare metal server profiles +// This request lists [bare metal server profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-bare-metal-servers-profile) +// available in the region. A bare metal server profile specifies the performance characteristics and pricing model for +// a bare metal server. +func (vpc *VpcV1) ListBareMetalServerProfiles(listBareMetalServerProfilesOptions *ListBareMetalServerProfilesOptions) (result *BareMetalServerProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBareMetalServerProfilesWithContext(context.Background(), listBareMetalServerProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPCAddressPrefixWithContext is an alternate form of the UpdateVPCAddressPrefix method which supports a Context parameter -func (vpc *VpcV1) UpdateVPCAddressPrefixWithContext(ctx context.Context, updateVPCAddressPrefixOptions *UpdateVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPCAddressPrefixOptions, "updateVPCAddressPrefixOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(updateVPCAddressPrefixOptions, "updateVPCAddressPrefixOptions") +// ListBareMetalServerProfilesWithContext is an alternate form of the ListBareMetalServerProfiles method which supports a Context parameter +func (vpc *VpcV1) ListBareMetalServerProfilesWithContext(ctx context.Context, listBareMetalServerProfilesOptions *ListBareMetalServerProfilesOptions) (result *BareMetalServerProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listBareMetalServerProfilesOptions, "listBareMetalServerProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "vpc_id": *updateVPCAddressPrefixOptions.VPCID, - "id": *updateVPCAddressPrefixOptions.ID, - } - - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_server/profiles`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPCAddressPrefixOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCAddressPrefix") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBareMetalServerProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - _, err = builder.SetBodyContentJSON(updateVPCAddressPrefixOptions.AddressPrefixPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listBareMetalServerProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listBareMetalServerProfilesOptions.Start)) + } + if listBareMetalServerProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listBareMetalServerProfilesOptions.Limit)) } request, err := builder.Build() @@ -1207,12 +1258,12 @@ func (vpc *VpcV1) UpdateVPCAddressPrefixWithContext(ctx context.Context, updateV var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_vpc_address_prefix", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_bare_metal_server_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddressPrefix) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1223,88 +1274,52 @@ func (vpc *VpcV1) UpdateVPCAddressPrefixWithContext(ctx context.Context, updateV return } -// ListVPCDnsResolutionBindings : List DNS resolution bindings for a VPC -// This request lists DNS resolution bindings for a VPC. A DNS resolution binding represents an association with another -// VPC for centralizing DNS name resolution. -// -// If the VPC specified by the identifier in the URL is a DNS hub VPC (has `dns.enable_hub` set to `true`) then there is -// one binding for each VPC bound to the hub VPC. The endpoint gateways in the bound VPCs can allow (using -// `allow_dns_resolution_binding`) the hub VPC to centralize resolution of their DNS names. -// -// If the VPC specified by the identifier in the URL is not a DNS hub VPC, then there is at most one binding (to a hub -// VPC). The endpoint gateways in the VPC specified by the identifier in the URL can allow (using -// `allow_dns_resolution_binding`) its hub VPC to centralize resolution of their DNS names. -// -// To make use of centralized DNS resolution, a VPC bound to a DNS hub VPC must delegate DNS resolution to its hub VPC -// by setting `dns.resolver.type` to `delegate`. -// -// The bindings will be sorted by their `created_at` property values, with newest bindings first. Bindings with -// identical `created_at` property values will in turn be sorted by ascending `name` property values. -func (vpc *VpcV1) ListVPCDnsResolutionBindings(listVPCDnsResolutionBindingsOptions *ListVPCDnsResolutionBindingsOptions) (result *VpcdnsResolutionBindingCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPCDnsResolutionBindingsWithContext(context.Background(), listVPCDnsResolutionBindingsOptions) +// GetBareMetalServerProfile : Retrieve a bare metal server profile +// This request retrieves a single bare metal server profile specified by the name in the URL. +func (vpc *VpcV1) GetBareMetalServerProfile(getBareMetalServerProfileOptions *GetBareMetalServerProfileOptions) (result *BareMetalServerProfile, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBareMetalServerProfileWithContext(context.Background(), getBareMetalServerProfileOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPCDnsResolutionBindingsWithContext is an alternate form of the ListVPCDnsResolutionBindings method which supports a Context parameter -func (vpc *VpcV1) ListVPCDnsResolutionBindingsWithContext(ctx context.Context, listVPCDnsResolutionBindingsOptions *ListVPCDnsResolutionBindingsOptions) (result *VpcdnsResolutionBindingCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPCDnsResolutionBindingsOptions, "listVPCDnsResolutionBindingsOptions cannot be nil") +// GetBareMetalServerProfileWithContext is an alternate form of the GetBareMetalServerProfile method which supports a Context parameter +func (vpc *VpcV1) GetBareMetalServerProfileWithContext(ctx context.Context, getBareMetalServerProfileOptions *GetBareMetalServerProfileOptions) (result *BareMetalServerProfile, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBareMetalServerProfileOptions, "getBareMetalServerProfileOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPCDnsResolutionBindingsOptions, "listVPCDnsResolutionBindingsOptions") + err = core.ValidateStruct(getBareMetalServerProfileOptions, "getBareMetalServerProfileOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *listVPCDnsResolutionBindingsOptions.VPCID, + "name": *getBareMetalServerProfileOptions.Name, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_server/profiles/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPCDnsResolutionBindingsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCDnsResolutionBindings") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBareMetalServerProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPCDnsResolutionBindingsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.Sort)) - } - if listVPCDnsResolutionBindingsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.Start)) - } - if listVPCDnsResolutionBindingsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.Limit)) - } - if listVPCDnsResolutionBindingsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.Name)) - } - if listVPCDnsResolutionBindingsOptions.VPCCRN != nil { - builder.AddQuery("vpc.crn", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.VPCCRN)) - } - if listVPCDnsResolutionBindingsOptions.VPCName != nil { - builder.AddQuery("vpc.name", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.VPCName)) - } - if listVPCDnsResolutionBindingsOptions.AccountID != nil { - builder.AddQuery("account.id", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.AccountID)) - } request, err := builder.Build() if err != nil { @@ -1315,12 +1330,12 @@ func (vpc *VpcV1) ListVPCDnsResolutionBindingsWithContext(ctx context.Context, l var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpc_dns_resolution_bindings", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_bare_metal_server_profile", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBindingCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerProfile) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1331,72 +1346,72 @@ func (vpc *VpcV1) ListVPCDnsResolutionBindingsWithContext(ctx context.Context, l return } -// CreateVPCDnsResolutionBinding : Create a DNS resolution binding -// This request creates a new DNS resolution binding from a DNS resolution binding prototype object. The prototype -// object is structured in the same way as a retrieved DNS resolution binding, and contains the information necessary to -// create the new DNS resolution binding. -// -// For this request to succeed, `dns.enable_hub` must be `false` for the VPC specified by the identifier in the URL, and -// the VPC must not already have a DNS resolution binding. -// -// See [About DNS sharing for VPE gateways](/docs/vpc?topic=vpc-vpe-dns-sharing) for more information. -func (vpc *VpcV1) CreateVPCDnsResolutionBinding(createVPCDnsResolutionBindingOptions *CreateVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPCDnsResolutionBindingWithContext(context.Background(), createVPCDnsResolutionBindingOptions) +// ListBareMetalServers : List bare metal servers +// This request lists bare metal servers in the region. +func (vpc *VpcV1) ListBareMetalServers(listBareMetalServersOptions *ListBareMetalServersOptions) (result *BareMetalServerCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBareMetalServersWithContext(context.Background(), listBareMetalServersOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPCDnsResolutionBindingWithContext is an alternate form of the CreateVPCDnsResolutionBinding method which supports a Context parameter -func (vpc *VpcV1) CreateVPCDnsResolutionBindingWithContext(ctx context.Context, createVPCDnsResolutionBindingOptions *CreateVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVPCDnsResolutionBindingOptions, "createVPCDnsResolutionBindingOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(createVPCDnsResolutionBindingOptions, "createVPCDnsResolutionBindingOptions") +// ListBareMetalServersWithContext is an alternate form of the ListBareMetalServers method which supports a Context parameter +func (vpc *VpcV1) ListBareMetalServersWithContext(ctx context.Context, listBareMetalServersOptions *ListBareMetalServersOptions) (result *BareMetalServerCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listBareMetalServersOptions, "listBareMetalServersOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "vpc_id": *createVPCDnsResolutionBindingOptions.VPCID, - } - - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPCDnsResolutionBindingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServers") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCDnsResolutionBinding") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBareMetalServersOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if createVPCDnsResolutionBindingOptions.VPC != nil { - body["vpc"] = createVPCDnsResolutionBindingOptions.VPC + if listBareMetalServersOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listBareMetalServersOptions.Start)) } - if createVPCDnsResolutionBindingOptions.Name != nil { - body["name"] = createVPCDnsResolutionBindingOptions.Name + if listBareMetalServersOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listBareMetalServersOptions.Limit)) } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listBareMetalServersOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listBareMetalServersOptions.ResourceGroupID)) + } + if listBareMetalServersOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listBareMetalServersOptions.Name)) + } + if listBareMetalServersOptions.ReservationID != nil { + builder.AddQuery("reservation.id", fmt.Sprint(*listBareMetalServersOptions.ReservationID)) + } + if listBareMetalServersOptions.ReservationCRN != nil { + builder.AddQuery("reservation.crn", fmt.Sprint(*listBareMetalServersOptions.ReservationCRN)) + } + if listBareMetalServersOptions.ReservationName != nil { + builder.AddQuery("reservation.name", fmt.Sprint(*listBareMetalServersOptions.ReservationName)) + } + if listBareMetalServersOptions.VPCID != nil { + builder.AddQuery("vpc.id", fmt.Sprint(*listBareMetalServersOptions.VPCID)) + } + if listBareMetalServersOptions.VPCCRN != nil { + builder.AddQuery("vpc.crn", fmt.Sprint(*listBareMetalServersOptions.VPCCRN)) + } + if listBareMetalServersOptions.VPCName != nil { + builder.AddQuery("vpc.name", fmt.Sprint(*listBareMetalServersOptions.VPCName)) } request, err := builder.Build() @@ -1408,12 +1423,12 @@ func (vpc *VpcV1) CreateVPCDnsResolutionBindingWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpc_dns_resolution_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_bare_metal_servers", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBinding) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1424,57 +1439,60 @@ func (vpc *VpcV1) CreateVPCDnsResolutionBindingWithContext(ctx context.Context, return } -// DeleteVPCDnsResolutionBinding : Delete a DNS resolution binding -// This request deletes a DNS resolution binding. This operation cannot be reversed. +// CreateBareMetalServer : Create a bare metal server +// This request provisions a new bare metal server from a prototype object. The prototype object is structured in the +// same way as a retrieved bare metal server, and contains the information necessary to provision the new bare metal +// server. The bare metal server is automatically started. // -// For this request to succeed, the VPC specified by the identifier in the URL must not have -// `dns.resolver.type` set to `delegated`. -func (vpc *VpcV1) DeleteVPCDnsResolutionBinding(deleteVPCDnsResolutionBindingOptions *DeleteVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteVPCDnsResolutionBindingWithContext(context.Background(), deleteVPCDnsResolutionBindingOptions) +// For this request to succeed, the properties in the request must adhere to the source image's `allowed_use` property. +func (vpc *VpcV1) CreateBareMetalServer(createBareMetalServerOptions *CreateBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateBareMetalServerWithContext(context.Background(), createBareMetalServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPCDnsResolutionBindingWithContext is an alternate form of the DeleteVPCDnsResolutionBinding method which supports a Context parameter -func (vpc *VpcV1) DeleteVPCDnsResolutionBindingWithContext(ctx context.Context, deleteVPCDnsResolutionBindingOptions *DeleteVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPCDnsResolutionBindingOptions, "deleteVPCDnsResolutionBindingOptions cannot be nil") +// CreateBareMetalServerWithContext is an alternate form of the CreateBareMetalServer method which supports a Context parameter +func (vpc *VpcV1) CreateBareMetalServerWithContext(ctx context.Context, createBareMetalServerOptions *CreateBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createBareMetalServerOptions, "createBareMetalServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPCDnsResolutionBindingOptions, "deleteVPCDnsResolutionBindingOptions") + err = core.ValidateStruct(createBareMetalServerOptions, "createBareMetalServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "vpc_id": *deleteVPCDnsResolutionBindingOptions.VPCID, - "id": *deleteVPCDnsResolutionBindingOptions.ID, - } - - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPCDnsResolutionBindingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBareMetalServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCDnsResolutionBinding") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createBareMetalServerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(createBareMetalServerOptions.BareMetalServerPrototype) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -1484,12 +1502,12 @@ func (vpc *VpcV1) DeleteVPCDnsResolutionBindingWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpc_dns_resolution_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_bare_metal_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBinding) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1500,54 +1518,71 @@ func (vpc *VpcV1) DeleteVPCDnsResolutionBindingWithContext(ctx context.Context, return } -// GetVPCDnsResolutionBinding : Retrieve a DNS resolution binding -// This request retrieves a single DNS resolution binding specified by the identifier in the URL. -func (vpc *VpcV1) GetVPCDnsResolutionBinding(getVPCDnsResolutionBindingOptions *GetVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCDnsResolutionBindingWithContext(context.Background(), getVPCDnsResolutionBindingOptions) +// CreateBareMetalServerConsoleAccessToken : Create a console access token for a bare metal server +// This request creates a new single-use console access token for a bare metal server. All console configuration is +// provided at token create time, and the token is subsequently used in the `access_token` query parameter for the +// WebSocket request. The access token is only valid for a short period of time, and a maximum of one token is valid +// for a given bare metal server at a time. For this request to succeed, the server must have a `status` of `stopped`, +// `starting`, or `running`. +func (vpc *VpcV1) CreateBareMetalServerConsoleAccessToken(createBareMetalServerConsoleAccessTokenOptions *CreateBareMetalServerConsoleAccessTokenOptions) (result *BareMetalServerConsoleAccessToken, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateBareMetalServerConsoleAccessTokenWithContext(context.Background(), createBareMetalServerConsoleAccessTokenOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCDnsResolutionBindingWithContext is an alternate form of the GetVPCDnsResolutionBinding method which supports a Context parameter -func (vpc *VpcV1) GetVPCDnsResolutionBindingWithContext(ctx context.Context, getVPCDnsResolutionBindingOptions *GetVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPCDnsResolutionBindingOptions, "getVPCDnsResolutionBindingOptions cannot be nil") +// CreateBareMetalServerConsoleAccessTokenWithContext is an alternate form of the CreateBareMetalServerConsoleAccessToken method which supports a Context parameter +func (vpc *VpcV1) CreateBareMetalServerConsoleAccessTokenWithContext(ctx context.Context, createBareMetalServerConsoleAccessTokenOptions *CreateBareMetalServerConsoleAccessTokenOptions) (result *BareMetalServerConsoleAccessToken, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createBareMetalServerConsoleAccessTokenOptions, "createBareMetalServerConsoleAccessTokenOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCDnsResolutionBindingOptions, "getVPCDnsResolutionBindingOptions") + err = core.ValidateStruct(createBareMetalServerConsoleAccessTokenOptions, "createBareMetalServerConsoleAccessTokenOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *getVPCDnsResolutionBindingOptions.VPCID, - "id": *getVPCDnsResolutionBindingOptions.ID, + "bare_metal_server_id": *createBareMetalServerConsoleAccessTokenOptions.BareMetalServerID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/console_access_token`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCDnsResolutionBindingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBareMetalServerConsoleAccessToken") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCDnsResolutionBinding") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createBareMetalServerConsoleAccessTokenOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createBareMetalServerConsoleAccessTokenOptions.ConsoleType != nil { + body["console_type"] = createBareMetalServerConsoleAccessTokenOptions.ConsoleType + } + if createBareMetalServerConsoleAccessTokenOptions.Force != nil { + body["force"] = createBareMetalServerConsoleAccessTokenOptions.Force + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -1557,12 +1592,12 @@ func (vpc *VpcV1) GetVPCDnsResolutionBindingWithContext(ctx context.Context, get var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc_dns_resolution_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_bare_metal_server_console_access_token", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBinding) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerConsoleAccessToken) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1573,63 +1608,54 @@ func (vpc *VpcV1) GetVPCDnsResolutionBindingWithContext(ctx context.Context, get return } -// UpdateVPCDnsResolutionBinding : Update a DNS resolution binding -// This request updates a DNS resolution binding with the information in a provided DNS resolution binding patch. The -// DNS resolution binding patch object is structured in the same way as a retrieved DNS resolution binding and contains -// only the information to be updated. -func (vpc *VpcV1) UpdateVPCDnsResolutionBinding(updateVPCDnsResolutionBindingOptions *UpdateVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPCDnsResolutionBindingWithContext(context.Background(), updateVPCDnsResolutionBindingOptions) +// ListBareMetalServerDisks : List disks on a bare metal server +// This request lists disks on a bare metal server. A disk is a block device that is locally attached to the physical +// server. By default, the listed disks are sorted by their `created_at` property values, with the newest disk first. +func (vpc *VpcV1) ListBareMetalServerDisks(listBareMetalServerDisksOptions *ListBareMetalServerDisksOptions) (result *BareMetalServerDiskCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBareMetalServerDisksWithContext(context.Background(), listBareMetalServerDisksOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPCDnsResolutionBindingWithContext is an alternate form of the UpdateVPCDnsResolutionBinding method which supports a Context parameter -func (vpc *VpcV1) UpdateVPCDnsResolutionBindingWithContext(ctx context.Context, updateVPCDnsResolutionBindingOptions *UpdateVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPCDnsResolutionBindingOptions, "updateVPCDnsResolutionBindingOptions cannot be nil") +// ListBareMetalServerDisksWithContext is an alternate form of the ListBareMetalServerDisks method which supports a Context parameter +func (vpc *VpcV1) ListBareMetalServerDisksWithContext(ctx context.Context, listBareMetalServerDisksOptions *ListBareMetalServerDisksOptions) (result *BareMetalServerDiskCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listBareMetalServerDisksOptions, "listBareMetalServerDisksOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPCDnsResolutionBindingOptions, "updateVPCDnsResolutionBindingOptions") + err = core.ValidateStruct(listBareMetalServerDisksOptions, "listBareMetalServerDisksOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *updateVPCDnsResolutionBindingOptions.VPCID, - "id": *updateVPCDnsResolutionBindingOptions.ID, + "bare_metal_server_id": *listBareMetalServerDisksOptions.BareMetalServerID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/disks`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPCDnsResolutionBindingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerDisks") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCDnsResolutionBinding") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBareMetalServerDisksOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVPCDnsResolutionBindingOptions.VpcdnsResolutionBindingPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -1639,12 +1665,12 @@ func (vpc *VpcV1) UpdateVPCDnsResolutionBindingWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_vpc_dns_resolution_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_bare_metal_server_disks", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBinding) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerDiskCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1655,66 +1681,53 @@ func (vpc *VpcV1) UpdateVPCDnsResolutionBindingWithContext(ctx context.Context, return } -// ListVPCRoutes : List routes in a VPC's default routing table -// This request lists routes in the VPC's default routing table. Each route is zone-specific and directs any packets -// matching its destination CIDR block to a `next_hop` IP address. The most specific route matching a packet's -// destination will be used. If multiple equally-specific routes exist, traffic will be distributed across them. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) ListVPCRoutes(listVPCRoutesOptions *ListVPCRoutesOptions) (result *RouteCollectionVPCContext, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPCRoutesWithContext(context.Background(), listVPCRoutesOptions) +// GetBareMetalServerDisk : Retrieve a bare metal server disk +// This request retrieves a single disk specified by the identifier in the URL. +func (vpc *VpcV1) GetBareMetalServerDisk(getBareMetalServerDiskOptions *GetBareMetalServerDiskOptions) (result *BareMetalServerDisk, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBareMetalServerDiskWithContext(context.Background(), getBareMetalServerDiskOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPCRoutesWithContext is an alternate form of the ListVPCRoutes method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) ListVPCRoutesWithContext(ctx context.Context, listVPCRoutesOptions *ListVPCRoutesOptions) (result *RouteCollectionVPCContext, response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: ListVPCRoutes") - err = core.ValidateNotNil(listVPCRoutesOptions, "listVPCRoutesOptions cannot be nil") +// GetBareMetalServerDiskWithContext is an alternate form of the GetBareMetalServerDisk method which supports a Context parameter +func (vpc *VpcV1) GetBareMetalServerDiskWithContext(ctx context.Context, getBareMetalServerDiskOptions *GetBareMetalServerDiskOptions) (result *BareMetalServerDisk, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBareMetalServerDiskOptions, "getBareMetalServerDiskOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPCRoutesOptions, "listVPCRoutesOptions") + err = core.ValidateStruct(getBareMetalServerDiskOptions, "getBareMetalServerDiskOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *listVPCRoutesOptions.VPCID, + "bare_metal_server_id": *getBareMetalServerDiskOptions.BareMetalServerID, + "id": *getBareMetalServerDiskOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/disks/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPCRoutesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerDisk") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCRoutes") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBareMetalServerDiskOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPCRoutesOptions.ZoneName != nil { - builder.AddQuery("zone.name", fmt.Sprint(*listVPCRoutesOptions.ZoneName)) - } - if listVPCRoutesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPCRoutesOptions.Start)) - } - if listVPCRoutesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPCRoutesOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -1725,12 +1738,12 @@ func (vpc *VpcV1) ListVPCRoutesWithContext(ctx context.Context, listVPCRoutesOpt var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpc_routes", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_bare_metal_server_disk", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRouteCollectionVPCContext) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerDisk) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1741,85 +1754,59 @@ func (vpc *VpcV1) ListVPCRoutesWithContext(ctx context.Context, listVPCRoutesOpt return } -// CreateVPCRoute : Create a route in a VPC's default routing table -// This request creates a new route in the VPC's default routing table. The route prototype object is structured in the -// same way as a retrieved route, and contains the information necessary to create the new route. The request will fail -// if the new route will cause a loop. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) CreateVPCRoute(createVPCRouteOptions *CreateVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPCRouteWithContext(context.Background(), createVPCRouteOptions) +// UpdateBareMetalServerDisk : Update a bare metal server disk +// This request updates the bare metal server disk with the information in a provided patch. +func (vpc *VpcV1) UpdateBareMetalServerDisk(updateBareMetalServerDiskOptions *UpdateBareMetalServerDiskOptions) (result *BareMetalServerDisk, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateBareMetalServerDiskWithContext(context.Background(), updateBareMetalServerDiskOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPCRouteWithContext is an alternate form of the CreateVPCRoute method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) CreateVPCRouteWithContext(ctx context.Context, createVPCRouteOptions *CreateVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: CreateVPCRoute") - err = core.ValidateNotNil(createVPCRouteOptions, "createVPCRouteOptions cannot be nil") +// UpdateBareMetalServerDiskWithContext is an alternate form of the UpdateBareMetalServerDisk method which supports a Context parameter +func (vpc *VpcV1) UpdateBareMetalServerDiskWithContext(ctx context.Context, updateBareMetalServerDiskOptions *UpdateBareMetalServerDiskOptions) (result *BareMetalServerDisk, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateBareMetalServerDiskOptions, "updateBareMetalServerDiskOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVPCRouteOptions, "createVPCRouteOptions") + err = core.ValidateStruct(updateBareMetalServerDiskOptions, "updateBareMetalServerDiskOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *createVPCRouteOptions.VPCID, + "bare_metal_server_id": *updateBareMetalServerDiskOptions.BareMetalServerID, + "id": *updateBareMetalServerDiskOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/disks/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPCRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBareMetalServerDisk") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateBareMetalServerDiskOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createVPCRouteOptions.Destination != nil { - body["destination"] = createVPCRouteOptions.Destination - } - if createVPCRouteOptions.Zone != nil { - body["zone"] = createVPCRouteOptions.Zone - } - if createVPCRouteOptions.Action != nil { - body["action"] = createVPCRouteOptions.Action - } - if createVPCRouteOptions.Advertise != nil { - body["advertise"] = createVPCRouteOptions.Advertise - } - if createVPCRouteOptions.Name != nil { - body["name"] = createVPCRouteOptions.Name - } - if createVPCRouteOptions.NextHop != nil { - body["next_hop"] = createVPCRouteOptions.NextHop - } - if createVPCRouteOptions.Priority != nil { - body["priority"] = createVPCRouteOptions.Priority - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + _, err = builder.SetBodyContentJSON(updateBareMetalServerDiskOptions.BareMetalServerDiskPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -1831,12 +1818,12 @@ func (vpc *VpcV1) CreateVPCRouteWithContext(ctx context.Context, createVPCRouteO var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpc_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_bare_metal_server_disk", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerDisk) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1847,55 +1834,65 @@ func (vpc *VpcV1) CreateVPCRouteWithContext(ctx context.Context, createVPCRouteO return } -// DeleteVPCRoute : Delete a VPC route -// This request deletes a route. This operation cannot be reversed. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) DeleteVPCRoute(deleteVPCRouteOptions *DeleteVPCRouteOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPCRouteWithContext(context.Background(), deleteVPCRouteOptions) +// ListBareMetalServerNetworkAttachments : List network attachments on a bare metal server +// This request lists network attachments on a bare metal server. A bare metal server network attachment is an abstract +// representation of a network device and attaches a bare metal server to a single subnet. Each network interface on a +// bare metal server can attach to any subnet in the zone, including subnets that are already attached to the bare metal +// server. +// +// The network attachments will be sorted by their `created_at` property values, with newest network attachments first. +// Network attachments with identical `created_at` property values will in turn be sorted by ascending `name` property +// values. +func (vpc *VpcV1) ListBareMetalServerNetworkAttachments(listBareMetalServerNetworkAttachmentsOptions *ListBareMetalServerNetworkAttachmentsOptions) (result *BareMetalServerNetworkAttachmentCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBareMetalServerNetworkAttachmentsWithContext(context.Background(), listBareMetalServerNetworkAttachmentsOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPCRouteWithContext is an alternate form of the DeleteVPCRoute method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) DeleteVPCRouteWithContext(ctx context.Context, deleteVPCRouteOptions *DeleteVPCRouteOptions) (response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: DeleteVPCRoute") - err = core.ValidateNotNil(deleteVPCRouteOptions, "deleteVPCRouteOptions cannot be nil") +// ListBareMetalServerNetworkAttachmentsWithContext is an alternate form of the ListBareMetalServerNetworkAttachments method which supports a Context parameter +func (vpc *VpcV1) ListBareMetalServerNetworkAttachmentsWithContext(ctx context.Context, listBareMetalServerNetworkAttachmentsOptions *ListBareMetalServerNetworkAttachmentsOptions) (result *BareMetalServerNetworkAttachmentCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listBareMetalServerNetworkAttachmentsOptions, "listBareMetalServerNetworkAttachmentsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPCRouteOptions, "deleteVPCRouteOptions") + err = core.ValidateStruct(listBareMetalServerNetworkAttachmentsOptions, "listBareMetalServerNetworkAttachmentsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *deleteVPCRouteOptions.VPCID, - "id": *deleteVPCRouteOptions.ID, + "bare_metal_server_id": *listBareMetalServerNetworkAttachmentsOptions.BareMetalServerID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPCRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerNetworkAttachments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBareMetalServerNetworkAttachmentsOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listBareMetalServerNetworkAttachmentsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listBareMetalServerNetworkAttachmentsOptions.Start)) + } + if listBareMetalServerNetworkAttachmentsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listBareMetalServerNetworkAttachmentsOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -1903,67 +1900,81 @@ func (vpc *VpcV1) DeleteVPCRouteWithContext(ctx context.Context, deleteVPCRouteO return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpc_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_bare_metal_server_network_attachments", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkAttachmentCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetVPCRoute : Retrieve a VPC route -// This request retrieves a single route specified by the identifier in the URL. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) GetVPCRoute(getVPCRouteOptions *GetVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCRouteWithContext(context.Background(), getVPCRouteOptions) +// CreateBareMetalServerNetworkAttachment : Create a network attachment on a bare metal server +// This request creates a new bare metal server network attachment from a bare metal server network attachment prototype +// object. The prototype object is structured in the same way as a retrieved bare metal server network attachment, and +// contains the information necessary to create the new bare metal server network attachment. +func (vpc *VpcV1) CreateBareMetalServerNetworkAttachment(createBareMetalServerNetworkAttachmentOptions *CreateBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateBareMetalServerNetworkAttachmentWithContext(context.Background(), createBareMetalServerNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCRouteWithContext is an alternate form of the GetVPCRoute method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) GetVPCRouteWithContext(ctx context.Context, getVPCRouteOptions *GetVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: GetVPCRoute") - err = core.ValidateNotNil(getVPCRouteOptions, "getVPCRouteOptions cannot be nil") +// CreateBareMetalServerNetworkAttachmentWithContext is an alternate form of the CreateBareMetalServerNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) CreateBareMetalServerNetworkAttachmentWithContext(ctx context.Context, createBareMetalServerNetworkAttachmentOptions *CreateBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createBareMetalServerNetworkAttachmentOptions, "createBareMetalServerNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCRouteOptions, "getVPCRouteOptions") + err = core.ValidateStruct(createBareMetalServerNetworkAttachmentOptions, "createBareMetalServerNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *getVPCRouteOptions.VPCID, - "id": *getVPCRouteOptions.ID, + "bare_metal_server_id": *createBareMetalServerNetworkAttachmentOptions.BareMetalServerID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBareMetalServerNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createBareMetalServerNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(createBareMetalServerNetworkAttachmentOptions.BareMetalServerNetworkAttachmentPrototype) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -1973,12 +1984,12 @@ func (vpc *VpcV1) GetVPCRouteWithContext(ctx context.Context, getVPCRouteOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_bare_metal_server_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -1989,148 +2000,119 @@ func (vpc *VpcV1) GetVPCRouteWithContext(ctx context.Context, getVPCRouteOptions return } -// UpdateVPCRoute : Update a VPC route -// This request updates a route with the information in a provided route patch. The route patch object is structured in -// the same way as a retrieved route and contains only the information to be updated. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) UpdateVPCRoute(updateVPCRouteOptions *UpdateVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPCRouteWithContext(context.Background(), updateVPCRouteOptions) +// DeleteBareMetalServerNetworkAttachment : Delete a bare metal server network attachment +// This request deletes a bare metal server network attachment. This operation cannot be reversed. Any floating IPs +// associated with the bare metal server network attachment are implicitly disassociated. +// +// The bare metal server's primary network attachment cannot be deleted. +func (vpc *VpcV1) DeleteBareMetalServerNetworkAttachment(deleteBareMetalServerNetworkAttachmentOptions *DeleteBareMetalServerNetworkAttachmentOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteBareMetalServerNetworkAttachmentWithContext(context.Background(), deleteBareMetalServerNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPCRouteWithContext is an alternate form of the UpdateVPCRoute method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) UpdateVPCRouteWithContext(ctx context.Context, updateVPCRouteOptions *UpdateVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: UpdateVPCRoute") - err = core.ValidateNotNil(updateVPCRouteOptions, "updateVPCRouteOptions cannot be nil") +// DeleteBareMetalServerNetworkAttachmentWithContext is an alternate form of the DeleteBareMetalServerNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) DeleteBareMetalServerNetworkAttachmentWithContext(ctx context.Context, deleteBareMetalServerNetworkAttachmentOptions *DeleteBareMetalServerNetworkAttachmentOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteBareMetalServerNetworkAttachmentOptions, "deleteBareMetalServerNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPCRouteOptions, "updateVPCRouteOptions") + err = core.ValidateStruct(deleteBareMetalServerNetworkAttachmentOptions, "deleteBareMetalServerNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *updateVPCRouteOptions.VPCID, - "id": *updateVPCRouteOptions.ID, + "bare_metal_server_id": *deleteBareMetalServerNetworkAttachmentOptions.BareMetalServerID, + "id": *deleteBareMetalServerNetworkAttachmentOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPCRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBareMetalServerNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteBareMetalServerNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVPCRouteOptions.RoutePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "update_vpc_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_bare_metal_server_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListVPCRoutingTables : List routing tables for a VPC -// This request lists routing tables for a VPC. Each subnet in a VPC is associated with a routing table, which controls -// delivery of packets sent on that subnet according to the action of the most specific matching route in the table. If -// multiple equally-specific routes exist, traffic will be distributed across them. If no routes match, delivery will be -// controlled by the system's built-in routes. -func (vpc *VpcV1) ListVPCRoutingTables(listVPCRoutingTablesOptions *ListVPCRoutingTablesOptions) (result *RoutingTableCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPCRoutingTablesWithContext(context.Background(), listVPCRoutingTablesOptions) +// GetBareMetalServerNetworkAttachment : Retrieve a bare metal server network attachment +// This request retrieves a single bare metal server network attachment specified by the identifier in the URL. +func (vpc *VpcV1) GetBareMetalServerNetworkAttachment(getBareMetalServerNetworkAttachmentOptions *GetBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBareMetalServerNetworkAttachmentWithContext(context.Background(), getBareMetalServerNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPCRoutingTablesWithContext is an alternate form of the ListVPCRoutingTables method which supports a Context parameter -func (vpc *VpcV1) ListVPCRoutingTablesWithContext(ctx context.Context, listVPCRoutingTablesOptions *ListVPCRoutingTablesOptions) (result *RoutingTableCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPCRoutingTablesOptions, "listVPCRoutingTablesOptions cannot be nil") +// GetBareMetalServerNetworkAttachmentWithContext is an alternate form of the GetBareMetalServerNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) GetBareMetalServerNetworkAttachmentWithContext(ctx context.Context, getBareMetalServerNetworkAttachmentOptions *GetBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBareMetalServerNetworkAttachmentOptions, "getBareMetalServerNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPCRoutingTablesOptions, "listVPCRoutingTablesOptions") + err = core.ValidateStruct(getBareMetalServerNetworkAttachmentOptions, "getBareMetalServerNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *listVPCRoutingTablesOptions.VPCID, + "bare_metal_server_id": *getBareMetalServerNetworkAttachmentOptions.BareMetalServerID, + "id": *getBareMetalServerNetworkAttachmentOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPCRoutingTablesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCRoutingTables") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBareMetalServerNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPCRoutingTablesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPCRoutingTablesOptions.Start)) - } - if listVPCRoutingTablesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPCRoutingTablesOptions.Limit)) - } - if listVPCRoutingTablesOptions.IsDefault != nil { - builder.AddQuery("is_default", fmt.Sprint(*listVPCRoutingTablesOptions.IsDefault)) - } request, err := builder.Build() if err != nil { @@ -2141,12 +2123,12 @@ func (vpc *VpcV1) ListVPCRoutingTablesWithContext(ctx context.Context, listVPCRo var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpc_routing_tables", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_bare_metal_server_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTableCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2157,84 +2139,58 @@ func (vpc *VpcV1) ListVPCRoutingTablesWithContext(ctx context.Context, listVPCRo return } -// CreateVPCRoutingTable : Create a routing table for a VPC -// This request creates a routing table from a routing table prototype object. The prototype object is structured in the -// same way as a retrieved routing table, and contains the information necessary to create the new routing table. -// -// At present, the routing table's `resource_group` will be inherited from its VPC, but may be specifiable in the -// future. -func (vpc *VpcV1) CreateVPCRoutingTable(createVPCRoutingTableOptions *CreateVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPCRoutingTableWithContext(context.Background(), createVPCRoutingTableOptions) +// UpdateBareMetalServerNetworkAttachment : Update a bare metal server network attachment +// This request updates a bare metal server network attachment with the information provided in a bare metal server +// network attachment patch object. The bare metal server network attachment patch object is structured in the same way +// as a retrieved bare metal server network attachment and contains only the information to be updated. +func (vpc *VpcV1) UpdateBareMetalServerNetworkAttachment(updateBareMetalServerNetworkAttachmentOptions *UpdateBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateBareMetalServerNetworkAttachmentWithContext(context.Background(), updateBareMetalServerNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPCRoutingTableWithContext is an alternate form of the CreateVPCRoutingTable method which supports a Context parameter -func (vpc *VpcV1) CreateVPCRoutingTableWithContext(ctx context.Context, createVPCRoutingTableOptions *CreateVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVPCRoutingTableOptions, "createVPCRoutingTableOptions cannot be nil") +// UpdateBareMetalServerNetworkAttachmentWithContext is an alternate form of the UpdateBareMetalServerNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) UpdateBareMetalServerNetworkAttachmentWithContext(ctx context.Context, updateBareMetalServerNetworkAttachmentOptions *UpdateBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateBareMetalServerNetworkAttachmentOptions, "updateBareMetalServerNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVPCRoutingTableOptions, "createVPCRoutingTableOptions") + err = core.ValidateStruct(updateBareMetalServerNetworkAttachmentOptions, "updateBareMetalServerNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *createVPCRoutingTableOptions.VPCID, + "bare_metal_server_id": *updateBareMetalServerNetworkAttachmentOptions.BareMetalServerID, + "id": *updateBareMetalServerNetworkAttachmentOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPCRoutingTableOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBareMetalServerNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCRoutingTable") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateBareMetalServerNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createVPCRoutingTableOptions.AcceptRoutesFrom != nil { - body["accept_routes_from"] = createVPCRoutingTableOptions.AcceptRoutesFrom - } - if createVPCRoutingTableOptions.AdvertiseRoutesTo != nil { - body["advertise_routes_to"] = createVPCRoutingTableOptions.AdvertiseRoutesTo - } - if createVPCRoutingTableOptions.Name != nil { - body["name"] = createVPCRoutingTableOptions.Name - } - if createVPCRoutingTableOptions.RouteDirectLinkIngress != nil { - body["route_direct_link_ingress"] = createVPCRoutingTableOptions.RouteDirectLinkIngress - } - if createVPCRoutingTableOptions.RouteInternetIngress != nil { - body["route_internet_ingress"] = createVPCRoutingTableOptions.RouteInternetIngress - } - if createVPCRoutingTableOptions.RouteTransitGatewayIngress != nil { - body["route_transit_gateway_ingress"] = createVPCRoutingTableOptions.RouteTransitGatewayIngress - } - if createVPCRoutingTableOptions.RouteVPCZoneIngress != nil { - body["route_vpc_zone_ingress"] = createVPCRoutingTableOptions.RouteVPCZoneIngress - } - if createVPCRoutingTableOptions.Routes != nil { - body["routes"] = createVPCRoutingTableOptions.Routes - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(updateBareMetalServerNetworkAttachmentOptions.BareMetalServerNetworkAttachmentPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -2249,12 +2205,12 @@ func (vpc *VpcV1) CreateVPCRoutingTableWithContext(ctx context.Context, createVP var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpc_routing_table", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_bare_metal_server_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2265,56 +2221,65 @@ func (vpc *VpcV1) CreateVPCRoutingTableWithContext(ctx context.Context, createVP return } -// DeleteVPCRoutingTable : Delete a VPC routing table -// This request deletes a routing table. A routing table cannot be deleted if it is associated with any subnets in the -// VPC. Additionally, a VPC's default routing table cannot be deleted. This operation cannot be reversed. -func (vpc *VpcV1) DeleteVPCRoutingTable(deleteVPCRoutingTableOptions *DeleteVPCRoutingTableOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPCRoutingTableWithContext(context.Background(), deleteVPCRoutingTableOptions) +// ListBareMetalServerNetworkInterfaces : List network interfaces on a bare metal server +// This request lists network interfaces on a bare metal server. A bare metal server network interface is an abstract +// representation of a network device and attaches a bare metal server to a single subnet. Each network interface on a +// bare metal server can attach to any subnet in the zone, including subnets that are already attached to the bare metal +// server. +// +// If this bare metal server has network attachments, each returned network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface. +func (vpc *VpcV1) ListBareMetalServerNetworkInterfaces(listBareMetalServerNetworkInterfacesOptions *ListBareMetalServerNetworkInterfacesOptions) (result *BareMetalServerNetworkInterfaceCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBareMetalServerNetworkInterfacesWithContext(context.Background(), listBareMetalServerNetworkInterfacesOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPCRoutingTableWithContext is an alternate form of the DeleteVPCRoutingTable method which supports a Context parameter -func (vpc *VpcV1) DeleteVPCRoutingTableWithContext(ctx context.Context, deleteVPCRoutingTableOptions *DeleteVPCRoutingTableOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPCRoutingTableOptions, "deleteVPCRoutingTableOptions cannot be nil") +// ListBareMetalServerNetworkInterfacesWithContext is an alternate form of the ListBareMetalServerNetworkInterfaces method which supports a Context parameter +func (vpc *VpcV1) ListBareMetalServerNetworkInterfacesWithContext(ctx context.Context, listBareMetalServerNetworkInterfacesOptions *ListBareMetalServerNetworkInterfacesOptions) (result *BareMetalServerNetworkInterfaceCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listBareMetalServerNetworkInterfacesOptions, "listBareMetalServerNetworkInterfacesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPCRoutingTableOptions, "deleteVPCRoutingTableOptions") + err = core.ValidateStruct(listBareMetalServerNetworkInterfacesOptions, "listBareMetalServerNetworkInterfacesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *deleteVPCRoutingTableOptions.VPCID, - "id": *deleteVPCRoutingTableOptions.ID, + "bare_metal_server_id": *listBareMetalServerNetworkInterfacesOptions.BareMetalServerID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPCRoutingTableOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerNetworkInterfaces") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCRoutingTable") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBareMetalServerNetworkInterfacesOptions.Headers { builder.AddHeader(headerName, headerValue) } - if deleteVPCRoutingTableOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteVPCRoutingTableOptions.IfMatch)) - } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listBareMetalServerNetworkInterfacesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listBareMetalServerNetworkInterfacesOptions.Start)) + } + if listBareMetalServerNetworkInterfacesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listBareMetalServerNetworkInterfacesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -2322,64 +2287,87 @@ func (vpc *VpcV1) DeleteVPCRoutingTableWithContext(ctx context.Context, deleteVP return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpc_routing_table", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_bare_metal_server_network_interfaces", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkInterfaceCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetVPCRoutingTable : Retrieve a VPC routing table -// This request retrieves a single routing table specified by the identifier in the URL. -func (vpc *VpcV1) GetVPCRoutingTable(getVPCRoutingTableOptions *GetVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCRoutingTableWithContext(context.Background(), getVPCRoutingTableOptions) +// CreateBareMetalServerNetworkInterface : Create a network interface on a bare metal server +// This request creates a new bare metal server network interface from a bare metal server network interface prototype +// object. The prototype object is structured in the same way as a retrieved bare metal server network interface, and +// contains the information necessary to create the new bare metal server network interface. Any subnet in the bare +// metal server's VPC may be specified, even if it is already attached to another bare metal server network interface. +// Addresses on the bare metal server network interface must be within the specified subnet's CIDR blocks. +// +// If this bare metal server has network attachments, each network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface, and new network interfaces are not allowed to be created. +func (vpc *VpcV1) CreateBareMetalServerNetworkInterface(createBareMetalServerNetworkInterfaceOptions *CreateBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateBareMetalServerNetworkInterfaceWithContext(context.Background(), createBareMetalServerNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCRoutingTableWithContext is an alternate form of the GetVPCRoutingTable method which supports a Context parameter -func (vpc *VpcV1) GetVPCRoutingTableWithContext(ctx context.Context, getVPCRoutingTableOptions *GetVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPCRoutingTableOptions, "getVPCRoutingTableOptions cannot be nil") +// CreateBareMetalServerNetworkInterfaceWithContext is an alternate form of the CreateBareMetalServerNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) CreateBareMetalServerNetworkInterfaceWithContext(ctx context.Context, createBareMetalServerNetworkInterfaceOptions *CreateBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createBareMetalServerNetworkInterfaceOptions, "createBareMetalServerNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCRoutingTableOptions, "getVPCRoutingTableOptions") + err = core.ValidateStruct(createBareMetalServerNetworkInterfaceOptions, "createBareMetalServerNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *getVPCRoutingTableOptions.VPCID, - "id": *getVPCRoutingTableOptions.ID, + "bare_metal_server_id": *createBareMetalServerNetworkInterfaceOptions.BareMetalServerID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCRoutingTableOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBareMetalServerNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCRoutingTable") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createBareMetalServerNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(createBareMetalServerNetworkInterfaceOptions.BareMetalServerNetworkInterfacePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -2389,12 +2377,12 @@ func (vpc *VpcV1) GetVPCRoutingTableWithContext(ctx context.Context, getVPCRouti var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc_routing_table", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_bare_metal_server_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2405,64 +2393,126 @@ func (vpc *VpcV1) GetVPCRoutingTableWithContext(ctx context.Context, getVPCRouti return } -// UpdateVPCRoutingTable : Update a VPC routing table -// This request updates a routing table with the information in a provided routing table patch. The patch object is -// structured in the same way as a retrieved table and contains only the information to be updated. -func (vpc *VpcV1) UpdateVPCRoutingTable(updateVPCRoutingTableOptions *UpdateVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPCRoutingTableWithContext(context.Background(), updateVPCRoutingTableOptions) +// DeleteBareMetalServerNetworkInterface : Delete a bare metal server network interface +// This request deletes a bare metal server network interface. This operation cannot be reversed. Any floating IPs +// associated with the bare metal server network interface are implicitly disassociated. The primary bare metal server +// network interface is not allowed to be deleted. +// +// If this bare metal server has network attachments, this network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface, and is not allowed to be deleted. +func (vpc *VpcV1) DeleteBareMetalServerNetworkInterface(deleteBareMetalServerNetworkInterfaceOptions *DeleteBareMetalServerNetworkInterfaceOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteBareMetalServerNetworkInterfaceWithContext(context.Background(), deleteBareMetalServerNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPCRoutingTableWithContext is an alternate form of the UpdateVPCRoutingTable method which supports a Context parameter -func (vpc *VpcV1) UpdateVPCRoutingTableWithContext(ctx context.Context, updateVPCRoutingTableOptions *UpdateVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPCRoutingTableOptions, "updateVPCRoutingTableOptions cannot be nil") +// DeleteBareMetalServerNetworkInterfaceWithContext is an alternate form of the DeleteBareMetalServerNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) DeleteBareMetalServerNetworkInterfaceWithContext(ctx context.Context, deleteBareMetalServerNetworkInterfaceOptions *DeleteBareMetalServerNetworkInterfaceOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteBareMetalServerNetworkInterfaceOptions, "deleteBareMetalServerNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPCRoutingTableOptions, "updateVPCRoutingTableOptions") + err = core.ValidateStruct(deleteBareMetalServerNetworkInterfaceOptions, "deleteBareMetalServerNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *updateVPCRoutingTableOptions.VPCID, - "id": *updateVPCRoutingTableOptions.ID, + "bare_metal_server_id": *deleteBareMetalServerNetworkInterfaceOptions.BareMetalServerID, + "id": *deleteBareMetalServerNetworkInterfaceOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPCRoutingTableOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBareMetalServerNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCRoutingTable") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteBareMetalServerNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateVPCRoutingTableOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateVPCRoutingTableOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVPCRoutingTableOptions.RoutingTablePatch) + request, err := builder.Build() if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "delete_bare_metal_server_network_interface", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// GetBareMetalServerNetworkInterface : Retrieve a bare metal server network interface +// This request retrieves a single bare metal server network interface specified by the identifier in the URL. +// +// If this bare metal server has network attachments, the retrieved network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface. +func (vpc *VpcV1) GetBareMetalServerNetworkInterface(getBareMetalServerNetworkInterfaceOptions *GetBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBareMetalServerNetworkInterfaceWithContext(context.Background(), getBareMetalServerNetworkInterfaceOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetBareMetalServerNetworkInterfaceWithContext is an alternate form of the GetBareMetalServerNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceWithContext(ctx context.Context, getBareMetalServerNetworkInterfaceOptions *GetBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBareMetalServerNetworkInterfaceOptions, "getBareMetalServerNetworkInterfaceOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } + err = core.ValidateStruct(getBareMetalServerNetworkInterfaceOptions, "getBareMetalServerNetworkInterfaceOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "bare_metal_server_id": *getBareMetalServerNetworkInterfaceOptions.BareMetalServerID, + "id": *getBareMetalServerNetworkInterfaceOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerNetworkInterface") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range getBareMetalServerNetworkInterfaceOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) request, err := builder.Build() if err != nil { @@ -2473,12 +2523,12 @@ func (vpc *VpcV1) UpdateVPCRoutingTableWithContext(ctx context.Context, updateVP var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_vpc_routing_table", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_bare_metal_server_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2489,62 +2539,65 @@ func (vpc *VpcV1) UpdateVPCRoutingTableWithContext(ctx context.Context, updateVP return } -// ListVPCRoutingTableRoutes : List routes in a VPC routing table -// This request lists routes in a VPC routing table. If subnets are associated with this routing table, delivery of -// packets sent on a subnet is performed according to the action of the most specific matching route in the table -// (provided the subnet and route are in the same zone). If multiple equally-specific routes exist, the route with the -// highest priority will be used. If two matching routes have the same destination and priority, traffic will be -// distributed between them. If no routes match, delivery will be controlled by the system's built-in routes. -func (vpc *VpcV1) ListVPCRoutingTableRoutes(listVPCRoutingTableRoutesOptions *ListVPCRoutingTableRoutesOptions) (result *RouteCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPCRoutingTableRoutesWithContext(context.Background(), listVPCRoutingTableRoutesOptions) +// UpdateBareMetalServerNetworkInterface : Update a bare metal server network interface +// This request updates a bare metal server network interface with the information provided in a bare metal server +// network interface patch object. The bare metal server network interface patch object is structured in the same way as +// a retrieved bare metal server network interface and needs to contain only the information to be updated. +// +// If this bare metal server has network attachments, this network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface, and is not allowed to be updated. +func (vpc *VpcV1) UpdateBareMetalServerNetworkInterface(updateBareMetalServerNetworkInterfaceOptions *UpdateBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateBareMetalServerNetworkInterfaceWithContext(context.Background(), updateBareMetalServerNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPCRoutingTableRoutesWithContext is an alternate form of the ListVPCRoutingTableRoutes method which supports a Context parameter -func (vpc *VpcV1) ListVPCRoutingTableRoutesWithContext(ctx context.Context, listVPCRoutingTableRoutesOptions *ListVPCRoutingTableRoutesOptions) (result *RouteCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPCRoutingTableRoutesOptions, "listVPCRoutingTableRoutesOptions cannot be nil") +// UpdateBareMetalServerNetworkInterfaceWithContext is an alternate form of the UpdateBareMetalServerNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) UpdateBareMetalServerNetworkInterfaceWithContext(ctx context.Context, updateBareMetalServerNetworkInterfaceOptions *UpdateBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateBareMetalServerNetworkInterfaceOptions, "updateBareMetalServerNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPCRoutingTableRoutesOptions, "listVPCRoutingTableRoutesOptions") + err = core.ValidateStruct(updateBareMetalServerNetworkInterfaceOptions, "updateBareMetalServerNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *listVPCRoutingTableRoutesOptions.VPCID, - "routing_table_id": *listVPCRoutingTableRoutesOptions.RoutingTableID, + "bare_metal_server_id": *updateBareMetalServerNetworkInterfaceOptions.BareMetalServerID, + "id": *updateBareMetalServerNetworkInterfaceOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPCRoutingTableRoutesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBareMetalServerNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCRoutingTableRoutes") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateBareMetalServerNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPCRoutingTableRoutesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPCRoutingTableRoutesOptions.Start)) - } - if listVPCRoutingTableRoutesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPCRoutingTableRoutesOptions.Limit)) + + _, err = builder.SetBodyContentJSON(updateBareMetalServerNetworkInterfaceOptions.BareMetalServerNetworkInterfacePatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -2556,12 +2609,12 @@ func (vpc *VpcV1) ListVPCRoutingTableRoutesWithContext(ctx context.Context, list var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpc_routing_table_routes", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_bare_metal_server_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRouteCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2572,84 +2625,54 @@ func (vpc *VpcV1) ListVPCRoutingTableRoutesWithContext(ctx context.Context, list return } -// CreateVPCRoutingTableRoute : Create a route in a VPC routing table -// This request creates a new VPC route from a VPC route prototype object. The prototype object is structured in the -// same way as a retrieved VPC route and contains the information necessary to create the route. -func (vpc *VpcV1) CreateVPCRoutingTableRoute(createVPCRoutingTableRouteOptions *CreateVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPCRoutingTableRouteWithContext(context.Background(), createVPCRoutingTableRouteOptions) +// ListBareMetalServerNetworkInterfaceFloatingIps : List floating IPs associated with a bare metal server network interface +// This request lists floating IPs associated with a bare metal server network interface. +func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceFloatingIps(listBareMetalServerNetworkInterfaceFloatingIpsOptions *ListBareMetalServerNetworkInterfaceFloatingIpsOptions) (result *FloatingIPUnpaginatedCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBareMetalServerNetworkInterfaceFloatingIpsWithContext(context.Background(), listBareMetalServerNetworkInterfaceFloatingIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPCRoutingTableRouteWithContext is an alternate form of the CreateVPCRoutingTableRoute method which supports a Context parameter -func (vpc *VpcV1) CreateVPCRoutingTableRouteWithContext(ctx context.Context, createVPCRoutingTableRouteOptions *CreateVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVPCRoutingTableRouteOptions, "createVPCRoutingTableRouteOptions cannot be nil") +// ListBareMetalServerNetworkInterfaceFloatingIpsWithContext is an alternate form of the ListBareMetalServerNetworkInterfaceFloatingIps method which supports a Context parameter +func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceFloatingIpsWithContext(ctx context.Context, listBareMetalServerNetworkInterfaceFloatingIpsOptions *ListBareMetalServerNetworkInterfaceFloatingIpsOptions) (result *FloatingIPUnpaginatedCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listBareMetalServerNetworkInterfaceFloatingIpsOptions, "listBareMetalServerNetworkInterfaceFloatingIpsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVPCRoutingTableRouteOptions, "createVPCRoutingTableRouteOptions") + err = core.ValidateStruct(listBareMetalServerNetworkInterfaceFloatingIpsOptions, "listBareMetalServerNetworkInterfaceFloatingIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *createVPCRoutingTableRouteOptions.VPCID, - "routing_table_id": *createVPCRoutingTableRouteOptions.RoutingTableID, + "bare_metal_server_id": *listBareMetalServerNetworkInterfaceFloatingIpsOptions.BareMetalServerID, + "network_interface_id": *listBareMetalServerNetworkInterfaceFloatingIpsOptions.NetworkInterfaceID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/floating_ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPCRoutingTableRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerNetworkInterfaceFloatingIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCRoutingTableRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBareMetalServerNetworkInterfaceFloatingIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createVPCRoutingTableRouteOptions.Destination != nil { - body["destination"] = createVPCRoutingTableRouteOptions.Destination - } - if createVPCRoutingTableRouteOptions.Zone != nil { - body["zone"] = createVPCRoutingTableRouteOptions.Zone - } - if createVPCRoutingTableRouteOptions.Action != nil { - body["action"] = createVPCRoutingTableRouteOptions.Action - } - if createVPCRoutingTableRouteOptions.Advertise != nil { - body["advertise"] = createVPCRoutingTableRouteOptions.Advertise - } - if createVPCRoutingTableRouteOptions.Name != nil { - body["name"] = createVPCRoutingTableRouteOptions.Name - } - if createVPCRoutingTableRouteOptions.NextHop != nil { - body["next_hop"] = createVPCRoutingTableRouteOptions.NextHop - } - if createVPCRoutingTableRouteOptions.Priority != nil { - body["priority"] = createVPCRoutingTableRouteOptions.Priority - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -2659,12 +2682,12 @@ func (vpc *VpcV1) CreateVPCRoutingTableRouteWithContext(ctx context.Context, cre var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpc_routing_table_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_bare_metal_server_network_interface_floating_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPUnpaginatedCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2675,49 +2698,48 @@ func (vpc *VpcV1) CreateVPCRoutingTableRouteWithContext(ctx context.Context, cre return } -// DeleteVPCRoutingTableRoute : Delete a VPC routing table route -// This request deletes a VPC route. This operation cannot be reversed. Only VPC routes with an `origin` of `user` are -// allowed to be deleted. -func (vpc *VpcV1) DeleteVPCRoutingTableRoute(deleteVPCRoutingTableRouteOptions *DeleteVPCRoutingTableRouteOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPCRoutingTableRouteWithContext(context.Background(), deleteVPCRoutingTableRouteOptions) +// RemoveBareMetalServerNetworkInterfaceFloatingIP : Disassociate a floating IP from a bare metal server network interface +// This request disassociates the specified floating IP from the specified bare metal server network interface. +func (vpc *VpcV1) RemoveBareMetalServerNetworkInterfaceFloatingIP(removeBareMetalServerNetworkInterfaceFloatingIPOptions *RemoveBareMetalServerNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RemoveBareMetalServerNetworkInterfaceFloatingIPWithContext(context.Background(), removeBareMetalServerNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPCRoutingTableRouteWithContext is an alternate form of the DeleteVPCRoutingTableRoute method which supports a Context parameter -func (vpc *VpcV1) DeleteVPCRoutingTableRouteWithContext(ctx context.Context, deleteVPCRoutingTableRouteOptions *DeleteVPCRoutingTableRouteOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPCRoutingTableRouteOptions, "deleteVPCRoutingTableRouteOptions cannot be nil") +// RemoveBareMetalServerNetworkInterfaceFloatingIPWithContext is an alternate form of the RemoveBareMetalServerNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) RemoveBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx context.Context, removeBareMetalServerNetworkInterfaceFloatingIPOptions *RemoveBareMetalServerNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(removeBareMetalServerNetworkInterfaceFloatingIPOptions, "removeBareMetalServerNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPCRoutingTableRouteOptions, "deleteVPCRoutingTableRouteOptions") + err = core.ValidateStruct(removeBareMetalServerNetworkInterfaceFloatingIPOptions, "removeBareMetalServerNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *deleteVPCRoutingTableRouteOptions.VPCID, - "routing_table_id": *deleteVPCRoutingTableRouteOptions.RoutingTableID, - "id": *deleteVPCRoutingTableRouteOptions.ID, + "bare_metal_server_id": *removeBareMetalServerNetworkInterfaceFloatingIPOptions.BareMetalServerID, + "network_interface_id": *removeBareMetalServerNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, + "id": *removeBareMetalServerNetworkInterfaceFloatingIPOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPCRoutingTableRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveBareMetalServerNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCRoutingTableRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range removeBareMetalServerNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -2732,7 +2754,7 @@ func (vpc *VpcV1) DeleteVPCRoutingTableRouteWithContext(ctx context.Context, del response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpc_routing_table_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "remove_bare_metal_server_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -2740,48 +2762,49 @@ func (vpc *VpcV1) DeleteVPCRoutingTableRouteWithContext(ctx context.Context, del return } -// GetVPCRoutingTableRoute : Retrieve a VPC routing table route -// This request retrieves a single VPC route specified by the identifier in the URL path. -func (vpc *VpcV1) GetVPCRoutingTableRoute(getVPCRoutingTableRouteOptions *GetVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPCRoutingTableRouteWithContext(context.Background(), getVPCRoutingTableRouteOptions) +// GetBareMetalServerNetworkInterfaceFloatingIP : Retrieve associated floating IP +// This request retrieves a specified floating IP if it is associated with the bare metal server network interface +// specified in the URL. +func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceFloatingIP(getBareMetalServerNetworkInterfaceFloatingIPOptions *GetBareMetalServerNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBareMetalServerNetworkInterfaceFloatingIPWithContext(context.Background(), getBareMetalServerNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPCRoutingTableRouteWithContext is an alternate form of the GetVPCRoutingTableRoute method which supports a Context parameter -func (vpc *VpcV1) GetVPCRoutingTableRouteWithContext(ctx context.Context, getVPCRoutingTableRouteOptions *GetVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPCRoutingTableRouteOptions, "getVPCRoutingTableRouteOptions cannot be nil") +// GetBareMetalServerNetworkInterfaceFloatingIPWithContext is an alternate form of the GetBareMetalServerNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx context.Context, getBareMetalServerNetworkInterfaceFloatingIPOptions *GetBareMetalServerNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBareMetalServerNetworkInterfaceFloatingIPOptions, "getBareMetalServerNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPCRoutingTableRouteOptions, "getVPCRoutingTableRouteOptions") + err = core.ValidateStruct(getBareMetalServerNetworkInterfaceFloatingIPOptions, "getBareMetalServerNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *getVPCRoutingTableRouteOptions.VPCID, - "routing_table_id": *getVPCRoutingTableRouteOptions.RoutingTableID, - "id": *getVPCRoutingTableRouteOptions.ID, + "bare_metal_server_id": *getBareMetalServerNetworkInterfaceFloatingIPOptions.BareMetalServerID, + "network_interface_id": *getBareMetalServerNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, + "id": *getBareMetalServerNetworkInterfaceFloatingIPOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPCRoutingTableRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCRoutingTableRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBareMetalServerNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -2798,12 +2821,12 @@ func (vpc *VpcV1) GetVPCRoutingTableRouteWithContext(ctx context.Context, getVPC var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpc_routing_table_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_bare_metal_server_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2814,64 +2837,63 @@ func (vpc *VpcV1) GetVPCRoutingTableRouteWithContext(ctx context.Context, getVPC return } -// UpdateVPCRoutingTableRoute : Update a VPC routing table route -// This request updates a VPC route with the information provided in a route patch object. The patch object is -// structured in the same way as a retrieved VPC route and needs to contain only the information to be updated. Only VPC -// routes with an `origin` of `user` are allowed to be updated. -func (vpc *VpcV1) UpdateVPCRoutingTableRoute(updateVPCRoutingTableRouteOptions *UpdateVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPCRoutingTableRouteWithContext(context.Background(), updateVPCRoutingTableRouteOptions) +// AddBareMetalServerNetworkInterfaceFloatingIP : Associate a floating IP with a bare metal server network interface +// This request associates the specified floating IP with the specified bare metal server network interface. If +// `enable_infrastructure_nat` is `false`, this adds the IP to any existing associations. If `enable_infrastructure_nat` +// is `true`, this replaces any existing association. +// +// The existing floating IP must: +// - not be required by another resource, such as a public gateway +// - be in the same `zone` as the bare metal server +// +// A request body is not required, and if provided, is ignored. +func (vpc *VpcV1) AddBareMetalServerNetworkInterfaceFloatingIP(addBareMetalServerNetworkInterfaceFloatingIPOptions *AddBareMetalServerNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.AddBareMetalServerNetworkInterfaceFloatingIPWithContext(context.Background(), addBareMetalServerNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPCRoutingTableRouteWithContext is an alternate form of the UpdateVPCRoutingTableRoute method which supports a Context parameter -func (vpc *VpcV1) UpdateVPCRoutingTableRouteWithContext(ctx context.Context, updateVPCRoutingTableRouteOptions *UpdateVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPCRoutingTableRouteOptions, "updateVPCRoutingTableRouteOptions cannot be nil") +// AddBareMetalServerNetworkInterfaceFloatingIPWithContext is an alternate form of the AddBareMetalServerNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) AddBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx context.Context, addBareMetalServerNetworkInterfaceFloatingIPOptions *AddBareMetalServerNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(addBareMetalServerNetworkInterfaceFloatingIPOptions, "addBareMetalServerNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPCRoutingTableRouteOptions, "updateVPCRoutingTableRouteOptions") + err = core.ValidateStruct(addBareMetalServerNetworkInterfaceFloatingIPOptions, "addBareMetalServerNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpc_id": *updateVPCRoutingTableRouteOptions.VPCID, - "routing_table_id": *updateVPCRoutingTableRouteOptions.RoutingTableID, - "id": *updateVPCRoutingTableRouteOptions.ID, + "bare_metal_server_id": *addBareMetalServerNetworkInterfaceFloatingIPOptions.BareMetalServerID, + "network_interface_id": *addBareMetalServerNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, + "id": *addBareMetalServerNetworkInterfaceFloatingIPOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPCRoutingTableRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddBareMetalServerNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCRoutingTableRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range addBareMetalServerNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVPCRoutingTableRouteOptions.RoutePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -2881,12 +2903,12 @@ func (vpc *VpcV1) UpdateVPCRoutingTableRouteWithContext(ctx context.Context, upd var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_vpc_routing_table_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "add_bare_metal_server_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2897,71 +2919,56 @@ func (vpc *VpcV1) UpdateVPCRoutingTableRouteWithContext(ctx context.Context, upd return } -// ListSubnets : List subnets -// This request lists subnets in the region. Subnets are contiguous ranges of IP addresses specified in CIDR block -// notation. Each subnet is within a particular zone and cannot span multiple zones or regions. -func (vpc *VpcV1) ListSubnets(listSubnetsOptions *ListSubnetsOptions) (result *SubnetCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSubnetsWithContext(context.Background(), listSubnetsOptions) +// ListBareMetalServerNetworkInterfaceIps : List the primary reserved IP for a bare metal server network interface +// This request lists the primary reserved IP for a bare metal server network interface. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceIps(listBareMetalServerNetworkInterfaceIpsOptions *ListBareMetalServerNetworkInterfaceIpsOptions) (result *ReservedIPCollectionBareMetalServerNetworkInterfaceContext, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListBareMetalServerNetworkInterfaceIpsWithContext(context.Background(), listBareMetalServerNetworkInterfaceIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSubnetsWithContext is an alternate form of the ListSubnets method which supports a Context parameter -func (vpc *VpcV1) ListSubnetsWithContext(ctx context.Context, listSubnetsOptions *ListSubnetsOptions) (result *SubnetCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listSubnetsOptions, "listSubnetsOptions") +// ListBareMetalServerNetworkInterfaceIpsWithContext is an alternate form of the ListBareMetalServerNetworkInterfaceIps method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceIpsWithContext(ctx context.Context, listBareMetalServerNetworkInterfaceIpsOptions *ListBareMetalServerNetworkInterfaceIpsOptions) (result *ReservedIPCollectionBareMetalServerNetworkInterfaceContext, response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: ListBareMetalServerNetworkInterfaceIps") + err = core.ValidateNotNil(listBareMetalServerNetworkInterfaceIpsOptions, "listBareMetalServerNetworkInterfaceIpsOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listBareMetalServerNetworkInterfaceIpsOptions, "listBareMetalServerNetworkInterfaceIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "bare_metal_server_id": *listBareMetalServerNetworkInterfaceIpsOptions.BareMetalServerID, + "network_interface_id": *listBareMetalServerNetworkInterfaceIpsOptions.NetworkInterfaceID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSubnetsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerNetworkInterfaceIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSubnets") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listBareMetalServerNetworkInterfaceIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listSubnetsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listSubnetsOptions.Start)) - } - if listSubnetsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listSubnetsOptions.Limit)) - } - if listSubnetsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listSubnetsOptions.ResourceGroupID)) - } - if listSubnetsOptions.ZoneName != nil { - builder.AddQuery("zone.name", fmt.Sprint(*listSubnetsOptions.ZoneName)) - } - if listSubnetsOptions.VPCID != nil { - builder.AddQuery("vpc.id", fmt.Sprint(*listSubnetsOptions.VPCID)) - } - if listSubnetsOptions.VPCCRN != nil { - builder.AddQuery("vpc.crn", fmt.Sprint(*listSubnetsOptions.VPCCRN)) - } - if listSubnetsOptions.VPCName != nil { - builder.AddQuery("vpc.name", fmt.Sprint(*listSubnetsOptions.VPCName)) - } - if listSubnetsOptions.RoutingTableID != nil { - builder.AddQuery("routing_table.id", fmt.Sprint(*listSubnetsOptions.RoutingTableID)) - } - if listSubnetsOptions.RoutingTableName != nil { - builder.AddQuery("routing_table.name", fmt.Sprint(*listSubnetsOptions.RoutingTableName)) - } request, err := builder.Build() if err != nil { @@ -2972,12 +2979,12 @@ func (vpc *VpcV1) ListSubnetsWithContext(ctx context.Context, listSubnetsOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_subnets", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_bare_metal_server_network_interface_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSubnetCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollectionBareMetalServerNetworkInterfaceContext) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -2988,58 +2995,58 @@ func (vpc *VpcV1) ListSubnetsWithContext(ctx context.Context, listSubnetsOptions return } -// CreateSubnet : Create a subnet -// This request creates a new subnet from a subnet prototype object. The prototype object is structured in the same way -// as a retrieved subnet, and contains the information necessary to create the new subnet. For this request to succeed, -// the prototype's CIDR block must not overlap with an existing subnet in the VPC. -func (vpc *VpcV1) CreateSubnet(createSubnetOptions *CreateSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateSubnetWithContext(context.Background(), createSubnetOptions) +// GetBareMetalServerNetworkInterfaceIP : Retrieve the primary reserved IP +// This request retrieves the primary reserved IP for a bare metal server network interface. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceIP(getBareMetalServerNetworkInterfaceIPOptions *GetBareMetalServerNetworkInterfaceIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBareMetalServerNetworkInterfaceIPWithContext(context.Background(), getBareMetalServerNetworkInterfaceIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateSubnetWithContext is an alternate form of the CreateSubnet method which supports a Context parameter -func (vpc *VpcV1) CreateSubnetWithContext(ctx context.Context, createSubnetOptions *CreateSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createSubnetOptions, "createSubnetOptions cannot be nil") +// GetBareMetalServerNetworkInterfaceIPWithContext is an alternate form of the GetBareMetalServerNetworkInterfaceIP method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceIPWithContext(ctx context.Context, getBareMetalServerNetworkInterfaceIPOptions *GetBareMetalServerNetworkInterfaceIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: GetBareMetalServerNetworkInterfaceIP") + err = core.ValidateNotNil(getBareMetalServerNetworkInterfaceIPOptions, "getBareMetalServerNetworkInterfaceIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createSubnetOptions, "createSubnetOptions") + err = core.ValidateStruct(getBareMetalServerNetworkInterfaceIPOptions, "getBareMetalServerNetworkInterfaceIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "bare_metal_server_id": *getBareMetalServerNetworkInterfaceIPOptions.BareMetalServerID, + "network_interface_id": *getBareMetalServerNetworkInterfaceIPOptions.NetworkInterfaceID, + "id": *getBareMetalServerNetworkInterfaceIPOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createSubnetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerNetworkInterfaceIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSubnet") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBareMetalServerNetworkInterfaceIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createSubnetOptions.SubnetPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -3049,12 +3056,12 @@ func (vpc *VpcV1) CreateSubnetWithContext(ctx context.Context, createSubnetOptio var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_subnet", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_bare_metal_server_network_interface_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSubnet) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3065,50 +3072,47 @@ func (vpc *VpcV1) CreateSubnetWithContext(ctx context.Context, createSubnetOptio return } -// DeleteSubnet : Delete a subnet -// This request deletes a subnet. This operation cannot be reversed. For this request to succeed, the subnet must not be -// referenced by any bare metal server network interfaces, instance network interfaces, virtual network interfaces, VPN -// gateways, or load balancers. A delete operation automatically detaches the subnet from any network ACLs, public -// gateways, or endpoint gateways. All flow log collectors with `auto_delete` set to `true` targeting the subnet or any -// resource in the subnet are automatically deleted. -func (vpc *VpcV1) DeleteSubnet(deleteSubnetOptions *DeleteSubnetOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteSubnetWithContext(context.Background(), deleteSubnetOptions) +// DeleteBareMetalServer : Delete a bare metal server +// This request deletes a bare metal server. This operation cannot be reversed. Any floating IPs associated with the +// bare metal server network interfaces are implicitly disassociated. +func (vpc *VpcV1) DeleteBareMetalServer(deleteBareMetalServerOptions *DeleteBareMetalServerOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteBareMetalServerWithContext(context.Background(), deleteBareMetalServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSubnetWithContext is an alternate form of the DeleteSubnet method which supports a Context parameter -func (vpc *VpcV1) DeleteSubnetWithContext(ctx context.Context, deleteSubnetOptions *DeleteSubnetOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSubnetOptions, "deleteSubnetOptions cannot be nil") +// DeleteBareMetalServerWithContext is an alternate form of the DeleteBareMetalServer method which supports a Context parameter +func (vpc *VpcV1) DeleteBareMetalServerWithContext(ctx context.Context, deleteBareMetalServerOptions *DeleteBareMetalServerOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteBareMetalServerOptions, "deleteBareMetalServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSubnetOptions, "deleteSubnetOptions") + err = core.ValidateStruct(deleteBareMetalServerOptions, "deleteBareMetalServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteSubnetOptions.ID, + "id": *deleteBareMetalServerOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSubnetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBareMetalServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSubnet") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteBareMetalServerOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -3123,7 +3127,7 @@ func (vpc *VpcV1) DeleteSubnetWithContext(ctx context.Context, deleteSubnetOptio response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_subnet", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_bare_metal_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -3131,46 +3135,46 @@ func (vpc *VpcV1) DeleteSubnetWithContext(ctx context.Context, deleteSubnetOptio return } -// GetSubnet : Retrieve a subnet -// This request retrieves a single subnet specified by the identifier in the URL. -func (vpc *VpcV1) GetSubnet(getSubnetOptions *GetSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSubnetWithContext(context.Background(), getSubnetOptions) +// GetBareMetalServer : Retrieve a bare metal server +// This request retrieves a single bare metal server specified by the identifier in the URL. +func (vpc *VpcV1) GetBareMetalServer(getBareMetalServerOptions *GetBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBareMetalServerWithContext(context.Background(), getBareMetalServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSubnetWithContext is an alternate form of the GetSubnet method which supports a Context parameter -func (vpc *VpcV1) GetSubnetWithContext(ctx context.Context, getSubnetOptions *GetSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSubnetOptions, "getSubnetOptions cannot be nil") +// GetBareMetalServerWithContext is an alternate form of the GetBareMetalServer method which supports a Context parameter +func (vpc *VpcV1) GetBareMetalServerWithContext(ctx context.Context, getBareMetalServerOptions *GetBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBareMetalServerOptions, "getBareMetalServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSubnetOptions, "getSubnetOptions") + err = core.ValidateStruct(getBareMetalServerOptions, "getBareMetalServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getSubnetOptions.ID, + "id": *getBareMetalServerOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSubnetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnet") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getBareMetalServerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3187,12 +3191,12 @@ func (vpc *VpcV1) GetSubnetWithContext(ctx context.Context, getSubnetOptions *Ge var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_subnet", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_bare_metal_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSubnet) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3203,47 +3207,50 @@ func (vpc *VpcV1) GetSubnetWithContext(ctx context.Context, getSubnetOptions *Ge return } -// UpdateSubnet : Update a subnet -// This request updates a subnet with the information in a provided subnet patch. The subnet patch object is structured -// in the same way as a retrieved subnet and contains only the information to be updated. -func (vpc *VpcV1) UpdateSubnet(updateSubnetOptions *UpdateSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateSubnetWithContext(context.Background(), updateSubnetOptions) +// UpdateBareMetalServer : Update a bare metal server +// This request updates a bare metal server with the information in a provided patch. The bare metal server patch object +// is structured in the same way as a retrieved bare metal server and contains only the information to be updated. +// +// For this request to succeed, the properties in the request must adhere to the `allowed_use` property of the disk +// referenced in the server's `boot_target`. +func (vpc *VpcV1) UpdateBareMetalServer(updateBareMetalServerOptions *UpdateBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateBareMetalServerWithContext(context.Background(), updateBareMetalServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateSubnetWithContext is an alternate form of the UpdateSubnet method which supports a Context parameter -func (vpc *VpcV1) UpdateSubnetWithContext(ctx context.Context, updateSubnetOptions *UpdateSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateSubnetOptions, "updateSubnetOptions cannot be nil") +// UpdateBareMetalServerWithContext is an alternate form of the UpdateBareMetalServer method which supports a Context parameter +func (vpc *VpcV1) UpdateBareMetalServerWithContext(ctx context.Context, updateBareMetalServerOptions *UpdateBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateBareMetalServerOptions, "updateBareMetalServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateSubnetOptions, "updateSubnetOptions") + err = core.ValidateStruct(updateBareMetalServerOptions, "updateBareMetalServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateSubnetOptions.ID, + "id": *updateBareMetalServerOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateSubnetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBareMetalServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSubnet") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateBareMetalServerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3252,7 +3259,7 @@ func (vpc *VpcV1) UpdateSubnetWithContext(ctx context.Context, updateSubnetOptio builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateSubnetOptions.SubnetPatch) + _, err = builder.SetBodyContentJSON(updateBareMetalServerOptions.BareMetalServerPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -3267,12 +3274,12 @@ func (vpc *VpcV1) UpdateSubnetWithContext(ctx context.Context, updateSubnetOptio var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_subnet", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_bare_metal_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSubnet) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3283,127 +3290,219 @@ func (vpc *VpcV1) UpdateSubnetWithContext(ctx context.Context, updateSubnetOptio return } -// GetSubnetNetworkACL : Retrieve a subnet's attached network ACL -// This request retrieves the network ACL attached to the subnet specified by the identifier in the URL. -func (vpc *VpcV1) GetSubnetNetworkACL(getSubnetNetworkACLOptions *GetSubnetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSubnetNetworkACLWithContext(context.Background(), getSubnetNetworkACLOptions) +// UpdateFirmwareForBareMetalServer : Update firmware for a bare metal server +// This request updates a bare metal server to the latest available firmware. The server must be stopped. +func (vpc *VpcV1) UpdateFirmwareForBareMetalServer(updateFirmwareForBareMetalServerOptions *UpdateFirmwareForBareMetalServerOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.UpdateFirmwareForBareMetalServerWithContext(context.Background(), updateFirmwareForBareMetalServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSubnetNetworkACLWithContext is an alternate form of the GetSubnetNetworkACL method which supports a Context parameter -func (vpc *VpcV1) GetSubnetNetworkACLWithContext(ctx context.Context, getSubnetNetworkACLOptions *GetSubnetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSubnetNetworkACLOptions, "getSubnetNetworkACLOptions cannot be nil") +// UpdateFirmwareForBareMetalServerWithContext is an alternate form of the UpdateFirmwareForBareMetalServer method which supports a Context parameter +func (vpc *VpcV1) UpdateFirmwareForBareMetalServerWithContext(ctx context.Context, updateFirmwareForBareMetalServerOptions *UpdateFirmwareForBareMetalServerOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateFirmwareForBareMetalServerOptions, "updateFirmwareForBareMetalServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSubnetNetworkACLOptions, "getSubnetNetworkACLOptions") + err = core.ValidateStruct(updateFirmwareForBareMetalServerOptions, "updateFirmwareForBareMetalServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getSubnetNetworkACLOptions.ID, + "id": *updateFirmwareForBareMetalServerOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/network_acl`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/firmware/update`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSubnetNetworkACLOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateFirmwareForBareMetalServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnetNetworkACL") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateFirmwareForBareMetalServerOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if updateFirmwareForBareMetalServerOptions.AutoStart != nil { + body["auto_start"] = updateFirmwareForBareMetalServerOptions.AutoStart + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_subnet_network_acl", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_firmware_for_bare_metal_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ReplaceSubnetNetworkACL : Replace the network ACL for a subnet -// This request replaces the existing network ACL for a subnet with the network ACL specified in the request body. -func (vpc *VpcV1) ReplaceSubnetNetworkACL(replaceSubnetNetworkACLOptions *ReplaceSubnetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - result, response, err = vpc.ReplaceSubnetNetworkACLWithContext(context.Background(), replaceSubnetNetworkACLOptions) +// GetBareMetalServerInitialization : Retrieve initialization configuration for a bare metal server +// This request retrieves configuration used to initialize the bare metal server, such as the image used, SSH keys, and +// any configured usernames and passwords. These can subsequently be changed on the server and therefore may not be +// current. +func (vpc *VpcV1) GetBareMetalServerInitialization(getBareMetalServerInitializationOptions *GetBareMetalServerInitializationOptions) (result *BareMetalServerInitialization, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetBareMetalServerInitializationWithContext(context.Background(), getBareMetalServerInitializationOptions) err = core.RepurposeSDKProblem(err, "") return } -// ReplaceSubnetNetworkACLWithContext is an alternate form of the ReplaceSubnetNetworkACL method which supports a Context parameter -func (vpc *VpcV1) ReplaceSubnetNetworkACLWithContext(ctx context.Context, replaceSubnetNetworkACLOptions *ReplaceSubnetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(replaceSubnetNetworkACLOptions, "replaceSubnetNetworkACLOptions cannot be nil") +// GetBareMetalServerInitializationWithContext is an alternate form of the GetBareMetalServerInitialization method which supports a Context parameter +func (vpc *VpcV1) GetBareMetalServerInitializationWithContext(ctx context.Context, getBareMetalServerInitializationOptions *GetBareMetalServerInitializationOptions) (result *BareMetalServerInitialization, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getBareMetalServerInitializationOptions, "getBareMetalServerInitializationOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(replaceSubnetNetworkACLOptions, "replaceSubnetNetworkACLOptions") + err = core.ValidateStruct(getBareMetalServerInitializationOptions, "getBareMetalServerInitializationOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *replaceSubnetNetworkACLOptions.ID, + "id": *getBareMetalServerInitializationOptions.ID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/network_acl`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/initialization`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range replaceSubnetNetworkACLOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerInitialization") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ReplaceSubnetNetworkACL") + for headerName, headerValue := range getBareMetalServerInitializationOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "get_bare_metal_server_initialization", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerInitialization) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// ReplaceBareMetalServerInitialization : Reinitialize a bare metal server +// This request reinitializes a bare metal server with the specified image and SSH keys. The server must be stopped. +// Upon successful reinitiatilization, the bare metal server will be started automatically. +// +// For this request to succeed, the properties of the server which would result from the reinitialization must adhere to +// the specified image's `allowed_use` property. +func (vpc *VpcV1) ReplaceBareMetalServerInitialization(replaceBareMetalServerInitializationOptions *ReplaceBareMetalServerInitializationOptions) (result *BareMetalServerInitialization, response *core.DetailedResponse, err error) { + result, response, err = vpc.ReplaceBareMetalServerInitializationWithContext(context.Background(), replaceBareMetalServerInitializationOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ReplaceBareMetalServerInitializationWithContext is an alternate form of the ReplaceBareMetalServerInitialization method which supports a Context parameter +func (vpc *VpcV1) ReplaceBareMetalServerInitializationWithContext(ctx context.Context, replaceBareMetalServerInitializationOptions *ReplaceBareMetalServerInitializationOptions) (result *BareMetalServerInitialization, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(replaceBareMetalServerInitializationOptions, "replaceBareMetalServerInitializationOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(replaceBareMetalServerInitializationOptions, "replaceBareMetalServerInitializationOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "id": *replaceBareMetalServerInitializationOptions.ID, + } + + builder := core.NewRequestBuilder(core.PUT) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/initialization`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ReplaceBareMetalServerInitialization") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range replaceBareMetalServerInitializationOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(replaceSubnetNetworkACLOptions.NetworkACLIdentity) + body := make(map[string]interface{}) + if replaceBareMetalServerInitializationOptions.Image != nil { + body["image"] = replaceBareMetalServerInitializationOptions.Image + } + if replaceBareMetalServerInitializationOptions.Keys != nil { + body["keys"] = replaceBareMetalServerInitializationOptions.Keys + } + if replaceBareMetalServerInitializationOptions.DefaultTrustedProfile != nil { + body["default_trusted_profile"] = replaceBareMetalServerInitializationOptions.DefaultTrustedProfile + } + if replaceBareMetalServerInitializationOptions.UserData != nil { + body["user_data"] = replaceBareMetalServerInitializationOptions.UserData + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -3418,12 +3517,12 @@ func (vpc *VpcV1) ReplaceSubnetNetworkACLWithContext(ctx context.Context, replac var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "replace_subnet_network_acl", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "replace_bare_metal_server_initialization", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerInitialization) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3434,46 +3533,47 @@ func (vpc *VpcV1) ReplaceSubnetNetworkACLWithContext(ctx context.Context, replac return } -// UnsetSubnetPublicGateway : Detach a public gateway from a subnet -// This request detaches the public gateway from the subnet specified by the subnet identifier in the URL. -func (vpc *VpcV1) UnsetSubnetPublicGateway(unsetSubnetPublicGatewayOptions *UnsetSubnetPublicGatewayOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.UnsetSubnetPublicGatewayWithContext(context.Background(), unsetSubnetPublicGatewayOptions) +// RestartBareMetalServer : Restart a bare metal server +// This request immediately restarts a bare metal server. For this request to succeed, the server must have a `status` +// of `running`. +func (vpc *VpcV1) RestartBareMetalServer(restartBareMetalServerOptions *RestartBareMetalServerOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RestartBareMetalServerWithContext(context.Background(), restartBareMetalServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// UnsetSubnetPublicGatewayWithContext is an alternate form of the UnsetSubnetPublicGateway method which supports a Context parameter -func (vpc *VpcV1) UnsetSubnetPublicGatewayWithContext(ctx context.Context, unsetSubnetPublicGatewayOptions *UnsetSubnetPublicGatewayOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(unsetSubnetPublicGatewayOptions, "unsetSubnetPublicGatewayOptions cannot be nil") +// RestartBareMetalServerWithContext is an alternate form of the RestartBareMetalServer method which supports a Context parameter +func (vpc *VpcV1) RestartBareMetalServerWithContext(ctx context.Context, restartBareMetalServerOptions *RestartBareMetalServerOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(restartBareMetalServerOptions, "restartBareMetalServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(unsetSubnetPublicGatewayOptions, "unsetSubnetPublicGatewayOptions") + err = core.ValidateStruct(restartBareMetalServerOptions, "restartBareMetalServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *unsetSubnetPublicGatewayOptions.ID, + "id": *restartBareMetalServerOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/public_gateway`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/restart`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range unsetSubnetPublicGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RestartBareMetalServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UnsetSubnetPublicGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range restartBareMetalServerOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -3488,7 +3588,7 @@ func (vpc *VpcV1) UnsetSubnetPublicGatewayWithContext(ctx context.Context, unset response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "unset_subnet_public_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "restart_bare_metal_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -3496,49 +3596,48 @@ func (vpc *VpcV1) UnsetSubnetPublicGatewayWithContext(ctx context.Context, unset return } -// GetSubnetPublicGateway : Retrieve a subnet's attached public gateway -// This request retrieves the public gateway attached to the subnet specified by the identifier in the URL. -func (vpc *VpcV1) GetSubnetPublicGateway(getSubnetPublicGatewayOptions *GetSubnetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSubnetPublicGatewayWithContext(context.Background(), getSubnetPublicGatewayOptions) +// StartBareMetalServer : Start a bare metal server +// This request starts a bare metal server. It will run immediately provided the server is stopped. +func (vpc *VpcV1) StartBareMetalServer(startBareMetalServerOptions *StartBareMetalServerOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.StartBareMetalServerWithContext(context.Background(), startBareMetalServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSubnetPublicGatewayWithContext is an alternate form of the GetSubnetPublicGateway method which supports a Context parameter -func (vpc *VpcV1) GetSubnetPublicGatewayWithContext(ctx context.Context, getSubnetPublicGatewayOptions *GetSubnetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSubnetPublicGatewayOptions, "getSubnetPublicGatewayOptions cannot be nil") +// StartBareMetalServerWithContext is an alternate form of the StartBareMetalServer method which supports a Context parameter +func (vpc *VpcV1) StartBareMetalServerWithContext(ctx context.Context, startBareMetalServerOptions *StartBareMetalServerOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(startBareMetalServerOptions, "startBareMetalServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSubnetPublicGatewayOptions, "getSubnetPublicGatewayOptions") + err = core.ValidateStruct(startBareMetalServerOptions, "startBareMetalServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getSubnetPublicGatewayOptions.ID, + "id": *startBareMetalServerOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/public_gateway`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/start`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSubnetPublicGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "StartBareMetalServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnetPublicGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range startBareMetalServerOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -3549,75 +3648,69 @@ func (vpc *VpcV1) GetSubnetPublicGatewayWithContext(ctx context.Context, getSubn return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_subnet_public_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "start_bare_metal_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// SetSubnetPublicGateway : Attach a public gateway to a subnet -// This request attaches the public gateway, specified in the request body, to the subnet specified by the subnet -// identifier in the URL. The public gateway must have the same VPC and zone as the subnet. -func (vpc *VpcV1) SetSubnetPublicGateway(setSubnetPublicGatewayOptions *SetSubnetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.SetSubnetPublicGatewayWithContext(context.Background(), setSubnetPublicGatewayOptions) +// StopBareMetalServer : Stop a bare metal server +// This request stops a bare metal server. It will run immediately provided the server is running. Note: A soft stop may +// not complete as it relies on the operating system to perform the operation. +func (vpc *VpcV1) StopBareMetalServer(stopBareMetalServerOptions *StopBareMetalServerOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.StopBareMetalServerWithContext(context.Background(), stopBareMetalServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// SetSubnetPublicGatewayWithContext is an alternate form of the SetSubnetPublicGateway method which supports a Context parameter -func (vpc *VpcV1) SetSubnetPublicGatewayWithContext(ctx context.Context, setSubnetPublicGatewayOptions *SetSubnetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(setSubnetPublicGatewayOptions, "setSubnetPublicGatewayOptions cannot be nil") +// StopBareMetalServerWithContext is an alternate form of the StopBareMetalServer method which supports a Context parameter +func (vpc *VpcV1) StopBareMetalServerWithContext(ctx context.Context, stopBareMetalServerOptions *StopBareMetalServerOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(stopBareMetalServerOptions, "stopBareMetalServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(setSubnetPublicGatewayOptions, "setSubnetPublicGatewayOptions") + err = core.ValidateStruct(stopBareMetalServerOptions, "stopBareMetalServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *setSubnetPublicGatewayOptions.ID, + "id": *stopBareMetalServerOptions.ID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/public_gateway`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/stop`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range setSubnetPublicGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "StopBareMetalServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "SetSubnetPublicGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range stopBareMetalServerOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(setSubnetPublicGatewayOptions.PublicGatewayIdentity) + body := make(map[string]interface{}) + if stopBareMetalServerOptions.Type != nil { + body["type"] = stopBareMetalServerOptions.Type + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -3629,71 +3722,60 @@ func (vpc *VpcV1) SetSubnetPublicGatewayWithContext(ctx context.Context, setSubn return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "set_subnet_public_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "stop_bare_metal_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetSubnetRoutingTable : Retrieve a subnet's attached routing table -// This request retrieves the routing table attached to the subnet specified by the identifier in the URL. -func (vpc *VpcV1) GetSubnetRoutingTable(getSubnetRoutingTableOptions *GetSubnetRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSubnetRoutingTableWithContext(context.Background(), getSubnetRoutingTableOptions) +// ListClusterNetworkProfiles : List cluster network profiles +// This request lists cluster network profiles available in the region. A cluster network profile specifies the +// performance characteristics and capabilities for a cluster network. +func (vpc *VpcV1) ListClusterNetworkProfiles(listClusterNetworkProfilesOptions *ListClusterNetworkProfilesOptions) (result *ClusterNetworkProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListClusterNetworkProfilesWithContext(context.Background(), listClusterNetworkProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSubnetRoutingTableWithContext is an alternate form of the GetSubnetRoutingTable method which supports a Context parameter -func (vpc *VpcV1) GetSubnetRoutingTableWithContext(ctx context.Context, getSubnetRoutingTableOptions *GetSubnetRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSubnetRoutingTableOptions, "getSubnetRoutingTableOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getSubnetRoutingTableOptions, "getSubnetRoutingTableOptions") +// ListClusterNetworkProfilesWithContext is an alternate form of the ListClusterNetworkProfiles method which supports a Context parameter +func (vpc *VpcV1) ListClusterNetworkProfilesWithContext(ctx context.Context, listClusterNetworkProfilesOptions *ListClusterNetworkProfilesOptions) (result *ClusterNetworkProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listClusterNetworkProfilesOptions, "listClusterNetworkProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *getSubnetRoutingTableOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/routing_table`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_network/profiles`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSubnetRoutingTableOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworkProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnetRoutingTable") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listClusterNetworkProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listClusterNetworkProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listClusterNetworkProfilesOptions.Start)) + } + if listClusterNetworkProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listClusterNetworkProfilesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -3704,12 +3786,12 @@ func (vpc *VpcV1) GetSubnetRoutingTableWithContext(ctx context.Context, getSubne var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_subnet_routing_table", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_cluster_network_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3720,63 +3802,53 @@ func (vpc *VpcV1) GetSubnetRoutingTableWithContext(ctx context.Context, getSubne return } -// ReplaceSubnetRoutingTable : Replace the routing table for a subnet -// This request replaces the existing routing table for a subnet with the routing table specified in the request body. -// -// For this request to succeed, the routing table `route_direct_link_ingress`, -// `route_internet_ingress`, `route_transit_gateway_ingress`, and `route_vpc_zone_ingress` properties must be `false`. -func (vpc *VpcV1) ReplaceSubnetRoutingTable(replaceSubnetRoutingTableOptions *ReplaceSubnetRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - result, response, err = vpc.ReplaceSubnetRoutingTableWithContext(context.Background(), replaceSubnetRoutingTableOptions) +// GetClusterNetworkProfile : Retrieve a cluster network profile +// This request retrieves a single cluster network profile specified by the name in the URL. +func (vpc *VpcV1) GetClusterNetworkProfile(getClusterNetworkProfileOptions *GetClusterNetworkProfileOptions) (result *ClusterNetworkProfile, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetClusterNetworkProfileWithContext(context.Background(), getClusterNetworkProfileOptions) err = core.RepurposeSDKProblem(err, "") return } -// ReplaceSubnetRoutingTableWithContext is an alternate form of the ReplaceSubnetRoutingTable method which supports a Context parameter -func (vpc *VpcV1) ReplaceSubnetRoutingTableWithContext(ctx context.Context, replaceSubnetRoutingTableOptions *ReplaceSubnetRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(replaceSubnetRoutingTableOptions, "replaceSubnetRoutingTableOptions cannot be nil") +// GetClusterNetworkProfileWithContext is an alternate form of the GetClusterNetworkProfile method which supports a Context parameter +func (vpc *VpcV1) GetClusterNetworkProfileWithContext(ctx context.Context, getClusterNetworkProfileOptions *GetClusterNetworkProfileOptions) (result *ClusterNetworkProfile, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getClusterNetworkProfileOptions, "getClusterNetworkProfileOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(replaceSubnetRoutingTableOptions, "replaceSubnetRoutingTableOptions") + err = core.ValidateStruct(getClusterNetworkProfileOptions, "getClusterNetworkProfileOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *replaceSubnetRoutingTableOptions.ID, + "name": *getClusterNetworkProfileOptions.Name, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/routing_table`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_network/profiles/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range replaceSubnetRoutingTableOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetworkProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ReplaceSubnetRoutingTable") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getClusterNetworkProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(replaceSubnetRoutingTableOptions.RoutingTableIdentity) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -3786,12 +3858,12 @@ func (vpc *VpcV1) ReplaceSubnetRoutingTableWithContext(ctx context.Context, repl var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "replace_subnet_routing_table", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_cluster_network_profile", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkProfile) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3802,73 +3874,68 @@ func (vpc *VpcV1) ReplaceSubnetRoutingTableWithContext(ctx context.Context, repl return } -// ListSubnetReservedIps : List reserved IPs in a subnet -// This request lists reserved IPs in a subnet. A reserved IP resource will exist for every address in the subnet which -// is not available for use. -func (vpc *VpcV1) ListSubnetReservedIps(listSubnetReservedIpsOptions *ListSubnetReservedIpsOptions) (result *ReservedIPCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSubnetReservedIpsWithContext(context.Background(), listSubnetReservedIpsOptions) +// ListClusterNetworks : List cluster networks +// This request lists [cluster networks](https://cloud.ibm.com/docs/vpc?topic=vpc-about-cluster-network) in the region. +// A cluster network is a grouping of resources in a separate networking space for high performance computing and +// networking. +func (vpc *VpcV1) ListClusterNetworks(listClusterNetworksOptions *ListClusterNetworksOptions) (result *ClusterNetworkCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListClusterNetworksWithContext(context.Background(), listClusterNetworksOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSubnetReservedIpsWithContext is an alternate form of the ListSubnetReservedIps method which supports a Context parameter -func (vpc *VpcV1) ListSubnetReservedIpsWithContext(ctx context.Context, listSubnetReservedIpsOptions *ListSubnetReservedIpsOptions) (result *ReservedIPCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listSubnetReservedIpsOptions, "listSubnetReservedIpsOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(listSubnetReservedIpsOptions, "listSubnetReservedIpsOptions") +// ListClusterNetworksWithContext is an alternate form of the ListClusterNetworks method which supports a Context parameter +func (vpc *VpcV1) ListClusterNetworksWithContext(ctx context.Context, listClusterNetworksOptions *ListClusterNetworksOptions) (result *ClusterNetworkCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listClusterNetworksOptions, "listClusterNetworksOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "subnet_id": *listSubnetReservedIpsOptions.SubnetID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSubnetReservedIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworks") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSubnetReservedIps") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listClusterNetworksOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listSubnetReservedIpsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listSubnetReservedIpsOptions.Start)) + if listClusterNetworksOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listClusterNetworksOptions.Start)) } - if listSubnetReservedIpsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listSubnetReservedIpsOptions.Limit)) + if listClusterNetworksOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listClusterNetworksOptions.Limit)) } - if listSubnetReservedIpsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listSubnetReservedIpsOptions.Sort)) + if listClusterNetworksOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listClusterNetworksOptions.ResourceGroupID)) } - if listSubnetReservedIpsOptions.TargetID != nil { - builder.AddQuery("target.id", fmt.Sprint(*listSubnetReservedIpsOptions.TargetID)) + if listClusterNetworksOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listClusterNetworksOptions.Name)) } - if listSubnetReservedIpsOptions.TargetCRN != nil { - builder.AddQuery("target.crn", fmt.Sprint(*listSubnetReservedIpsOptions.TargetCRN)) + if listClusterNetworksOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listClusterNetworksOptions.Sort)) } - if listSubnetReservedIpsOptions.TargetName != nil { - builder.AddQuery("target.name", fmt.Sprint(*listSubnetReservedIpsOptions.TargetName)) + if listClusterNetworksOptions.VPCID != nil { + builder.AddQuery("vpc.id", fmt.Sprint(*listClusterNetworksOptions.VPCID)) } - if listSubnetReservedIpsOptions.TargetResourceType != nil { - builder.AddQuery("target.resource_type", fmt.Sprint(*listSubnetReservedIpsOptions.TargetResourceType)) + if listClusterNetworksOptions.VPCCRN != nil { + builder.AddQuery("vpc.crn", fmt.Sprint(*listClusterNetworksOptions.VPCCRN)) + } + if listClusterNetworksOptions.VPCName != nil { + builder.AddQuery("vpc.name", fmt.Sprint(*listClusterNetworksOptions.VPCName)) } request, err := builder.Build() @@ -3880,12 +3947,12 @@ func (vpc *VpcV1) ListSubnetReservedIpsWithContext(ctx context.Context, listSubn var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_subnet_reserved_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_cluster_networks", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3896,47 +3963,44 @@ func (vpc *VpcV1) ListSubnetReservedIpsWithContext(ctx context.Context, listSubn return } -// CreateSubnetReservedIP : Reserve an IP in a subnet -// This request reserves an IP address in a subnet. If the provided prototype object includes an `address`, the address -// must not already be reserved. -func (vpc *VpcV1) CreateSubnetReservedIP(createSubnetReservedIPOptions *CreateSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateSubnetReservedIPWithContext(context.Background(), createSubnetReservedIPOptions) +// CreateClusterNetwork : Create a cluster network +// This request creates a new cluster network from a cluster network prototype object. The prototype object is +// structured in the same way as a retrieved cluster network, and contains the information necessary to create the new +// cluster network. +func (vpc *VpcV1) CreateClusterNetwork(createClusterNetworkOptions *CreateClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateClusterNetworkWithContext(context.Background(), createClusterNetworkOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateSubnetReservedIPWithContext is an alternate form of the CreateSubnetReservedIP method which supports a Context parameter -func (vpc *VpcV1) CreateSubnetReservedIPWithContext(ctx context.Context, createSubnetReservedIPOptions *CreateSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createSubnetReservedIPOptions, "createSubnetReservedIPOptions cannot be nil") +// CreateClusterNetworkWithContext is an alternate form of the CreateClusterNetwork method which supports a Context parameter +func (vpc *VpcV1) CreateClusterNetworkWithContext(ctx context.Context, createClusterNetworkOptions *CreateClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createClusterNetworkOptions, "createClusterNetworkOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createSubnetReservedIPOptions, "createSubnetReservedIPOptions") + err = core.ValidateStruct(createClusterNetworkOptions, "createClusterNetworkOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "subnet_id": *createSubnetReservedIPOptions.SubnetID, - } - builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createSubnetReservedIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetwork") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSubnetReservedIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createClusterNetworkOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -3946,17 +4010,23 @@ func (vpc *VpcV1) CreateSubnetReservedIPWithContext(ctx context.Context, createS builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createSubnetReservedIPOptions.Address != nil { - body["address"] = createSubnetReservedIPOptions.Address + if createClusterNetworkOptions.Profile != nil { + body["profile"] = createClusterNetworkOptions.Profile } - if createSubnetReservedIPOptions.AutoDelete != nil { - body["auto_delete"] = createSubnetReservedIPOptions.AutoDelete + if createClusterNetworkOptions.VPC != nil { + body["vpc"] = createClusterNetworkOptions.VPC } - if createSubnetReservedIPOptions.Name != nil { - body["name"] = createSubnetReservedIPOptions.Name + if createClusterNetworkOptions.Zone != nil { + body["zone"] = createClusterNetworkOptions.Zone } - if createSubnetReservedIPOptions.Target != nil { - body["target"] = createSubnetReservedIPOptions.Target + if createClusterNetworkOptions.Name != nil { + body["name"] = createClusterNetworkOptions.Name + } + if createClusterNetworkOptions.ResourceGroup != nil { + body["resource_group"] = createClusterNetworkOptions.ResourceGroup + } + if createClusterNetworkOptions.SubnetPrefixes != nil { + body["subnet_prefixes"] = createClusterNetworkOptions.SubnetPrefixes } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -3973,12 +4043,12 @@ func (vpc *VpcV1) CreateSubnetReservedIPWithContext(ctx context.Context, createS var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_subnet_reserved_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_cluster_network", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetwork) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -3989,56 +4059,69 @@ func (vpc *VpcV1) CreateSubnetReservedIPWithContext(ctx context.Context, createS return } -// DeleteSubnetReservedIP : Delete a reserved IP -// This request releases a reserved IP. This operation cannot be reversed. +// ListClusterNetworkInterfaces : List cluster network interfaces +// This request lists cluster network interfaces in the region. A cluster network interface is a logical abstraction of +// a cluster network interface in a subnet, and may be attached to a target resource. // -// For this request to succeed, the reserved IP must not be required by another resource, such as a bare metal server -// network interface, instance network interface or virtual network interface for which it is the primary IP. A -// provider-owned reserved IP is not allowed to be deleted. -func (vpc *VpcV1) DeleteSubnetReservedIP(deleteSubnetReservedIPOptions *DeleteSubnetReservedIPOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteSubnetReservedIPWithContext(context.Background(), deleteSubnetReservedIPOptions) +// The cluster network interfaces will be sorted by their `created_at` property values, with newest cluster network +// interfaces first. Cluster network interfaces with identical +// `created_at` property values will in turn be sorted by ascending `name` property values. +func (vpc *VpcV1) ListClusterNetworkInterfaces(listClusterNetworkInterfacesOptions *ListClusterNetworkInterfacesOptions) (result *ClusterNetworkInterfaceCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListClusterNetworkInterfacesWithContext(context.Background(), listClusterNetworkInterfacesOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSubnetReservedIPWithContext is an alternate form of the DeleteSubnetReservedIP method which supports a Context parameter -func (vpc *VpcV1) DeleteSubnetReservedIPWithContext(ctx context.Context, deleteSubnetReservedIPOptions *DeleteSubnetReservedIPOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSubnetReservedIPOptions, "deleteSubnetReservedIPOptions cannot be nil") +// ListClusterNetworkInterfacesWithContext is an alternate form of the ListClusterNetworkInterfaces method which supports a Context parameter +func (vpc *VpcV1) ListClusterNetworkInterfacesWithContext(ctx context.Context, listClusterNetworkInterfacesOptions *ListClusterNetworkInterfacesOptions) (result *ClusterNetworkInterfaceCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listClusterNetworkInterfacesOptions, "listClusterNetworkInterfacesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSubnetReservedIPOptions, "deleteSubnetReservedIPOptions") + err = core.ValidateStruct(listClusterNetworkInterfacesOptions, "listClusterNetworkInterfacesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "subnet_id": *deleteSubnetReservedIPOptions.SubnetID, - "id": *deleteSubnetReservedIPOptions.ID, + "cluster_network_id": *listClusterNetworkInterfacesOptions.ClusterNetworkID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSubnetReservedIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworkInterfaces") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSubnetReservedIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listClusterNetworkInterfacesOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listClusterNetworkInterfacesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listClusterNetworkInterfacesOptions.Start)) + } + if listClusterNetworkInterfacesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listClusterNetworkInterfacesOptions.Limit)) + } + if listClusterNetworkInterfacesOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listClusterNetworkInterfacesOptions.Name)) + } + if listClusterNetworkInterfacesOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listClusterNetworkInterfacesOptions.Sort)) + } request, err := builder.Build() if err != nil { @@ -4046,64 +4129,91 @@ func (vpc *VpcV1) DeleteSubnetReservedIPWithContext(ctx context.Context, deleteS return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_subnet_reserved_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_cluster_network_interfaces", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterfaceCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetSubnetReservedIP : Retrieve a reserved IP -// This request retrieves a single reserved IP specified by the identifier in the URL. -func (vpc *VpcV1) GetSubnetReservedIP(getSubnetReservedIPOptions *GetSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSubnetReservedIPWithContext(context.Background(), getSubnetReservedIPOptions) +// CreateClusterNetworkInterface : Create a cluster network interface +// This request creates a new cluster network interface from a cluster network interface prototype object. The prototype +// object is structured in the same way as a retrieved cluster network interface, and contains the information necessary +// to create the new cluster network interface. +func (vpc *VpcV1) CreateClusterNetworkInterface(createClusterNetworkInterfaceOptions *CreateClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateClusterNetworkInterfaceWithContext(context.Background(), createClusterNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSubnetReservedIPWithContext is an alternate form of the GetSubnetReservedIP method which supports a Context parameter -func (vpc *VpcV1) GetSubnetReservedIPWithContext(ctx context.Context, getSubnetReservedIPOptions *GetSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSubnetReservedIPOptions, "getSubnetReservedIPOptions cannot be nil") +// CreateClusterNetworkInterfaceWithContext is an alternate form of the CreateClusterNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) CreateClusterNetworkInterfaceWithContext(ctx context.Context, createClusterNetworkInterfaceOptions *CreateClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createClusterNetworkInterfaceOptions, "createClusterNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSubnetReservedIPOptions, "getSubnetReservedIPOptions") + err = core.ValidateStruct(createClusterNetworkInterfaceOptions, "createClusterNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "subnet_id": *getSubnetReservedIPOptions.SubnetID, - "id": *getSubnetReservedIPOptions.ID, + "cluster_network_id": *createClusterNetworkInterfaceOptions.ClusterNetworkID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSubnetReservedIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnetReservedIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createClusterNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createClusterNetworkInterfaceOptions.Name != nil { + body["name"] = createClusterNetworkInterfaceOptions.Name + } + if createClusterNetworkInterfaceOptions.PrimaryIP != nil { + body["primary_ip"] = createClusterNetworkInterfaceOptions.PrimaryIP + } + if createClusterNetworkInterfaceOptions.Subnet != nil { + body["subnet"] = createClusterNetworkInterfaceOptions.Subnet + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -4113,12 +4223,12 @@ func (vpc *VpcV1) GetSubnetReservedIPWithContext(ctx context.Context, getSubnetR var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_subnet_reserved_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_cluster_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4129,64 +4239,59 @@ func (vpc *VpcV1) GetSubnetReservedIPWithContext(ctx context.Context, getSubnetR return } -// UpdateSubnetReservedIP : Update a reserved IP -// This request updates a reserved IP with the information in a provided reserved IP patch. The reserved IP patch object -// is structured in the same way as a retrieved reserved IP and contains only the information to be updated. -// -// A provider-owned reserved IP is not allowed to be updated. -func (vpc *VpcV1) UpdateSubnetReservedIP(updateSubnetReservedIPOptions *UpdateSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateSubnetReservedIPWithContext(context.Background(), updateSubnetReservedIPOptions) +// DeleteClusterNetworkInterface : Delete a cluster network interface +// This request deletes a cluster network interface. This operation cannot be reversed. For this request to succeed, +// the cluster network interface must not be required by another resource, such as a cluster network attachment for a +// virtual server instance. +func (vpc *VpcV1) DeleteClusterNetworkInterface(deleteClusterNetworkInterfaceOptions *DeleteClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteClusterNetworkInterfaceWithContext(context.Background(), deleteClusterNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateSubnetReservedIPWithContext is an alternate form of the UpdateSubnetReservedIP method which supports a Context parameter -func (vpc *VpcV1) UpdateSubnetReservedIPWithContext(ctx context.Context, updateSubnetReservedIPOptions *UpdateSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateSubnetReservedIPOptions, "updateSubnetReservedIPOptions cannot be nil") +// DeleteClusterNetworkInterfaceWithContext is an alternate form of the DeleteClusterNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) DeleteClusterNetworkInterfaceWithContext(ctx context.Context, deleteClusterNetworkInterfaceOptions *DeleteClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteClusterNetworkInterfaceOptions, "deleteClusterNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateSubnetReservedIPOptions, "updateSubnetReservedIPOptions") + err = core.ValidateStruct(deleteClusterNetworkInterfaceOptions, "deleteClusterNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "subnet_id": *updateSubnetReservedIPOptions.SubnetID, - "id": *updateSubnetReservedIPOptions.ID, + "cluster_network_id": *deleteClusterNetworkInterfaceOptions.ClusterNetworkID, + "id": *deleteClusterNetworkInterfaceOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateSubnetReservedIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteClusterNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSubnetReservedIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteClusterNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") + if deleteClusterNetworkInterfaceOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteClusterNetworkInterfaceOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateSubnetReservedIPOptions.ReservedIPPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -4196,12 +4301,12 @@ func (vpc *VpcV1) UpdateSubnetReservedIPWithContext(ctx context.Context, updateS var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_subnet_reserved_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_cluster_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4212,68 +4317,53 @@ func (vpc *VpcV1) UpdateSubnetReservedIPWithContext(ctx context.Context, updateS return } -// ListImages : List images -// This request lists images available in the region. An image provides source data for a volume. Images are either -// system-provided, or created from another source, such as importing from Cloud Object Storage. -func (vpc *VpcV1) ListImages(listImagesOptions *ListImagesOptions) (result *ImageCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListImagesWithContext(context.Background(), listImagesOptions) +// GetClusterNetworkInterface : Retrieve a cluster network interface +// This request retrieves a single cluster network interface specified by the identifier in the URL. +func (vpc *VpcV1) GetClusterNetworkInterface(getClusterNetworkInterfaceOptions *GetClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetClusterNetworkInterfaceWithContext(context.Background(), getClusterNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListImagesWithContext is an alternate form of the ListImages method which supports a Context parameter -func (vpc *VpcV1) ListImagesWithContext(ctx context.Context, listImagesOptions *ListImagesOptions) (result *ImageCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listImagesOptions, "listImagesOptions") +// GetClusterNetworkInterfaceWithContext is an alternate form of the GetClusterNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) GetClusterNetworkInterfaceWithContext(ctx context.Context, getClusterNetworkInterfaceOptions *GetClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getClusterNetworkInterfaceOptions, "getClusterNetworkInterfaceOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getClusterNetworkInterfaceOptions, "getClusterNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "cluster_network_id": *getClusterNetworkInterfaceOptions.ClusterNetworkID, + "id": *getClusterNetworkInterfaceOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listImagesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListImages") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getClusterNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listImagesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listImagesOptions.Start)) - } - if listImagesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listImagesOptions.Limit)) - } - if listImagesOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listImagesOptions.ResourceGroupID)) - } - if listImagesOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listImagesOptions.Name)) - } - if listImagesOptions.Status != nil { - builder.AddQuery("status", strings.Join(listImagesOptions.Status, ",")) - } - if listImagesOptions.Visibility != nil { - builder.AddQuery("visibility", fmt.Sprint(*listImagesOptions.Visibility)) - } - if listImagesOptions.UserDataFormat != nil { - builder.AddQuery("user_data_format", strings.Join(listImagesOptions.UserDataFormat, ",")) - } - if listImagesOptions.OwnerType != nil { - builder.AddQuery("owner_type", fmt.Sprint(*listImagesOptions.OwnerType)) - } request, err := builder.Build() if err != nil { @@ -4284,12 +4374,12 @@ func (vpc *VpcV1) ListImagesWithContext(ctx context.Context, listImagesOptions * var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_images", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_cluster_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4300,54 +4390,61 @@ func (vpc *VpcV1) ListImagesWithContext(ctx context.Context, listImagesOptions * return } -// CreateImage : Create an image -// This request creates a new image from an image prototype object. The prototype object is structured in the same way -// as a retrieved image, and contains the information necessary to create the new image. If an image is being imported, -// a URL to the image file on object storage must be specified. If an image is being created from an existing volume, -// that volume must be specified. -func (vpc *VpcV1) CreateImage(createImageOptions *CreateImageOptions) (result *Image, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateImageWithContext(context.Background(), createImageOptions) +// UpdateClusterNetworkInterface : Update a cluster network interface +// This request updates a cluster network interface with the information provided in a cluster network interface patch +// object. The patch object is structured in the same way as a retrieved cluster network interface and needs to contain +// only the information to be updated. +func (vpc *VpcV1) UpdateClusterNetworkInterface(updateClusterNetworkInterfaceOptions *UpdateClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateClusterNetworkInterfaceWithContext(context.Background(), updateClusterNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateImageWithContext is an alternate form of the CreateImage method which supports a Context parameter -func (vpc *VpcV1) CreateImageWithContext(ctx context.Context, createImageOptions *CreateImageOptions) (result *Image, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createImageOptions, "createImageOptions cannot be nil") +// UpdateClusterNetworkInterfaceWithContext is an alternate form of the UpdateClusterNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) UpdateClusterNetworkInterfaceWithContext(ctx context.Context, updateClusterNetworkInterfaceOptions *UpdateClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateClusterNetworkInterfaceOptions, "updateClusterNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createImageOptions, "createImageOptions") + err = core.ValidateStruct(updateClusterNetworkInterfaceOptions, "updateClusterNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "cluster_network_id": *updateClusterNetworkInterfaceOptions.ClusterNetworkID, + "id": *updateClusterNetworkInterfaceOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createImageOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateClusterNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateImage") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateClusterNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateClusterNetworkInterfaceOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateClusterNetworkInterfaceOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createImageOptions.ImagePrototype) + _, err = builder.SetBodyContentJSON(updateClusterNetworkInterfaceOptions.ClusterNetworkInterfacePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -4362,12 +4459,12 @@ func (vpc *VpcV1) CreateImageWithContext(ctx context.Context, createImageOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_image", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_cluster_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImage) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4378,55 +4475,65 @@ func (vpc *VpcV1) CreateImageWithContext(ctx context.Context, createImageOptions return } -// DeleteImage : Delete an image -// This request deletes an image. Any active image export jobs will be completed first. This operation cannot be -// reversed. A system-provided image is not allowed to be deleted. Additionally, an image cannot be deleted if it: -// - has a `status` of `deleting` -// - has a `status` of `pending` with a `status_reasons` code of `image_request_in_progress` -// - has `catalog_offering.managed` set to `true`. -func (vpc *VpcV1) DeleteImage(deleteImageOptions *DeleteImageOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteImageWithContext(context.Background(), deleteImageOptions) +// ListClusterNetworkSubnets : List cluster network subnets +// This request lists cluster network subnets in the cluster network. A cluster network subnet provides network routing +// between other cluster network subnets within a cluster network. +func (vpc *VpcV1) ListClusterNetworkSubnets(listClusterNetworkSubnetsOptions *ListClusterNetworkSubnetsOptions) (result *ClusterNetworkSubnetCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListClusterNetworkSubnetsWithContext(context.Background(), listClusterNetworkSubnetsOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteImageWithContext is an alternate form of the DeleteImage method which supports a Context parameter -func (vpc *VpcV1) DeleteImageWithContext(ctx context.Context, deleteImageOptions *DeleteImageOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteImageOptions, "deleteImageOptions cannot be nil") +// ListClusterNetworkSubnetsWithContext is an alternate form of the ListClusterNetworkSubnets method which supports a Context parameter +func (vpc *VpcV1) ListClusterNetworkSubnetsWithContext(ctx context.Context, listClusterNetworkSubnetsOptions *ListClusterNetworkSubnetsOptions) (result *ClusterNetworkSubnetCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listClusterNetworkSubnetsOptions, "listClusterNetworkSubnetsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteImageOptions, "deleteImageOptions") + err = core.ValidateStruct(listClusterNetworkSubnetsOptions, "listClusterNetworkSubnetsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteImageOptions.ID, + "cluster_network_id": *listClusterNetworkSubnetsOptions.ClusterNetworkID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteImageOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworkSubnets") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteImage") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listClusterNetworkSubnetsOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listClusterNetworkSubnetsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listClusterNetworkSubnetsOptions.Start)) + } + if listClusterNetworkSubnetsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listClusterNetworkSubnetsOptions.Limit)) + } + if listClusterNetworkSubnetsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listClusterNetworkSubnetsOptions.Name)) + } + if listClusterNetworkSubnetsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listClusterNetworkSubnetsOptions.Sort)) + } request, err := builder.Build() if err != nil { @@ -4434,63 +4541,81 @@ func (vpc *VpcV1) DeleteImageWithContext(ctx context.Context, deleteImageOptions return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_image", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_cluster_network_subnets", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetImage : Retrieve an image -// This request retrieves a single image specified by the identifier in the URL. -func (vpc *VpcV1) GetImage(getImageOptions *GetImageOptions) (result *Image, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetImageWithContext(context.Background(), getImageOptions) +// CreateClusterNetworkSubnet : Create a cluster network subnet +// This request creates a new cluster network subnet from a cluster network subnet prototype object. The prototype +// object is structured in the same way as a retrieved cluster network subnet, and contains the information necessary to +// create the new cluster network subnet. +func (vpc *VpcV1) CreateClusterNetworkSubnet(createClusterNetworkSubnetOptions *CreateClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateClusterNetworkSubnetWithContext(context.Background(), createClusterNetworkSubnetOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetImageWithContext is an alternate form of the GetImage method which supports a Context parameter -func (vpc *VpcV1) GetImageWithContext(ctx context.Context, getImageOptions *GetImageOptions) (result *Image, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getImageOptions, "getImageOptions cannot be nil") +// CreateClusterNetworkSubnetWithContext is an alternate form of the CreateClusterNetworkSubnet method which supports a Context parameter +func (vpc *VpcV1) CreateClusterNetworkSubnetWithContext(ctx context.Context, createClusterNetworkSubnetOptions *CreateClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createClusterNetworkSubnetOptions, "createClusterNetworkSubnetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getImageOptions, "getImageOptions") + err = core.ValidateStruct(createClusterNetworkSubnetOptions, "createClusterNetworkSubnetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getImageOptions.ID, + "cluster_network_id": *createClusterNetworkSubnetOptions.ClusterNetworkID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getImageOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetworkSubnet") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetImage") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createClusterNetworkSubnetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(createClusterNetworkSubnetOptions.ClusterNetworkSubnetPrototype) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -4500,12 +4625,12 @@ func (vpc *VpcV1) GetImageWithContext(ctx context.Context, getImageOptions *GetI var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_image", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_cluster_network_subnet", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImage) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnet) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4516,60 +4641,64 @@ func (vpc *VpcV1) GetImageWithContext(ctx context.Context, getImageOptions *GetI return } -// UpdateImage : Update an image -// This request updates an image with the information in a provided image patch. The image patch object is structured in -// the same way as a retrieved image and contains only the information to be updated. A system-provided image is not -// allowed to be updated. An image with a `status` of `deleting` cannot be updated. -func (vpc *VpcV1) UpdateImage(updateImageOptions *UpdateImageOptions) (result *Image, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateImageWithContext(context.Background(), updateImageOptions) +// ListClusterNetworkSubnetReservedIps : List cluster network subnet reserved IPs +// This request lists cluster network subnet reserved IPs in the cluster network. +func (vpc *VpcV1) ListClusterNetworkSubnetReservedIps(listClusterNetworkSubnetReservedIpsOptions *ListClusterNetworkSubnetReservedIpsOptions) (result *ClusterNetworkSubnetReservedIPCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListClusterNetworkSubnetReservedIpsWithContext(context.Background(), listClusterNetworkSubnetReservedIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateImageWithContext is an alternate form of the UpdateImage method which supports a Context parameter -func (vpc *VpcV1) UpdateImageWithContext(ctx context.Context, updateImageOptions *UpdateImageOptions) (result *Image, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateImageOptions, "updateImageOptions cannot be nil") +// ListClusterNetworkSubnetReservedIpsWithContext is an alternate form of the ListClusterNetworkSubnetReservedIps method which supports a Context parameter +func (vpc *VpcV1) ListClusterNetworkSubnetReservedIpsWithContext(ctx context.Context, listClusterNetworkSubnetReservedIpsOptions *ListClusterNetworkSubnetReservedIpsOptions) (result *ClusterNetworkSubnetReservedIPCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listClusterNetworkSubnetReservedIpsOptions, "listClusterNetworkSubnetReservedIpsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateImageOptions, "updateImageOptions") + err = core.ValidateStruct(listClusterNetworkSubnetReservedIpsOptions, "listClusterNetworkSubnetReservedIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateImageOptions.ID, + "cluster_network_id": *listClusterNetworkSubnetReservedIpsOptions.ClusterNetworkID, + "cluster_network_subnet_id": *listClusterNetworkSubnetReservedIpsOptions.ClusterNetworkSubnetID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateImageOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworkSubnetReservedIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateImage") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listClusterNetworkSubnetReservedIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - _, err = builder.SetBodyContentJSON(updateImageOptions.ImagePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listClusterNetworkSubnetReservedIpsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listClusterNetworkSubnetReservedIpsOptions.Start)) + } + if listClusterNetworkSubnetReservedIpsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listClusterNetworkSubnetReservedIpsOptions.Limit)) + } + if listClusterNetworkSubnetReservedIpsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listClusterNetworkSubnetReservedIpsOptions.Name)) + } + if listClusterNetworkSubnetReservedIpsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listClusterNetworkSubnetReservedIpsOptions.Sort)) } request, err := builder.Build() @@ -4581,12 +4710,12 @@ func (vpc *VpcV1) UpdateImageWithContext(ctx context.Context, updateImageOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_image", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_cluster_network_subnet_reserved_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImage) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIPCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4597,130 +4726,146 @@ func (vpc *VpcV1) UpdateImageWithContext(ctx context.Context, updateImageOptions return } -// DeprecateImage : Deprecate an image -// This request deprecates an image, resulting in its `status` becoming `deprecated` and -// `deprecation_at` being set to the current date and time. -// -// The image must: -// - have a `status` of `available` -// - have `catalog_offering.managed` set to `false` -// - not have `deprecation_at` set -// -// The image must not have `deprecation_at` set, must have `catalog_offering.managed` set to -// `false`, and must have a `status` of `available`. -// -// A system-provided image is not allowed to be deprecated. -func (vpc *VpcV1) DeprecateImage(deprecateImageOptions *DeprecateImageOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeprecateImageWithContext(context.Background(), deprecateImageOptions) +// CreateClusterNetworkSubnetReservedIP : Create a cluster network subnet reserved IP +// This request creates a new cluster network subnet reserved IP from a cluster network subnet reserved IP prototype +// object. The prototype object is structured in the same way as a retrieved cluster network subnet reserved IP, and +// contains the information necessary to create the new cluster network subnet reserved IP. +func (vpc *VpcV1) CreateClusterNetworkSubnetReservedIP(createClusterNetworkSubnetReservedIPOptions *CreateClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateClusterNetworkSubnetReservedIPWithContext(context.Background(), createClusterNetworkSubnetReservedIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeprecateImageWithContext is an alternate form of the DeprecateImage method which supports a Context parameter -func (vpc *VpcV1) DeprecateImageWithContext(ctx context.Context, deprecateImageOptions *DeprecateImageOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deprecateImageOptions, "deprecateImageOptions cannot be nil") +// CreateClusterNetworkSubnetReservedIPWithContext is an alternate form of the CreateClusterNetworkSubnetReservedIP method which supports a Context parameter +func (vpc *VpcV1) CreateClusterNetworkSubnetReservedIPWithContext(ctx context.Context, createClusterNetworkSubnetReservedIPOptions *CreateClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createClusterNetworkSubnetReservedIPOptions, "createClusterNetworkSubnetReservedIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deprecateImageOptions, "deprecateImageOptions") + err = core.ValidateStruct(createClusterNetworkSubnetReservedIPOptions, "createClusterNetworkSubnetReservedIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deprecateImageOptions.ID, + "cluster_network_id": *createClusterNetworkSubnetReservedIPOptions.ClusterNetworkID, + "cluster_network_subnet_id": *createClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}/deprecate`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deprecateImageOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetworkSubnetReservedIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeprecateImage") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createClusterNetworkSubnetReservedIPOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createClusterNetworkSubnetReservedIPOptions.Address != nil { + body["address"] = createClusterNetworkSubnetReservedIPOptions.Address + } + if createClusterNetworkSubnetReservedIPOptions.Name != nil { + body["name"] = createClusterNetworkSubnetReservedIPOptions.Name + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "deprecate_image", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_cluster_network_subnet_reserved_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIP) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ObsoleteImage : Obsolete an image -// This request obsoletes an image, resulting in its `status` becoming `obsolete` and -// `obsolescence_at` being set to the current date and time. -// -// The image must: -// - have a `status` of `available` or `deprecated` -// - have `catalog_offering.managed` set to `false` -// - not have `deprecation_at` set in the future -// - not have `obsolescence_at` set +// DeleteClusterNetworkSubnetReservedIP : Delete a cluster network subnet reserved IP +// This request deletes a cluster network subnet reserved IP. This operation cannot be reversed. // -// A system-provided image is not allowed to be obsoleted. -func (vpc *VpcV1) ObsoleteImage(obsoleteImageOptions *ObsoleteImageOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.ObsoleteImageWithContext(context.Background(), obsoleteImageOptions) +// For this request to succeed, the reserved IP must be unbound. A provider-owned reserved IP is not allowed to be +// deleted. +func (vpc *VpcV1) DeleteClusterNetworkSubnetReservedIP(deleteClusterNetworkSubnetReservedIPOptions *DeleteClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteClusterNetworkSubnetReservedIPWithContext(context.Background(), deleteClusterNetworkSubnetReservedIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// ObsoleteImageWithContext is an alternate form of the ObsoleteImage method which supports a Context parameter -func (vpc *VpcV1) ObsoleteImageWithContext(ctx context.Context, obsoleteImageOptions *ObsoleteImageOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(obsoleteImageOptions, "obsoleteImageOptions cannot be nil") +// DeleteClusterNetworkSubnetReservedIPWithContext is an alternate form of the DeleteClusterNetworkSubnetReservedIP method which supports a Context parameter +func (vpc *VpcV1) DeleteClusterNetworkSubnetReservedIPWithContext(ctx context.Context, deleteClusterNetworkSubnetReservedIPOptions *DeleteClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteClusterNetworkSubnetReservedIPOptions, "deleteClusterNetworkSubnetReservedIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(obsoleteImageOptions, "obsoleteImageOptions") + err = core.ValidateStruct(deleteClusterNetworkSubnetReservedIPOptions, "deleteClusterNetworkSubnetReservedIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *obsoleteImageOptions.ID, + "cluster_network_id": *deleteClusterNetworkSubnetReservedIPOptions.ClusterNetworkID, + "cluster_network_subnet_id": *deleteClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetID, + "id": *deleteClusterNetworkSubnetReservedIPOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}/obsolete`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range obsoleteImageOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteClusterNetworkSubnetReservedIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ObsoleteImage") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteClusterNetworkSubnetReservedIPOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + if deleteClusterNetworkSubnetReservedIPOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteClusterNetworkSubnetReservedIPOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -4731,70 +4876,73 @@ func (vpc *VpcV1) ObsoleteImageWithContext(ctx context.Context, obsoleteImageOpt return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "obsolete_image", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_cluster_network_subnet_reserved_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIP) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListImageExportJobs : List export jobs for an image -// This request lists export jobs for an image. Each job tracks the exporting of the image to another location, such as -// a bucket within cloud object storage. -// -// The jobs will be sorted by their `created_at` property values, with newest jobs first. Jobs with identical -// `created_at` property values will in turn be sorted by ascending -// `name` property values. -func (vpc *VpcV1) ListImageExportJobs(listImageExportJobsOptions *ListImageExportJobsOptions) (result *ImageExportJobUnpaginatedCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListImageExportJobsWithContext(context.Background(), listImageExportJobsOptions) +// GetClusterNetworkSubnetReservedIP : Retrieve a cluster network subnet reserved IP +// This request retrieves a single cluster network subnet reserved IP specified by the identifier in the URL. +func (vpc *VpcV1) GetClusterNetworkSubnetReservedIP(getClusterNetworkSubnetReservedIPOptions *GetClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetClusterNetworkSubnetReservedIPWithContext(context.Background(), getClusterNetworkSubnetReservedIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListImageExportJobsWithContext is an alternate form of the ListImageExportJobs method which supports a Context parameter -func (vpc *VpcV1) ListImageExportJobsWithContext(ctx context.Context, listImageExportJobsOptions *ListImageExportJobsOptions) (result *ImageExportJobUnpaginatedCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listImageExportJobsOptions, "listImageExportJobsOptions cannot be nil") +// GetClusterNetworkSubnetReservedIPWithContext is an alternate form of the GetClusterNetworkSubnetReservedIP method which supports a Context parameter +func (vpc *VpcV1) GetClusterNetworkSubnetReservedIPWithContext(ctx context.Context, getClusterNetworkSubnetReservedIPOptions *GetClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getClusterNetworkSubnetReservedIPOptions, "getClusterNetworkSubnetReservedIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listImageExportJobsOptions, "listImageExportJobsOptions") + err = core.ValidateStruct(getClusterNetworkSubnetReservedIPOptions, "getClusterNetworkSubnetReservedIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "image_id": *listImageExportJobsOptions.ImageID, + "cluster_network_id": *getClusterNetworkSubnetReservedIPOptions.ClusterNetworkID, + "cluster_network_subnet_id": *getClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetID, + "id": *getClusterNetworkSubnetReservedIPOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listImageExportJobsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetworkSubnetReservedIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListImageExportJobs") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getClusterNetworkSubnetReservedIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listImageExportJobsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listImageExportJobsOptions.Name)) - } request, err := builder.Build() if err != nil { @@ -4805,12 +4953,12 @@ func (vpc *VpcV1) ListImageExportJobsWithContext(ctx context.Context, listImageE var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_image_export_jobs", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_cluster_network_subnet_reserved_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageExportJobUnpaginatedCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4821,68 +4969,62 @@ func (vpc *VpcV1) ListImageExportJobsWithContext(ctx context.Context, listImageE return } -// CreateImageExportJob : Create an export job for an image -// This request creates and queues a new export job for the image specified in the URL using the image export job -// prototype object. The image must be owned by the account and be in the `available`, `deprecated`, `obsolete`, or -// `unusable` state. The prototype object is structured in the same way as a retrieved image export job, and contains -// the information necessary to create and queue the new image export job. -func (vpc *VpcV1) CreateImageExportJob(createImageExportJobOptions *CreateImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateImageExportJobWithContext(context.Background(), createImageExportJobOptions) +// UpdateClusterNetworkSubnetReservedIP : Update a cluster network subnet reserved IP +// This request updates a cluster network subnet reserved IP with the information provided in a cluster network subnet +// reserved IP patch object. The patch object is structured in the same way as a retrieved cluster network subnet +// reserved IP and needs to contain only the information to be updated. +func (vpc *VpcV1) UpdateClusterNetworkSubnetReservedIP(updateClusterNetworkSubnetReservedIPOptions *UpdateClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateClusterNetworkSubnetReservedIPWithContext(context.Background(), updateClusterNetworkSubnetReservedIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateImageExportJobWithContext is an alternate form of the CreateImageExportJob method which supports a Context parameter -func (vpc *VpcV1) CreateImageExportJobWithContext(ctx context.Context, createImageExportJobOptions *CreateImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createImageExportJobOptions, "createImageExportJobOptions cannot be nil") +// UpdateClusterNetworkSubnetReservedIPWithContext is an alternate form of the UpdateClusterNetworkSubnetReservedIP method which supports a Context parameter +func (vpc *VpcV1) UpdateClusterNetworkSubnetReservedIPWithContext(ctx context.Context, updateClusterNetworkSubnetReservedIPOptions *UpdateClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateClusterNetworkSubnetReservedIPOptions, "updateClusterNetworkSubnetReservedIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createImageExportJobOptions, "createImageExportJobOptions") + err = core.ValidateStruct(updateClusterNetworkSubnetReservedIPOptions, "updateClusterNetworkSubnetReservedIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "image_id": *createImageExportJobOptions.ImageID, + "cluster_network_id": *updateClusterNetworkSubnetReservedIPOptions.ClusterNetworkID, + "cluster_network_subnet_id": *updateClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetID, + "id": *updateClusterNetworkSubnetReservedIPOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createImageExportJobOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateClusterNetworkSubnetReservedIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateImageExportJob") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateClusterNetworkSubnetReservedIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateClusterNetworkSubnetReservedIPOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateClusterNetworkSubnetReservedIPOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createImageExportJobOptions.StorageBucket != nil { - body["storage_bucket"] = createImageExportJobOptions.StorageBucket - } - if createImageExportJobOptions.Format != nil { - body["format"] = createImageExportJobOptions.Format - } - if createImageExportJobOptions.Name != nil { - body["name"] = createImageExportJobOptions.Name - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(updateClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetReservedIPPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -4897,12 +5039,12 @@ func (vpc *VpcV1) CreateImageExportJobWithContext(ctx context.Context, createIma var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_image_export_job", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_cluster_network_subnet_reserved_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageExportJob) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -4913,51 +5055,55 @@ func (vpc *VpcV1) CreateImageExportJobWithContext(ctx context.Context, createIma return } -// DeleteImageExportJob : Delete an image export job -// This request deletes an image export job. This operation cannot be reversed. If the job has not completed, the job -// will be canceled, and the incomplete exported image object deleted. If the job has completed, the exported image -// object will not be deleted. -func (vpc *VpcV1) DeleteImageExportJob(deleteImageExportJobOptions *DeleteImageExportJobOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteImageExportJobWithContext(context.Background(), deleteImageExportJobOptions) +// DeleteClusterNetworkSubnet : Delete a cluster network subnet +// This request deletes a cluster network subnet. This operation cannot be reversed. +// +// For this request to succeed, this cluster subnet must not be attached to a cluster network interface. +func (vpc *VpcV1) DeleteClusterNetworkSubnet(deleteClusterNetworkSubnetOptions *DeleteClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteClusterNetworkSubnetWithContext(context.Background(), deleteClusterNetworkSubnetOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteImageExportJobWithContext is an alternate form of the DeleteImageExportJob method which supports a Context parameter -func (vpc *VpcV1) DeleteImageExportJobWithContext(ctx context.Context, deleteImageExportJobOptions *DeleteImageExportJobOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteImageExportJobOptions, "deleteImageExportJobOptions cannot be nil") +// DeleteClusterNetworkSubnetWithContext is an alternate form of the DeleteClusterNetworkSubnet method which supports a Context parameter +func (vpc *VpcV1) DeleteClusterNetworkSubnetWithContext(ctx context.Context, deleteClusterNetworkSubnetOptions *DeleteClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteClusterNetworkSubnetOptions, "deleteClusterNetworkSubnetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteImageExportJobOptions, "deleteImageExportJobOptions") + err = core.ValidateStruct(deleteClusterNetworkSubnetOptions, "deleteClusterNetworkSubnetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "image_id": *deleteImageExportJobOptions.ImageID, - "id": *deleteImageExportJobOptions.ID, + "cluster_network_id": *deleteClusterNetworkSubnetOptions.ClusterNetworkID, + "id": *deleteClusterNetworkSubnetOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteImageExportJobOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteClusterNetworkSubnet") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteImageExportJob") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteClusterNetworkSubnetOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + if deleteClusterNetworkSubnetOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteClusterNetworkSubnetOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -4968,57 +5114,66 @@ func (vpc *VpcV1) DeleteImageExportJobWithContext(ctx context.Context, deleteIma return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_image_export_job", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_cluster_network_subnet", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnet) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetImageExportJob : Retrieve an image export job -// This request retrieves a single image export job specified by the identifier in the URL. -func (vpc *VpcV1) GetImageExportJob(getImageExportJobOptions *GetImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetImageExportJobWithContext(context.Background(), getImageExportJobOptions) +// GetClusterNetworkSubnet : Retrieve a cluster network subnet +// This request retrieves a single cluster network subnet specified by the identifier in the URL. +func (vpc *VpcV1) GetClusterNetworkSubnet(getClusterNetworkSubnetOptions *GetClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetClusterNetworkSubnetWithContext(context.Background(), getClusterNetworkSubnetOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetImageExportJobWithContext is an alternate form of the GetImageExportJob method which supports a Context parameter -func (vpc *VpcV1) GetImageExportJobWithContext(ctx context.Context, getImageExportJobOptions *GetImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getImageExportJobOptions, "getImageExportJobOptions cannot be nil") +// GetClusterNetworkSubnetWithContext is an alternate form of the GetClusterNetworkSubnet method which supports a Context parameter +func (vpc *VpcV1) GetClusterNetworkSubnetWithContext(ctx context.Context, getClusterNetworkSubnetOptions *GetClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getClusterNetworkSubnetOptions, "getClusterNetworkSubnetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getImageExportJobOptions, "getImageExportJobOptions") + err = core.ValidateStruct(getClusterNetworkSubnetOptions, "getClusterNetworkSubnetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "image_id": *getImageExportJobOptions.ImageID, - "id": *getImageExportJobOptions.ID, + "cluster_network_id": *getClusterNetworkSubnetOptions.ClusterNetworkID, + "id": *getClusterNetworkSubnetOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getImageExportJobOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetworkSubnet") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetImageExportJob") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getClusterNetworkSubnetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -5035,12 +5190,12 @@ func (vpc *VpcV1) GetImageExportJobWithContext(ctx context.Context, getImageExpo var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_image_export_job", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_cluster_network_subnet", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageExportJob) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnet) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5051,58 +5206,61 @@ func (vpc *VpcV1) GetImageExportJobWithContext(ctx context.Context, getImageExpo return } -// UpdateImageExportJob : Update an image export job -// This request updates an image export job with the information in a provided image export job patch. The image export -// job patch object is structured in the same way as a retrieved image export job and contains only the information to -// be updated. -func (vpc *VpcV1) UpdateImageExportJob(updateImageExportJobOptions *UpdateImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateImageExportJobWithContext(context.Background(), updateImageExportJobOptions) +// UpdateClusterNetworkSubnet : Update a cluster network subnet +// This request updates a cluster network subnet with the information provided in a cluster network subnet patch object. +// The patch object is structured in the same way as a retrieved cluster network subnet and needs to contain only the +// information to be updated. +func (vpc *VpcV1) UpdateClusterNetworkSubnet(updateClusterNetworkSubnetOptions *UpdateClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateClusterNetworkSubnetWithContext(context.Background(), updateClusterNetworkSubnetOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateImageExportJobWithContext is an alternate form of the UpdateImageExportJob method which supports a Context parameter -func (vpc *VpcV1) UpdateImageExportJobWithContext(ctx context.Context, updateImageExportJobOptions *UpdateImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateImageExportJobOptions, "updateImageExportJobOptions cannot be nil") +// UpdateClusterNetworkSubnetWithContext is an alternate form of the UpdateClusterNetworkSubnet method which supports a Context parameter +func (vpc *VpcV1) UpdateClusterNetworkSubnetWithContext(ctx context.Context, updateClusterNetworkSubnetOptions *UpdateClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateClusterNetworkSubnetOptions, "updateClusterNetworkSubnetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateImageExportJobOptions, "updateImageExportJobOptions") + err = core.ValidateStruct(updateClusterNetworkSubnetOptions, "updateClusterNetworkSubnetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "image_id": *updateImageExportJobOptions.ImageID, - "id": *updateImageExportJobOptions.ID, + "cluster_network_id": *updateClusterNetworkSubnetOptions.ClusterNetworkID, + "id": *updateClusterNetworkSubnetOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateImageExportJobOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateClusterNetworkSubnet") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateImageExportJob") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateClusterNetworkSubnetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateClusterNetworkSubnetOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateClusterNetworkSubnetOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateImageExportJobOptions.ImageExportJobPatch) + _, err = builder.SetBodyContentJSON(updateClusterNetworkSubnetOptions.ClusterNetworkSubnetPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -5117,12 +5275,12 @@ func (vpc *VpcV1) UpdateImageExportJobWithContext(ctx context.Context, updateIma var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_image_export_job", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_cluster_network_subnet", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageExportJob) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnet) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5133,49 +5291,57 @@ func (vpc *VpcV1) UpdateImageExportJobWithContext(ctx context.Context, updateIma return } -// ListOperatingSystems : List operating systems -// This request lists operating systems in the region. -func (vpc *VpcV1) ListOperatingSystems(listOperatingSystemsOptions *ListOperatingSystemsOptions) (result *OperatingSystemCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListOperatingSystemsWithContext(context.Background(), listOperatingSystemsOptions) +// DeleteClusterNetwork : Delete a cluster network +// This request deletes a cluster network. This operation cannot be reversed. +// +// For this request to succeed, virtual server instances must not reside in this cluster network. +func (vpc *VpcV1) DeleteClusterNetwork(deleteClusterNetworkOptions *DeleteClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteClusterNetworkWithContext(context.Background(), deleteClusterNetworkOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListOperatingSystemsWithContext is an alternate form of the ListOperatingSystems method which supports a Context parameter -func (vpc *VpcV1) ListOperatingSystemsWithContext(ctx context.Context, listOperatingSystemsOptions *ListOperatingSystemsOptions) (result *OperatingSystemCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listOperatingSystemsOptions, "listOperatingSystemsOptions") +// DeleteClusterNetworkWithContext is an alternate form of the DeleteClusterNetwork method which supports a Context parameter +func (vpc *VpcV1) DeleteClusterNetworkWithContext(ctx context.Context, deleteClusterNetworkOptions *DeleteClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteClusterNetworkOptions, "deleteClusterNetworkOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteClusterNetworkOptions, "deleteClusterNetworkOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "id": *deleteClusterNetworkOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/operating_systems`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listOperatingSystemsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteClusterNetwork") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListOperatingSystems") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteClusterNetworkOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + if deleteClusterNetworkOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteClusterNetworkOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listOperatingSystemsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listOperatingSystemsOptions.Start)) - } - if listOperatingSystemsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listOperatingSystemsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -5186,12 +5352,12 @@ func (vpc *VpcV1) ListOperatingSystemsWithContext(ctx context.Context, listOpera var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_operating_systems", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_cluster_network", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalOperatingSystemCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetwork) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5202,53 +5368,137 @@ func (vpc *VpcV1) ListOperatingSystemsWithContext(ctx context.Context, listOpera return } -// GetOperatingSystem : Retrieve an operating system -// This request retrieves a single operating system specified by the name in the URL. -func (vpc *VpcV1) GetOperatingSystem(getOperatingSystemOptions *GetOperatingSystemOptions) (result *OperatingSystem, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetOperatingSystemWithContext(context.Background(), getOperatingSystemOptions) +// GetClusterNetwork : Retrieve a cluster network +// This request retrieves a single cluster network specified by the identifier in the URL. +func (vpc *VpcV1) GetClusterNetwork(getClusterNetworkOptions *GetClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetClusterNetworkWithContext(context.Background(), getClusterNetworkOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetOperatingSystemWithContext is an alternate form of the GetOperatingSystem method which supports a Context parameter -func (vpc *VpcV1) GetOperatingSystemWithContext(ctx context.Context, getOperatingSystemOptions *GetOperatingSystemOptions) (result *OperatingSystem, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getOperatingSystemOptions, "getOperatingSystemOptions cannot be nil") +// GetClusterNetworkWithContext is an alternate form of the GetClusterNetwork method which supports a Context parameter +func (vpc *VpcV1) GetClusterNetworkWithContext(ctx context.Context, getClusterNetworkOptions *GetClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getClusterNetworkOptions, "getClusterNetworkOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getOperatingSystemOptions, "getOperatingSystemOptions") + err = core.ValidateStruct(getClusterNetworkOptions, "getClusterNetworkOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "name": *getOperatingSystemOptions.Name, + "id": *getClusterNetworkOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/operating_systems/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getOperatingSystemOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetwork") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetOperatingSystem") + for headerName, headerValue := range getClusterNetworkOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "get_cluster_network", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetwork) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// UpdateClusterNetwork : Update a cluster +// This request updates a cluster network with the information provided in a cluster network patch object. The patch +// object is structured in the same way as a retrieved cluster network and needs to contain only the information to be +// updated. +func (vpc *VpcV1) UpdateClusterNetwork(updateClusterNetworkOptions *UpdateClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateClusterNetworkWithContext(context.Background(), updateClusterNetworkOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// UpdateClusterNetworkWithContext is an alternate form of the UpdateClusterNetwork method which supports a Context parameter +func (vpc *VpcV1) UpdateClusterNetworkWithContext(ctx context.Context, updateClusterNetworkOptions *UpdateClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateClusterNetworkOptions, "updateClusterNetworkOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(updateClusterNetworkOptions, "updateClusterNetworkOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "id": *updateClusterNetworkOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateClusterNetwork") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range updateClusterNetworkOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateClusterNetworkOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateClusterNetworkOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateClusterNetworkOptions.ClusterNetworkPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -5258,12 +5508,12 @@ func (vpc *VpcV1) GetOperatingSystemWithContext(ctx context.Context, getOperatin var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_operating_system", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_cluster_network", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalOperatingSystem) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetwork) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5274,18 +5524,18 @@ func (vpc *VpcV1) GetOperatingSystemWithContext(ctx context.Context, getOperatin return } -// ListKeys : List keys -// This request lists keys in the region. A key contains a public SSH key which may be installed on instances when they -// are created. Private keys are not stored. -func (vpc *VpcV1) ListKeys(listKeysOptions *ListKeysOptions) (result *KeyCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListKeysWithContext(context.Background(), listKeysOptions) +// ListDedicatedHostGroups : List dedicated host groups +// This request lists dedicated host groups in the region. Each dedicated host must belong to exactly one group, which +// controls placement of instances. Dedicated host groups do not span zones. +func (vpc *VpcV1) ListDedicatedHostGroups(listDedicatedHostGroupsOptions *ListDedicatedHostGroupsOptions) (result *DedicatedHostGroupCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListDedicatedHostGroupsWithContext(context.Background(), listDedicatedHostGroupsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListKeysWithContext is an alternate form of the ListKeys method which supports a Context parameter -func (vpc *VpcV1) ListKeysWithContext(ctx context.Context, listKeysOptions *ListKeysOptions) (result *KeyCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listKeysOptions, "listKeysOptions") +// ListDedicatedHostGroupsWithContext is an alternate form of the ListDedicatedHostGroups method which supports a Context parameter +func (vpc *VpcV1) ListDedicatedHostGroupsWithContext(ctx context.Context, listDedicatedHostGroupsOptions *ListDedicatedHostGroupsOptions) (result *DedicatedHostGroupCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listDedicatedHostGroupsOptions, "listDedicatedHostGroupsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -5294,32 +5544,38 @@ func (vpc *VpcV1) ListKeysWithContext(ctx context.Context, listKeysOptions *List builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listKeysOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListDedicatedHostGroups") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListKeys") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listDedicatedHostGroupsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listKeysOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listKeysOptions.Start)) + if listDedicatedHostGroupsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listDedicatedHostGroupsOptions.Start)) } - if listKeysOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listKeysOptions.Limit)) + if listDedicatedHostGroupsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listDedicatedHostGroupsOptions.Limit)) } - if listKeysOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listKeysOptions.ResourceGroupID)) + if listDedicatedHostGroupsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listDedicatedHostGroupsOptions.ResourceGroupID)) + } + if listDedicatedHostGroupsOptions.ZoneName != nil { + builder.AddQuery("zone.name", fmt.Sprint(*listDedicatedHostGroupsOptions.ZoneName)) + } + if listDedicatedHostGroupsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listDedicatedHostGroupsOptions.Name)) } request, err := builder.Build() @@ -5331,12 +5587,12 @@ func (vpc *VpcV1) ListKeysWithContext(ctx context.Context, listKeysOptions *List var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_keys", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_dedicated_host_groups", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKeyCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostGroupCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5347,24 +5603,22 @@ func (vpc *VpcV1) ListKeysWithContext(ctx context.Context, listKeysOptions *List return } -// CreateKey : Create a key -// This request creates a new SSH key from an key prototype object. The prototype object is structured in the same way -// as a retrieved key, and contains the information necessary to create the new key. The public key value must be -// provided. -func (vpc *VpcV1) CreateKey(createKeyOptions *CreateKeyOptions) (result *Key, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateKeyWithContext(context.Background(), createKeyOptions) +// CreateDedicatedHostGroup : Create a dedicated host group +// This request creates a new dedicated host group. +func (vpc *VpcV1) CreateDedicatedHostGroup(createDedicatedHostGroupOptions *CreateDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateDedicatedHostGroupWithContext(context.Background(), createDedicatedHostGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateKeyWithContext is an alternate form of the CreateKey method which supports a Context parameter -func (vpc *VpcV1) CreateKeyWithContext(ctx context.Context, createKeyOptions *CreateKeyOptions) (result *Key, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createKeyOptions, "createKeyOptions cannot be nil") +// CreateDedicatedHostGroupWithContext is an alternate form of the CreateDedicatedHostGroup method which supports a Context parameter +func (vpc *VpcV1) CreateDedicatedHostGroupWithContext(ctx context.Context, createDedicatedHostGroupOptions *CreateDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createDedicatedHostGroupOptions, "createDedicatedHostGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createKeyOptions, "createKeyOptions") + err = core.ValidateStruct(createDedicatedHostGroupOptions, "createDedicatedHostGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -5373,18 +5627,18 @@ func (vpc *VpcV1) CreateKeyWithContext(ctx context.Context, createKeyOptions *Cr builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateDedicatedHostGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createDedicatedHostGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -5394,17 +5648,20 @@ func (vpc *VpcV1) CreateKeyWithContext(ctx context.Context, createKeyOptions *Cr builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createKeyOptions.PublicKey != nil { - body["public_key"] = createKeyOptions.PublicKey + if createDedicatedHostGroupOptions.Class != nil { + body["class"] = createDedicatedHostGroupOptions.Class } - if createKeyOptions.Name != nil { - body["name"] = createKeyOptions.Name + if createDedicatedHostGroupOptions.Family != nil { + body["family"] = createDedicatedHostGroupOptions.Family } - if createKeyOptions.ResourceGroup != nil { - body["resource_group"] = createKeyOptions.ResourceGroup + if createDedicatedHostGroupOptions.Zone != nil { + body["zone"] = createDedicatedHostGroupOptions.Zone } - if createKeyOptions.Type != nil { - body["type"] = createKeyOptions.Type + if createDedicatedHostGroupOptions.Name != nil { + body["name"] = createDedicatedHostGroupOptions.Name + } + if createDedicatedHostGroupOptions.ResourceGroup != nil { + body["resource_group"] = createDedicatedHostGroupOptions.ResourceGroup } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -5421,12 +5678,12 @@ func (vpc *VpcV1) CreateKeyWithContext(ctx context.Context, createKeyOptions *Cr var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_dedicated_host_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKey) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5437,46 +5694,46 @@ func (vpc *VpcV1) CreateKeyWithContext(ctx context.Context, createKeyOptions *Cr return } -// DeleteKey : Delete a key -// This request deletes a key. This operation cannot be reversed. -func (vpc *VpcV1) DeleteKey(deleteKeyOptions *DeleteKeyOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteKeyWithContext(context.Background(), deleteKeyOptions) +// DeleteDedicatedHostGroup : Delete a dedicated host group +// This request deletes a dedicated host group. +func (vpc *VpcV1) DeleteDedicatedHostGroup(deleteDedicatedHostGroupOptions *DeleteDedicatedHostGroupOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteDedicatedHostGroupWithContext(context.Background(), deleteDedicatedHostGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteKeyWithContext is an alternate form of the DeleteKey method which supports a Context parameter -func (vpc *VpcV1) DeleteKeyWithContext(ctx context.Context, deleteKeyOptions *DeleteKeyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteKeyOptions, "deleteKeyOptions cannot be nil") +// DeleteDedicatedHostGroupWithContext is an alternate form of the DeleteDedicatedHostGroup method which supports a Context parameter +func (vpc *VpcV1) DeleteDedicatedHostGroupWithContext(ctx context.Context, deleteDedicatedHostGroupOptions *DeleteDedicatedHostGroupOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteDedicatedHostGroupOptions, "deleteDedicatedHostGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteKeyOptions, "deleteKeyOptions") + err = core.ValidateStruct(deleteDedicatedHostGroupOptions, "deleteDedicatedHostGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteKeyOptions.ID, + "id": *deleteDedicatedHostGroupOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteDedicatedHostGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteDedicatedHostGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -5491,7 +5748,7 @@ func (vpc *VpcV1) DeleteKeyWithContext(ctx context.Context, deleteKeyOptions *De response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_dedicated_host_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -5499,46 +5756,46 @@ func (vpc *VpcV1) DeleteKeyWithContext(ctx context.Context, deleteKeyOptions *De return } -// GetKey : Retrieve a key -// This request retrieves a single key specified by the identifier in the URL. -func (vpc *VpcV1) GetKey(getKeyOptions *GetKeyOptions) (result *Key, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetKeyWithContext(context.Background(), getKeyOptions) +// GetDedicatedHostGroup : Retrieve a dedicated host group +// This request retrieves a single dedicated host group specified by the identifier in the URL. +func (vpc *VpcV1) GetDedicatedHostGroup(getDedicatedHostGroupOptions *GetDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetDedicatedHostGroupWithContext(context.Background(), getDedicatedHostGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetKeyWithContext is an alternate form of the GetKey method which supports a Context parameter -func (vpc *VpcV1) GetKeyWithContext(ctx context.Context, getKeyOptions *GetKeyOptions) (result *Key, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getKeyOptions, "getKeyOptions cannot be nil") +// GetDedicatedHostGroupWithContext is an alternate form of the GetDedicatedHostGroup method which supports a Context parameter +func (vpc *VpcV1) GetDedicatedHostGroupWithContext(ctx context.Context, getDedicatedHostGroupOptions *GetDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getDedicatedHostGroupOptions, "getDedicatedHostGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getKeyOptions, "getKeyOptions") + err = core.ValidateStruct(getDedicatedHostGroupOptions, "getDedicatedHostGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getKeyOptions.ID, + "id": *getDedicatedHostGroupOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetDedicatedHostGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getDedicatedHostGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -5555,12 +5812,12 @@ func (vpc *VpcV1) GetKeyWithContext(ctx context.Context, getKeyOptions *GetKeyOp var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_dedicated_host_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKey) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5571,46 +5828,48 @@ func (vpc *VpcV1) GetKeyWithContext(ctx context.Context, getKeyOptions *GetKeyOp return } -// UpdateKey : Update a key -// This request updates a key's name. -func (vpc *VpcV1) UpdateKey(updateKeyOptions *UpdateKeyOptions) (result *Key, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateKeyWithContext(context.Background(), updateKeyOptions) +// UpdateDedicatedHostGroup : Update a dedicated host group +// This request updates a dedicated host group with the information in a provided dedicated host group patch. The +// dedicated host group patch object is structured in the same way as a retrieved dedicated host group and contains only +// the information to be updated. +func (vpc *VpcV1) UpdateDedicatedHostGroup(updateDedicatedHostGroupOptions *UpdateDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateDedicatedHostGroupWithContext(context.Background(), updateDedicatedHostGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateKeyWithContext is an alternate form of the UpdateKey method which supports a Context parameter -func (vpc *VpcV1) UpdateKeyWithContext(ctx context.Context, updateKeyOptions *UpdateKeyOptions) (result *Key, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateKeyOptions, "updateKeyOptions cannot be nil") +// UpdateDedicatedHostGroupWithContext is an alternate form of the UpdateDedicatedHostGroup method which supports a Context parameter +func (vpc *VpcV1) UpdateDedicatedHostGroupWithContext(ctx context.Context, updateDedicatedHostGroupOptions *UpdateDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateDedicatedHostGroupOptions, "updateDedicatedHostGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateKeyOptions, "updateKeyOptions") + err = core.ValidateStruct(updateDedicatedHostGroupOptions, "updateDedicatedHostGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateKeyOptions.ID, + "id": *updateDedicatedHostGroupOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateKeyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateDedicatedHostGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateKey") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateDedicatedHostGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -5619,7 +5878,7 @@ func (vpc *VpcV1) UpdateKeyWithContext(ctx context.Context, updateKeyOptions *Up builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateKeyOptions.KeyPatch) + _, err = builder.SetBodyContentJSON(updateDedicatedHostGroupOptions.DedicatedHostGroupPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -5634,12 +5893,12 @@ func (vpc *VpcV1) UpdateKeyWithContext(ctx context.Context, updateKeyOptions *Up var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_key", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_dedicated_host_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKey) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5650,18 +5909,18 @@ func (vpc *VpcV1) UpdateKeyWithContext(ctx context.Context, updateKeyOptions *Up return } -// ListInstanceProfiles : List instance profiles -// This request lists provisionable [instance profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) in the -// region. An instance profile specifies the performance characteristics and pricing model for an instance. -func (vpc *VpcV1) ListInstanceProfiles(listInstanceProfilesOptions *ListInstanceProfilesOptions) (result *InstanceProfileCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceProfilesWithContext(context.Background(), listInstanceProfilesOptions) +// ListDedicatedHostProfiles : List dedicated host profiles +// This request lists provisionable [dedicated host profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-dh-profiles) in +// the region. A dedicated host profile specifies the hardware characteristics for a dedicated host. +func (vpc *VpcV1) ListDedicatedHostProfiles(listDedicatedHostProfilesOptions *ListDedicatedHostProfilesOptions) (result *DedicatedHostProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListDedicatedHostProfilesWithContext(context.Background(), listDedicatedHostProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceProfilesWithContext is an alternate form of the ListInstanceProfiles method which supports a Context parameter -func (vpc *VpcV1) ListInstanceProfilesWithContext(ctx context.Context, listInstanceProfilesOptions *ListInstanceProfilesOptions) (result *InstanceProfileCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listInstanceProfilesOptions, "listInstanceProfilesOptions") +// ListDedicatedHostProfilesWithContext is an alternate form of the ListDedicatedHostProfiles method which supports a Context parameter +func (vpc *VpcV1) ListDedicatedHostProfilesWithContext(ctx context.Context, listDedicatedHostProfilesOptions *ListDedicatedHostProfilesOptions) (result *DedicatedHostProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listDedicatedHostProfilesOptions, "listDedicatedHostProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -5670,24 +5929,30 @@ func (vpc *VpcV1) ListInstanceProfilesWithContext(ctx context.Context, listInsta builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/profiles`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/profiles`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceProfilesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListDedicatedHostProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceProfiles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listDedicatedHostProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listDedicatedHostProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listDedicatedHostProfilesOptions.Start)) + } + if listDedicatedHostProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listDedicatedHostProfilesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -5698,12 +5963,12 @@ func (vpc *VpcV1) ListInstanceProfilesWithContext(ctx context.Context, listInsta var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_profiles", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_dedicated_host_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceProfileCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5714,46 +5979,46 @@ func (vpc *VpcV1) ListInstanceProfilesWithContext(ctx context.Context, listInsta return } -// GetInstanceProfile : Retrieve an instance profile -// This request retrieves a single instance profile specified by the name in the URL. -func (vpc *VpcV1) GetInstanceProfile(getInstanceProfileOptions *GetInstanceProfileOptions) (result *InstanceProfile, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceProfileWithContext(context.Background(), getInstanceProfileOptions) +// GetDedicatedHostProfile : Retrieve a dedicated host profile +// This request retrieves a single dedicated host profile specified by the name in the URL. +func (vpc *VpcV1) GetDedicatedHostProfile(getDedicatedHostProfileOptions *GetDedicatedHostProfileOptions) (result *DedicatedHostProfile, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetDedicatedHostProfileWithContext(context.Background(), getDedicatedHostProfileOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceProfileWithContext is an alternate form of the GetInstanceProfile method which supports a Context parameter -func (vpc *VpcV1) GetInstanceProfileWithContext(ctx context.Context, getInstanceProfileOptions *GetInstanceProfileOptions) (result *InstanceProfile, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceProfileOptions, "getInstanceProfileOptions cannot be nil") +// GetDedicatedHostProfileWithContext is an alternate form of the GetDedicatedHostProfile method which supports a Context parameter +func (vpc *VpcV1) GetDedicatedHostProfileWithContext(ctx context.Context, getDedicatedHostProfileOptions *GetDedicatedHostProfileOptions) (result *DedicatedHostProfile, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getDedicatedHostProfileOptions, "getDedicatedHostProfileOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceProfileOptions, "getInstanceProfileOptions") + err = core.ValidateStruct(getDedicatedHostProfileOptions, "getDedicatedHostProfileOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "name": *getInstanceProfileOptions.Name, + "name": *getDedicatedHostProfileOptions.Name, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/profiles/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/profiles/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetDedicatedHostProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getDedicatedHostProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -5770,12 +6035,12 @@ func (vpc *VpcV1) GetInstanceProfileWithContext(ctx context.Context, getInstance var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_profile", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_dedicated_host_profile", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceProfile) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostProfile) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5786,17 +6051,17 @@ func (vpc *VpcV1) GetInstanceProfileWithContext(ctx context.Context, getInstance return } -// ListInstanceTemplates : List instance templates -// This request lists instance templates in the region. -func (vpc *VpcV1) ListInstanceTemplates(listInstanceTemplatesOptions *ListInstanceTemplatesOptions) (result *InstanceTemplateCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceTemplatesWithContext(context.Background(), listInstanceTemplatesOptions) +// ListDedicatedHosts : List dedicated hosts +// This request lists dedicated hosts in the region. +func (vpc *VpcV1) ListDedicatedHosts(listDedicatedHostsOptions *ListDedicatedHostsOptions) (result *DedicatedHostCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListDedicatedHostsWithContext(context.Background(), listDedicatedHostsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceTemplatesWithContext is an alternate form of the ListInstanceTemplates method which supports a Context parameter -func (vpc *VpcV1) ListInstanceTemplatesWithContext(ctx context.Context, listInstanceTemplatesOptions *ListInstanceTemplatesOptions) (result *InstanceTemplateCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listInstanceTemplatesOptions, "listInstanceTemplatesOptions") +// ListDedicatedHostsWithContext is an alternate form of the ListDedicatedHosts method which supports a Context parameter +func (vpc *VpcV1) ListDedicatedHostsWithContext(ctx context.Context, listDedicatedHostsOptions *ListDedicatedHostsOptions) (result *DedicatedHostCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listDedicatedHostsOptions, "listDedicatedHostsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -5805,24 +6070,42 @@ func (vpc *VpcV1) ListInstanceTemplatesWithContext(ctx context.Context, listInst builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceTemplatesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListDedicatedHosts") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceTemplates") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listDedicatedHostsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listDedicatedHostsOptions.DedicatedHostGroupID != nil { + builder.AddQuery("dedicated_host_group.id", fmt.Sprint(*listDedicatedHostsOptions.DedicatedHostGroupID)) + } + if listDedicatedHostsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listDedicatedHostsOptions.Start)) + } + if listDedicatedHostsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listDedicatedHostsOptions.Limit)) + } + if listDedicatedHostsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listDedicatedHostsOptions.ResourceGroupID)) + } + if listDedicatedHostsOptions.ZoneName != nil { + builder.AddQuery("zone.name", fmt.Sprint(*listDedicatedHostsOptions.ZoneName)) + } + if listDedicatedHostsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listDedicatedHostsOptions.Name)) + } request, err := builder.Build() if err != nil { @@ -5833,12 +6116,12 @@ func (vpc *VpcV1) ListInstanceTemplatesWithContext(ctx context.Context, listInst var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_templates", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_dedicated_hosts", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceTemplateCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5849,26 +6132,22 @@ func (vpc *VpcV1) ListInstanceTemplatesWithContext(ctx context.Context, listInst return } -// CreateInstanceTemplate : Create an instance template -// This request creates a new instance template. The prototype object is structured in the same way as a retrieved -// instance template, and contains the information necessary to provision a new instance from the template. -// -// If a `source_template` is specified in the prototype object, its contents are copied into the new template prior to -// copying any other properties provided in the prototype object. -func (vpc *VpcV1) CreateInstanceTemplate(createInstanceTemplateOptions *CreateInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateInstanceTemplateWithContext(context.Background(), createInstanceTemplateOptions) +// CreateDedicatedHost : Create a dedicated host +// This request creates a new dedicated host. +func (vpc *VpcV1) CreateDedicatedHost(createDedicatedHostOptions *CreateDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateDedicatedHostWithContext(context.Background(), createDedicatedHostOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateInstanceTemplateWithContext is an alternate form of the CreateInstanceTemplate method which supports a Context parameter -func (vpc *VpcV1) CreateInstanceTemplateWithContext(ctx context.Context, createInstanceTemplateOptions *CreateInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createInstanceTemplateOptions, "createInstanceTemplateOptions cannot be nil") +// CreateDedicatedHostWithContext is an alternate form of the CreateDedicatedHost method which supports a Context parameter +func (vpc *VpcV1) CreateDedicatedHostWithContext(ctx context.Context, createDedicatedHostOptions *CreateDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createDedicatedHostOptions, "createDedicatedHostOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createInstanceTemplateOptions, "createInstanceTemplateOptions") + err = core.ValidateStruct(createDedicatedHostOptions, "createDedicatedHostOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -5877,18 +6156,18 @@ func (vpc *VpcV1) CreateInstanceTemplateWithContext(ctx context.Context, createI builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createInstanceTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateDedicatedHost") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createDedicatedHostOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -5897,7 +6176,7 @@ func (vpc *VpcV1) CreateInstanceTemplateWithContext(ctx context.Context, createI builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createInstanceTemplateOptions.InstanceTemplatePrototype) + _, err = builder.SetBodyContentJSON(createDedicatedHostOptions.DedicatedHostPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -5912,12 +6191,12 @@ func (vpc *VpcV1) CreateInstanceTemplateWithContext(ctx context.Context, createI var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_instance_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_dedicated_host", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceTemplate) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHost) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -5928,48 +6207,51 @@ func (vpc *VpcV1) CreateInstanceTemplateWithContext(ctx context.Context, createI return } -// DeleteInstanceTemplate : Delete an instance template -// This request deletes the instance template. This operation cannot be reversed. -func (vpc *VpcV1) DeleteInstanceTemplate(deleteInstanceTemplateOptions *DeleteInstanceTemplateOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteInstanceTemplateWithContext(context.Background(), deleteInstanceTemplateOptions) +// ListDedicatedHostDisks : List disks on a dedicated host +// This request lists disks on a dedicated host. A disk is a physical device that is locally attached to the compute +// node. By default, the listed disks are sorted by their +// `created_at` property values, with the newest disk first. +func (vpc *VpcV1) ListDedicatedHostDisks(listDedicatedHostDisksOptions *ListDedicatedHostDisksOptions) (result *DedicatedHostDiskCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListDedicatedHostDisksWithContext(context.Background(), listDedicatedHostDisksOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteInstanceTemplateWithContext is an alternate form of the DeleteInstanceTemplate method which supports a Context parameter -func (vpc *VpcV1) DeleteInstanceTemplateWithContext(ctx context.Context, deleteInstanceTemplateOptions *DeleteInstanceTemplateOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteInstanceTemplateOptions, "deleteInstanceTemplateOptions cannot be nil") +// ListDedicatedHostDisksWithContext is an alternate form of the ListDedicatedHostDisks method which supports a Context parameter +func (vpc *VpcV1) ListDedicatedHostDisksWithContext(ctx context.Context, listDedicatedHostDisksOptions *ListDedicatedHostDisksOptions) (result *DedicatedHostDiskCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listDedicatedHostDisksOptions, "listDedicatedHostDisksOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteInstanceTemplateOptions, "deleteInstanceTemplateOptions") + err = core.ValidateStruct(listDedicatedHostDisksOptions, "listDedicatedHostDisksOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteInstanceTemplateOptions.ID, + "dedicated_host_id": *listDedicatedHostDisksOptions.DedicatedHostID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{dedicated_host_id}/disks`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteInstanceTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListDedicatedHostDisks") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listDedicatedHostDisksOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -5980,56 +6262,66 @@ func (vpc *VpcV1) DeleteInstanceTemplateWithContext(ctx context.Context, deleteI return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_instance_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_dedicated_host_disks", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostDiskCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetInstanceTemplate : Retrieve an instance template -// This request retrieves a single instance template specified by the identifier in the URL. -func (vpc *VpcV1) GetInstanceTemplate(getInstanceTemplateOptions *GetInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceTemplateWithContext(context.Background(), getInstanceTemplateOptions) +// GetDedicatedHostDisk : Retrieve a dedicated host disk +// This request retrieves a single dedicated host disk specified by the identifier in the URL. +func (vpc *VpcV1) GetDedicatedHostDisk(getDedicatedHostDiskOptions *GetDedicatedHostDiskOptions) (result *DedicatedHostDisk, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetDedicatedHostDiskWithContext(context.Background(), getDedicatedHostDiskOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceTemplateWithContext is an alternate form of the GetInstanceTemplate method which supports a Context parameter -func (vpc *VpcV1) GetInstanceTemplateWithContext(ctx context.Context, getInstanceTemplateOptions *GetInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceTemplateOptions, "getInstanceTemplateOptions cannot be nil") +// GetDedicatedHostDiskWithContext is an alternate form of the GetDedicatedHostDisk method which supports a Context parameter +func (vpc *VpcV1) GetDedicatedHostDiskWithContext(ctx context.Context, getDedicatedHostDiskOptions *GetDedicatedHostDiskOptions) (result *DedicatedHostDisk, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getDedicatedHostDiskOptions, "getDedicatedHostDiskOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceTemplateOptions, "getInstanceTemplateOptions") + err = core.ValidateStruct(getDedicatedHostDiskOptions, "getDedicatedHostDiskOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getInstanceTemplateOptions.ID, + "dedicated_host_id": *getDedicatedHostDiskOptions.DedicatedHostID, + "id": *getDedicatedHostDiskOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{dedicated_host_id}/disks/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetDedicatedHostDisk") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getDedicatedHostDiskOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -6046,12 +6338,12 @@ func (vpc *VpcV1) GetInstanceTemplateWithContext(ctx context.Context, getInstanc var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_dedicated_host_disk", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceTemplate) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostDisk) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6062,48 +6354,47 @@ func (vpc *VpcV1) GetInstanceTemplateWithContext(ctx context.Context, getInstanc return } -// UpdateInstanceTemplate : Update an instance template -// This request updates an instance template with the information provided in the instance template patch. The instance -// template patch object is structured in the same way as a retrieved instance template and contains only the -// information to be updated. -func (vpc *VpcV1) UpdateInstanceTemplate(updateInstanceTemplateOptions *UpdateInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateInstanceTemplateWithContext(context.Background(), updateInstanceTemplateOptions) +// UpdateDedicatedHostDisk : Update a dedicated host disk +// This request updates the dedicated host disk with the information in a provided patch. +func (vpc *VpcV1) UpdateDedicatedHostDisk(updateDedicatedHostDiskOptions *UpdateDedicatedHostDiskOptions) (result *DedicatedHostDisk, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateDedicatedHostDiskWithContext(context.Background(), updateDedicatedHostDiskOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateInstanceTemplateWithContext is an alternate form of the UpdateInstanceTemplate method which supports a Context parameter -func (vpc *VpcV1) UpdateInstanceTemplateWithContext(ctx context.Context, updateInstanceTemplateOptions *UpdateInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateInstanceTemplateOptions, "updateInstanceTemplateOptions cannot be nil") +// UpdateDedicatedHostDiskWithContext is an alternate form of the UpdateDedicatedHostDisk method which supports a Context parameter +func (vpc *VpcV1) UpdateDedicatedHostDiskWithContext(ctx context.Context, updateDedicatedHostDiskOptions *UpdateDedicatedHostDiskOptions) (result *DedicatedHostDisk, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateDedicatedHostDiskOptions, "updateDedicatedHostDiskOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateInstanceTemplateOptions, "updateInstanceTemplateOptions") + err = core.ValidateStruct(updateDedicatedHostDiskOptions, "updateDedicatedHostDiskOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateInstanceTemplateOptions.ID, + "dedicated_host_id": *updateDedicatedHostDiskOptions.DedicatedHostID, + "id": *updateDedicatedHostDiskOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{dedicated_host_id}/disks/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateInstanceTemplateOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateDedicatedHostDisk") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceTemplate") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateDedicatedHostDiskOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -6112,7 +6403,7 @@ func (vpc *VpcV1) UpdateInstanceTemplateWithContext(ctx context.Context, updateI builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateInstanceTemplateOptions.InstanceTemplatePatch) + _, err = builder.SetBodyContentJSON(updateDedicatedHostDiskOptions.DedicatedHostDiskPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -6127,12 +6418,12 @@ func (vpc *VpcV1) UpdateInstanceTemplateWithContext(ctx context.Context, updateI var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_instance_template", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_dedicated_host_disk", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceTemplate) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostDisk) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6143,103 +6434,52 @@ func (vpc *VpcV1) UpdateInstanceTemplateWithContext(ctx context.Context, updateI return } -// ListInstances : List instances -// This request lists instances in the region. -func (vpc *VpcV1) ListInstances(listInstancesOptions *ListInstancesOptions) (result *InstanceCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstancesWithContext(context.Background(), listInstancesOptions) +// DeleteDedicatedHost : Delete a dedicated host +// This request deletes a dedicated host. This operation cannot be reversed. For this request to succeed, `instances` +// must be empty and `instance_placement_enabled` must be `false`. +func (vpc *VpcV1) DeleteDedicatedHost(deleteDedicatedHostOptions *DeleteDedicatedHostOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteDedicatedHostWithContext(context.Background(), deleteDedicatedHostOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstancesWithContext is an alternate form of the ListInstances method which supports a Context parameter -func (vpc *VpcV1) ListInstancesWithContext(ctx context.Context, listInstancesOptions *ListInstancesOptions) (result *InstanceCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listInstancesOptions, "listInstancesOptions") +// DeleteDedicatedHostWithContext is an alternate form of the DeleteDedicatedHost method which supports a Context parameter +func (vpc *VpcV1) DeleteDedicatedHostWithContext(ctx context.Context, deleteDedicatedHostOptions *DeleteDedicatedHostOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteDedicatedHostOptions, "deleteDedicatedHostOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteDedicatedHostOptions, "deleteDedicatedHostOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "id": *deleteDedicatedHostOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstancesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteDedicatedHost") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstances") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteDedicatedHostOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listInstancesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listInstancesOptions.Start)) - } - if listInstancesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listInstancesOptions.Limit)) - } - if listInstancesOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listInstancesOptions.ResourceGroupID)) - } - if listInstancesOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listInstancesOptions.Name)) - } - if listInstancesOptions.ClusterNetworkID != nil { - builder.AddQuery("cluster_network.id", fmt.Sprint(*listInstancesOptions.ClusterNetworkID)) - } - if listInstancesOptions.ClusterNetworkCRN != nil { - builder.AddQuery("cluster_network.crn", fmt.Sprint(*listInstancesOptions.ClusterNetworkCRN)) - } - if listInstancesOptions.ClusterNetworkName != nil { - builder.AddQuery("cluster_network.name", fmt.Sprint(*listInstancesOptions.ClusterNetworkName)) - } - if listInstancesOptions.DedicatedHostID != nil { - builder.AddQuery("dedicated_host.id", fmt.Sprint(*listInstancesOptions.DedicatedHostID)) - } - if listInstancesOptions.DedicatedHostCRN != nil { - builder.AddQuery("dedicated_host.crn", fmt.Sprint(*listInstancesOptions.DedicatedHostCRN)) - } - if listInstancesOptions.DedicatedHostName != nil { - builder.AddQuery("dedicated_host.name", fmt.Sprint(*listInstancesOptions.DedicatedHostName)) - } - if listInstancesOptions.PlacementGroupID != nil { - builder.AddQuery("placement_group.id", fmt.Sprint(*listInstancesOptions.PlacementGroupID)) - } - if listInstancesOptions.PlacementGroupCRN != nil { - builder.AddQuery("placement_group.crn", fmt.Sprint(*listInstancesOptions.PlacementGroupCRN)) - } - if listInstancesOptions.PlacementGroupName != nil { - builder.AddQuery("placement_group.name", fmt.Sprint(*listInstancesOptions.PlacementGroupName)) - } - if listInstancesOptions.ReservationAffinityPolicy != nil { - builder.AddQuery("reservation_affinity.policy", fmt.Sprint(*listInstancesOptions.ReservationAffinityPolicy)) - } - if listInstancesOptions.ReservationID != nil { - builder.AddQuery("reservation.id", fmt.Sprint(*listInstancesOptions.ReservationID)) - } - if listInstancesOptions.ReservationCRN != nil { - builder.AddQuery("reservation.crn", fmt.Sprint(*listInstancesOptions.ReservationCRN)) - } - if listInstancesOptions.ReservationName != nil { - builder.AddQuery("reservation.name", fmt.Sprint(*listInstancesOptions.ReservationName)) - } - if listInstancesOptions.VPCID != nil { - builder.AddQuery("vpc.id", fmt.Sprint(*listInstancesOptions.VPCID)) - } - if listInstancesOptions.VPCCRN != nil { - builder.AddQuery("vpc.crn", fmt.Sprint(*listInstancesOptions.VPCCRN)) - } - if listInstancesOptions.VPCName != nil { - builder.AddQuery("vpc.name", fmt.Sprint(*listInstancesOptions.VPCName)) - } request, err := builder.Build() if err != nil { @@ -6247,77 +6487,63 @@ func (vpc *VpcV1) ListInstancesWithContext(ctx context.Context, listInstancesOpt return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_instances", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_dedicated_host", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateInstance : Create an instance -// This request provisions a new instance from an instance prototype object. The prototype object is structured in the -// same way as a retrieved instance, and contains the information necessary to provision the new instance. The instance -// is automatically started. -func (vpc *VpcV1) CreateInstance(createInstanceOptions *CreateInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateInstanceWithContext(context.Background(), createInstanceOptions) +// GetDedicatedHost : Retrieve a dedicated host +// This request retrieves a single dedicated host specified by the identifiers in the URL. +func (vpc *VpcV1) GetDedicatedHost(getDedicatedHostOptions *GetDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetDedicatedHostWithContext(context.Background(), getDedicatedHostOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateInstanceWithContext is an alternate form of the CreateInstance method which supports a Context parameter -func (vpc *VpcV1) CreateInstanceWithContext(ctx context.Context, createInstanceOptions *CreateInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createInstanceOptions, "createInstanceOptions cannot be nil") +// GetDedicatedHostWithContext is an alternate form of the GetDedicatedHost method which supports a Context parameter +func (vpc *VpcV1) GetDedicatedHostWithContext(ctx context.Context, getDedicatedHostOptions *GetDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getDedicatedHostOptions, "getDedicatedHostOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createInstanceOptions, "createInstanceOptions") + err = core.ValidateStruct(getDedicatedHostOptions, "getDedicatedHostOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "id": *getDedicatedHostOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createInstanceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetDedicatedHost") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstance") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getDedicatedHostOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createInstanceOptions.InstancePrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -6327,12 +6553,12 @@ func (vpc *VpcV1) CreateInstanceWithContext(ctx context.Context, createInstanceO var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_instance", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_dedicated_host", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstance) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHost) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6343,123 +6569,158 @@ func (vpc *VpcV1) CreateInstanceWithContext(ctx context.Context, createInstanceO return } -// DeleteInstance : Delete an instance -// This request deletes an instance. This operation cannot be reversed. Any floating IPs associated with instance -// network interfaces are implicitly disassociated. All virtual network interfaces with `auto_delete` set to `true` -// targeting instance network attachments on the instance are automatically deleted. All flow log collectors with -// `auto_delete` set to `true` targeting the instance, the instance network attachments, the instance network -// interfaces, or the automatically deleted virtual network interfaces are automatically deleted. -func (vpc *VpcV1) DeleteInstance(deleteInstanceOptions *DeleteInstanceOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteInstanceWithContext(context.Background(), deleteInstanceOptions) +// UpdateDedicatedHost : Update a dedicated host +// This request updates a dedicated host with the information in a provided dedicated host patch. The dedicated host +// patch object is structured in the same way as a retrieved dedicated host and contains only the information to be +// updated. +func (vpc *VpcV1) UpdateDedicatedHost(updateDedicatedHostOptions *UpdateDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateDedicatedHostWithContext(context.Background(), updateDedicatedHostOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteInstanceWithContext is an alternate form of the DeleteInstance method which supports a Context parameter -func (vpc *VpcV1) DeleteInstanceWithContext(ctx context.Context, deleteInstanceOptions *DeleteInstanceOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteInstanceOptions, "deleteInstanceOptions cannot be nil") +// UpdateDedicatedHostWithContext is an alternate form of the UpdateDedicatedHost method which supports a Context parameter +func (vpc *VpcV1) UpdateDedicatedHostWithContext(ctx context.Context, updateDedicatedHostOptions *UpdateDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateDedicatedHostOptions, "updateDedicatedHostOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteInstanceOptions, "deleteInstanceOptions") + err = core.ValidateStruct(updateDedicatedHostOptions, "updateDedicatedHostOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteInstanceOptions.ID, + "id": *updateDedicatedHostOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteInstanceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateDedicatedHost") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstance") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateDedicatedHostOptions.Headers { builder.AddHeader(headerName, headerValue) } - if deleteInstanceOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteInstanceOptions.IfMatch)) - } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateDedicatedHostOptions.DedicatedHostPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_instance", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_dedicated_host", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHost) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetInstance : Retrieve an instance -// This request retrieves a single instance specified by the identifier in the URL. -func (vpc *VpcV1) GetInstance(getInstanceOptions *GetInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceWithContext(context.Background(), getInstanceOptions) +// ListEndpointGateways : List endpoint gateways +// This request lists endpoint gateways in the region. An endpoint gateway maps one or more reserved IPs in a VPC to a +// target outside the VPC. +// +// The endpoint gateways will be sorted by their `created_at` property values, with newest endpoint gateway first. +// Endpoint gateways with identical `created_at` property values will in turn be sorted by ascending `name` property +// values. +func (vpc *VpcV1) ListEndpointGateways(listEndpointGatewaysOptions *ListEndpointGatewaysOptions) (result *EndpointGatewayCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListEndpointGatewaysWithContext(context.Background(), listEndpointGatewaysOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceWithContext is an alternate form of the GetInstance method which supports a Context parameter -func (vpc *VpcV1) GetInstanceWithContext(ctx context.Context, getInstanceOptions *GetInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceOptions, "getInstanceOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getInstanceOptions, "getInstanceOptions") +// ListEndpointGatewaysWithContext is an alternate form of the ListEndpointGateways method which supports a Context parameter +func (vpc *VpcV1) ListEndpointGatewaysWithContext(ctx context.Context, listEndpointGatewaysOptions *ListEndpointGatewaysOptions) (result *EndpointGatewayCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listEndpointGatewaysOptions, "listEndpointGatewaysOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *getInstanceOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListEndpointGateways") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstance") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listEndpointGatewaysOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - request, err := builder.Build() + if listEndpointGatewaysOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listEndpointGatewaysOptions.Name)) + } + if listEndpointGatewaysOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listEndpointGatewaysOptions.Start)) + } + if listEndpointGatewaysOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listEndpointGatewaysOptions.Limit)) + } + if listEndpointGatewaysOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listEndpointGatewaysOptions.ResourceGroupID)) + } + if listEndpointGatewaysOptions.LifecycleState != nil { + builder.AddQuery("lifecycle_state", strings.Join(listEndpointGatewaysOptions.LifecycleState, ",")) + } + if listEndpointGatewaysOptions.VPCID != nil { + builder.AddQuery("vpc.id", fmt.Sprint(*listEndpointGatewaysOptions.VPCID)) + } + if listEndpointGatewaysOptions.VPCCRN != nil { + builder.AddQuery("vpc.crn", fmt.Sprint(*listEndpointGatewaysOptions.VPCCRN)) + } + if listEndpointGatewaysOptions.VPCName != nil { + builder.AddQuery("vpc.name", fmt.Sprint(*listEndpointGatewaysOptions.VPCName)) + } + if listEndpointGatewaysOptions.AllowDnsResolutionBinding != nil { + builder.AddQuery("allow_dns_resolution_binding", fmt.Sprint(*listEndpointGatewaysOptions.AllowDnsResolutionBinding)) + } + + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return @@ -6468,12 +6729,12 @@ func (vpc *VpcV1) GetInstanceWithContext(ctx context.Context, getInstanceOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_endpoint_gateways", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstance) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEndpointGatewayCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6484,59 +6745,75 @@ func (vpc *VpcV1) GetInstanceWithContext(ctx context.Context, getInstanceOptions return } -// UpdateInstance : Update an instance -// This request updates an instance with the information in a provided instance patch. The instance patch object is -// structured in the same way as a retrieved instance and contains only the information to be updated. -func (vpc *VpcV1) UpdateInstance(updateInstanceOptions *UpdateInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateInstanceWithContext(context.Background(), updateInstanceOptions) +// CreateEndpointGateway : Create an endpoint gateway +// This request creates a new endpoint gateway from an endpoint gateway prototype object. The prototype object is +// structured in the same way as a retrieved endpoint gateway, and contains the information necessary to create a new +// endpoint gateway. An endpoint gateway maps one or more reserved IPs in a VPC to a target service outside the VPC. +func (vpc *VpcV1) CreateEndpointGateway(createEndpointGatewayOptions *CreateEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateEndpointGatewayWithContext(context.Background(), createEndpointGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateInstanceWithContext is an alternate form of the UpdateInstance method which supports a Context parameter -func (vpc *VpcV1) UpdateInstanceWithContext(ctx context.Context, updateInstanceOptions *UpdateInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateInstanceOptions, "updateInstanceOptions cannot be nil") +// CreateEndpointGatewayWithContext is an alternate form of the CreateEndpointGateway method which supports a Context parameter +func (vpc *VpcV1) CreateEndpointGatewayWithContext(ctx context.Context, createEndpointGatewayOptions *CreateEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createEndpointGatewayOptions, "createEndpointGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateInstanceOptions, "updateInstanceOptions") + err = core.ValidateStruct(createEndpointGatewayOptions, "createEndpointGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *updateInstanceOptions.ID, - } - - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateInstanceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateEndpointGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstance") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createEndpointGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateInstanceOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateInstanceOptions.IfMatch)) - } + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateInstanceOptions.InstancePatch) + body := make(map[string]interface{}) + if createEndpointGatewayOptions.Target != nil { + body["target"] = createEndpointGatewayOptions.Target + } + if createEndpointGatewayOptions.VPC != nil { + body["vpc"] = createEndpointGatewayOptions.VPC + } + if createEndpointGatewayOptions.AllowDnsResolutionBinding != nil { + body["allow_dns_resolution_binding"] = createEndpointGatewayOptions.AllowDnsResolutionBinding + } + if createEndpointGatewayOptions.Ips != nil { + body["ips"] = createEndpointGatewayOptions.Ips + } + if createEndpointGatewayOptions.Name != nil { + body["name"] = createEndpointGatewayOptions.Name + } + if createEndpointGatewayOptions.ResourceGroup != nil { + body["resource_group"] = createEndpointGatewayOptions.ResourceGroup + } + if createEndpointGatewayOptions.SecurityGroups != nil { + body["security_groups"] = createEndpointGatewayOptions.SecurityGroups + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -6551,12 +6828,12 @@ func (vpc *VpcV1) UpdateInstanceWithContext(ctx context.Context, updateInstanceO var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_instance", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_endpoint_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstance) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEndpointGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6567,53 +6844,61 @@ func (vpc *VpcV1) UpdateInstanceWithContext(ctx context.Context, updateInstanceO return } -// GetInstanceInitialization : Retrieve initialization configuration for an instance -// This request retrieves configuration used to initialize the instance, such as SSH keys and the Windows administrator -// password. These can subsequently be changed on the instance and therefore may not be current. -func (vpc *VpcV1) GetInstanceInitialization(getInstanceInitializationOptions *GetInstanceInitializationOptions) (result *InstanceInitialization, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceInitializationWithContext(context.Background(), getInstanceInitializationOptions) +// ListEndpointGatewayIps : List reserved IPs bound to an endpoint gateway +// This request lists reserved IPs bound to an endpoint gateway. +func (vpc *VpcV1) ListEndpointGatewayIps(listEndpointGatewayIpsOptions *ListEndpointGatewayIpsOptions) (result *ReservedIPCollectionEndpointGatewayContext, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListEndpointGatewayIpsWithContext(context.Background(), listEndpointGatewayIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceInitializationWithContext is an alternate form of the GetInstanceInitialization method which supports a Context parameter -func (vpc *VpcV1) GetInstanceInitializationWithContext(ctx context.Context, getInstanceInitializationOptions *GetInstanceInitializationOptions) (result *InstanceInitialization, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceInitializationOptions, "getInstanceInitializationOptions cannot be nil") +// ListEndpointGatewayIpsWithContext is an alternate form of the ListEndpointGatewayIps method which supports a Context parameter +func (vpc *VpcV1) ListEndpointGatewayIpsWithContext(ctx context.Context, listEndpointGatewayIpsOptions *ListEndpointGatewayIpsOptions) (result *ReservedIPCollectionEndpointGatewayContext, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listEndpointGatewayIpsOptions, "listEndpointGatewayIpsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceInitializationOptions, "getInstanceInitializationOptions") + err = core.ValidateStruct(listEndpointGatewayIpsOptions, "listEndpointGatewayIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getInstanceInitializationOptions.ID, + "endpoint_gateway_id": *listEndpointGatewayIpsOptions.EndpointGatewayID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{id}/initialization`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{endpoint_gateway_id}/ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceInitializationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListEndpointGatewayIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceInitialization") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listEndpointGatewayIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listEndpointGatewayIpsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listEndpointGatewayIpsOptions.Start)) + } + if listEndpointGatewayIpsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listEndpointGatewayIpsOptions.Limit)) + } + if listEndpointGatewayIpsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listEndpointGatewayIpsOptions.Sort)) + } request, err := builder.Build() if err != nil { @@ -6624,12 +6909,12 @@ func (vpc *VpcV1) GetInstanceInitializationWithContext(ctx context.Context, getI var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_initialization", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_endpoint_gateway_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceInitialization) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollectionEndpointGatewayContext) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6640,146 +6925,117 @@ func (vpc *VpcV1) GetInstanceInitializationWithContext(ctx context.Context, getI return } -// CreateInstanceAction : Create an instance action -// This request creates a new action which will be queued up to run as soon as any pending or running actions have -// completed. -func (vpc *VpcV1) CreateInstanceAction(createInstanceActionOptions *CreateInstanceActionOptions) (result *InstanceAction, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateInstanceActionWithContext(context.Background(), createInstanceActionOptions) +// RemoveEndpointGatewayIP : Unbind a reserved IP from an endpoint gateway +// This request unbinds the specified reserved IP from the specified endpoint gateway. If the reserved IP has +// `auto_delete` set to `true`, the reserved IP will be deleted. +func (vpc *VpcV1) RemoveEndpointGatewayIP(removeEndpointGatewayIPOptions *RemoveEndpointGatewayIPOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RemoveEndpointGatewayIPWithContext(context.Background(), removeEndpointGatewayIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateInstanceActionWithContext is an alternate form of the CreateInstanceAction method which supports a Context parameter -func (vpc *VpcV1) CreateInstanceActionWithContext(ctx context.Context, createInstanceActionOptions *CreateInstanceActionOptions) (result *InstanceAction, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createInstanceActionOptions, "createInstanceActionOptions cannot be nil") +// RemoveEndpointGatewayIPWithContext is an alternate form of the RemoveEndpointGatewayIP method which supports a Context parameter +func (vpc *VpcV1) RemoveEndpointGatewayIPWithContext(ctx context.Context, removeEndpointGatewayIPOptions *RemoveEndpointGatewayIPOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(removeEndpointGatewayIPOptions, "removeEndpointGatewayIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createInstanceActionOptions, "createInstanceActionOptions") + err = core.ValidateStruct(removeEndpointGatewayIPOptions, "removeEndpointGatewayIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *createInstanceActionOptions.InstanceID, + "endpoint_gateway_id": *removeEndpointGatewayIPOptions.EndpointGatewayID, + "id": *removeEndpointGatewayIPOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/actions`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{endpoint_gateway_id}/ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createInstanceActionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveEndpointGatewayIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceAction") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range removeEndpointGatewayIPOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createInstanceActionOptions.Type != nil { - body["type"] = createInstanceActionOptions.Type - } - if createInstanceActionOptions.Force != nil { - body["force"] = createInstanceActionOptions.Force - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "create_instance_action", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "remove_endpoint_gateway_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceAction) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListInstanceClusterNetworkAttachments : List cluster network attachments on an instance -// This request lists cluster network attachments on an instance. A cluster network attachment represents a device on -// the instance to which a cluster network interface is attached. -func (vpc *VpcV1) ListInstanceClusterNetworkAttachments(listInstanceClusterNetworkAttachmentsOptions *ListInstanceClusterNetworkAttachmentsOptions) (result *InstanceClusterNetworkAttachmentCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceClusterNetworkAttachmentsWithContext(context.Background(), listInstanceClusterNetworkAttachmentsOptions) +// GetEndpointGatewayIP : Retrieve a reserved IP bound to an endpoint gateway +// This request retrieves the specified reserved IP address if it is bound to the endpoint gateway specified in the URL. +func (vpc *VpcV1) GetEndpointGatewayIP(getEndpointGatewayIPOptions *GetEndpointGatewayIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetEndpointGatewayIPWithContext(context.Background(), getEndpointGatewayIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceClusterNetworkAttachmentsWithContext is an alternate form of the ListInstanceClusterNetworkAttachments method which supports a Context parameter -func (vpc *VpcV1) ListInstanceClusterNetworkAttachmentsWithContext(ctx context.Context, listInstanceClusterNetworkAttachmentsOptions *ListInstanceClusterNetworkAttachmentsOptions) (result *InstanceClusterNetworkAttachmentCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listInstanceClusterNetworkAttachmentsOptions, "listInstanceClusterNetworkAttachmentsOptions cannot be nil") +// GetEndpointGatewayIPWithContext is an alternate form of the GetEndpointGatewayIP method which supports a Context parameter +func (vpc *VpcV1) GetEndpointGatewayIPWithContext(ctx context.Context, getEndpointGatewayIPOptions *GetEndpointGatewayIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getEndpointGatewayIPOptions, "getEndpointGatewayIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listInstanceClusterNetworkAttachmentsOptions, "listInstanceClusterNetworkAttachmentsOptions") + err = core.ValidateStruct(getEndpointGatewayIPOptions, "getEndpointGatewayIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *listInstanceClusterNetworkAttachmentsOptions.InstanceID, + "endpoint_gateway_id": *getEndpointGatewayIPOptions.EndpointGatewayID, + "id": *getEndpointGatewayIPOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{endpoint_gateway_id}/ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceClusterNetworkAttachmentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetEndpointGatewayIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceClusterNetworkAttachments") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getEndpointGatewayIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listInstanceClusterNetworkAttachmentsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listInstanceClusterNetworkAttachmentsOptions.Start)) - } - if listInstanceClusterNetworkAttachmentsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listInstanceClusterNetworkAttachmentsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -6790,12 +7046,12 @@ func (vpc *VpcV1) ListInstanceClusterNetworkAttachmentsWithContext(ctx context.C var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_cluster_network_attachments", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_endpoint_gateway_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachmentCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6806,74 +7062,57 @@ func (vpc *VpcV1) ListInstanceClusterNetworkAttachmentsWithContext(ctx context.C return } -// CreateClusterNetworkAttachment : Create a cluster network attachment -// This request creates a cluster network attachment from an instance cluster network attachment prototype object. A -// cluster network attachment will attach the instance to a cluster network. The cluster network attachment prototype -// must specify a cluster network interface identity or a cluster network interface prototype. +// AddEndpointGatewayIP : Bind a reserved IP to an endpoint gateway +// This request binds the specified reserved IP to the specified endpoint gateway. The reserved IP: // -// The instance must be in a `stopped` or `stopping` state to create an instance cluster network attachment. -func (vpc *VpcV1) CreateClusterNetworkAttachment(createClusterNetworkAttachmentOptions *CreateClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateClusterNetworkAttachmentWithContext(context.Background(), createClusterNetworkAttachmentOptions) +// - must currently be unbound, or not required by its target +// - must not be in the same zone as any other reserved IP bound to the endpoint gateway. +func (vpc *VpcV1) AddEndpointGatewayIP(addEndpointGatewayIPOptions *AddEndpointGatewayIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.AddEndpointGatewayIPWithContext(context.Background(), addEndpointGatewayIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateClusterNetworkAttachmentWithContext is an alternate form of the CreateClusterNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) CreateClusterNetworkAttachmentWithContext(ctx context.Context, createClusterNetworkAttachmentOptions *CreateClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createClusterNetworkAttachmentOptions, "createClusterNetworkAttachmentOptions cannot be nil") +// AddEndpointGatewayIPWithContext is an alternate form of the AddEndpointGatewayIP method which supports a Context parameter +func (vpc *VpcV1) AddEndpointGatewayIPWithContext(ctx context.Context, addEndpointGatewayIPOptions *AddEndpointGatewayIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(addEndpointGatewayIPOptions, "addEndpointGatewayIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createClusterNetworkAttachmentOptions, "createClusterNetworkAttachmentOptions") + err = core.ValidateStruct(addEndpointGatewayIPOptions, "addEndpointGatewayIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *createClusterNetworkAttachmentOptions.InstanceID, + "endpoint_gateway_id": *addEndpointGatewayIPOptions.EndpointGatewayID, + "id": *addEndpointGatewayIPOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{endpoint_gateway_id}/ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createClusterNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddEndpointGatewayIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range addEndpointGatewayIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createClusterNetworkAttachmentOptions.ClusterNetworkInterface != nil { - body["cluster_network_interface"] = createClusterNetworkAttachmentOptions.ClusterNetworkInterface - } - if createClusterNetworkAttachmentOptions.Before != nil { - body["before"] = createClusterNetworkAttachmentOptions.Before - } - if createClusterNetworkAttachmentOptions.Name != nil { - body["name"] = createClusterNetworkAttachmentOptions.Name - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -6883,12 +7122,12 @@ func (vpc *VpcV1) CreateClusterNetworkAttachmentWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_cluster_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "add_endpoint_gateway_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -6899,53 +7138,51 @@ func (vpc *VpcV1) CreateClusterNetworkAttachmentWithContext(ctx context.Context, return } -// DeleteInstanceClusterNetworkAttachment : Delete an instance cluster network attachment -// This request deletes an instance cluster network attachment. The instance must be in a -// `stopped` or `stopping` state to delete an instance cluster network attachment. +// DeleteEndpointGateway : Delete an endpoint gateway +// This request deletes an endpoint gateway. This operation cannot be reversed. // -// This operation cannot be reversed. -func (vpc *VpcV1) DeleteInstanceClusterNetworkAttachment(deleteInstanceClusterNetworkAttachmentOptions *DeleteInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteInstanceClusterNetworkAttachmentWithContext(context.Background(), deleteInstanceClusterNetworkAttachmentOptions) +// Reserved IPs that were bound to the endpoint gateway will be released if their +// `auto_delete` property is set to true. +func (vpc *VpcV1) DeleteEndpointGateway(deleteEndpointGatewayOptions *DeleteEndpointGatewayOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteEndpointGatewayWithContext(context.Background(), deleteEndpointGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteInstanceClusterNetworkAttachmentWithContext is an alternate form of the DeleteInstanceClusterNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) DeleteInstanceClusterNetworkAttachmentWithContext(ctx context.Context, deleteInstanceClusterNetworkAttachmentOptions *DeleteInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteInstanceClusterNetworkAttachmentOptions, "deleteInstanceClusterNetworkAttachmentOptions cannot be nil") +// DeleteEndpointGatewayWithContext is an alternate form of the DeleteEndpointGateway method which supports a Context parameter +func (vpc *VpcV1) DeleteEndpointGatewayWithContext(ctx context.Context, deleteEndpointGatewayOptions *DeleteEndpointGatewayOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteEndpointGatewayOptions, "deleteEndpointGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteInstanceClusterNetworkAttachmentOptions, "deleteInstanceClusterNetworkAttachmentOptions") + err = core.ValidateStruct(deleteEndpointGatewayOptions, "deleteEndpointGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *deleteInstanceClusterNetworkAttachmentOptions.InstanceID, - "id": *deleteInstanceClusterNetworkAttachmentOptions.ID, + "id": *deleteEndpointGatewayOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteInstanceClusterNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteEndpointGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceClusterNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteEndpointGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -6956,66 +7193,56 @@ func (vpc *VpcV1) DeleteInstanceClusterNetworkAttachmentWithContext(ctx context. return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_instance_cluster_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_endpoint_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachment) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetInstanceClusterNetworkAttachment : Retrieve an instance cluster network attachment -// This request retrieves a single instance cluster network attachment specified by the identifier in the URL. -func (vpc *VpcV1) GetInstanceClusterNetworkAttachment(getInstanceClusterNetworkAttachmentOptions *GetInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceClusterNetworkAttachmentWithContext(context.Background(), getInstanceClusterNetworkAttachmentOptions) +// GetEndpointGateway : Retrieve an endpoint gateway +// This request retrieves a single endpoint gateway specified by the identifier in the URL. +func (vpc *VpcV1) GetEndpointGateway(getEndpointGatewayOptions *GetEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetEndpointGatewayWithContext(context.Background(), getEndpointGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceClusterNetworkAttachmentWithContext is an alternate form of the GetInstanceClusterNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) GetInstanceClusterNetworkAttachmentWithContext(ctx context.Context, getInstanceClusterNetworkAttachmentOptions *GetInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceClusterNetworkAttachmentOptions, "getInstanceClusterNetworkAttachmentOptions cannot be nil") +// GetEndpointGatewayWithContext is an alternate form of the GetEndpointGateway method which supports a Context parameter +func (vpc *VpcV1) GetEndpointGatewayWithContext(ctx context.Context, getEndpointGatewayOptions *GetEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getEndpointGatewayOptions, "getEndpointGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceClusterNetworkAttachmentOptions, "getInstanceClusterNetworkAttachmentOptions") + err = core.ValidateStruct(getEndpointGatewayOptions, "getEndpointGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *getInstanceClusterNetworkAttachmentOptions.InstanceID, - "id": *getInstanceClusterNetworkAttachmentOptions.ID, + "id": *getEndpointGatewayOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceClusterNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetEndpointGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceClusterNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getEndpointGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7032,12 +7259,12 @@ func (vpc *VpcV1) GetInstanceClusterNetworkAttachmentWithContext(ctx context.Con var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_cluster_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_endpoint_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEndpointGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7048,49 +7275,48 @@ func (vpc *VpcV1) GetInstanceClusterNetworkAttachmentWithContext(ctx context.Con return } -// UpdateInstanceClusterNetworkAttachment : Update an instance cluster network attachment -// This request updates an instance cluster network attachment with the information provided in an instance network -// interface patch object. The instance cluster network attachment patch object is structured in the same way as a -// retrieved instance cluster network attachment and needs to contain only the information to be updated. -func (vpc *VpcV1) UpdateInstanceClusterNetworkAttachment(updateInstanceClusterNetworkAttachmentOptions *UpdateInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateInstanceClusterNetworkAttachmentWithContext(context.Background(), updateInstanceClusterNetworkAttachmentOptions) +// UpdateEndpointGateway : Update an endpoint gateway +// This request updates an endpoint gateway with the information in a provided endpoint gateway patch. The endpoint +// gateway patch object is structured in the same way as a retrieved endpoint gateway and contains only the information +// to be updated. +func (vpc *VpcV1) UpdateEndpointGateway(updateEndpointGatewayOptions *UpdateEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateEndpointGatewayWithContext(context.Background(), updateEndpointGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateInstanceClusterNetworkAttachmentWithContext is an alternate form of the UpdateInstanceClusterNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) UpdateInstanceClusterNetworkAttachmentWithContext(ctx context.Context, updateInstanceClusterNetworkAttachmentOptions *UpdateInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateInstanceClusterNetworkAttachmentOptions, "updateInstanceClusterNetworkAttachmentOptions cannot be nil") +// UpdateEndpointGatewayWithContext is an alternate form of the UpdateEndpointGateway method which supports a Context parameter +func (vpc *VpcV1) UpdateEndpointGatewayWithContext(ctx context.Context, updateEndpointGatewayOptions *UpdateEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateEndpointGatewayOptions, "updateEndpointGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateInstanceClusterNetworkAttachmentOptions, "updateInstanceClusterNetworkAttachmentOptions") + err = core.ValidateStruct(updateEndpointGatewayOptions, "updateEndpointGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *updateInstanceClusterNetworkAttachmentOptions.InstanceID, - "id": *updateInstanceClusterNetworkAttachmentOptions.ID, + "id": *updateEndpointGatewayOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateInstanceClusterNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateEndpointGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceClusterNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateEndpointGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7099,7 +7325,7 @@ func (vpc *VpcV1) UpdateInstanceClusterNetworkAttachmentWithContext(ctx context. builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateInstanceClusterNetworkAttachmentOptions.InstanceClusterNetworkAttachmentPatch) + _, err = builder.SetBodyContentJSON(updateEndpointGatewayOptions.EndpointGatewayPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -7114,12 +7340,12 @@ func (vpc *VpcV1) UpdateInstanceClusterNetworkAttachmentWithContext(ctx context. var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_instance_cluster_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_endpoint_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEndpointGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7130,49 +7356,130 @@ func (vpc *VpcV1) UpdateInstanceClusterNetworkAttachmentWithContext(ctx context. return } -// CreateInstanceConsoleAccessToken : Create a console access token for an instance -// This request creates a new single-use console access token for an instance. All console configuration is provided at -// token create time, and the token is subsequently used in the `access_token` query parameter for the WebSocket -// request. The access token is only valid for a short period of time, and a maximum of one token is valid for a given -// instance at a time. -func (vpc *VpcV1) CreateInstanceConsoleAccessToken(createInstanceConsoleAccessTokenOptions *CreateInstanceConsoleAccessTokenOptions) (result *InstanceConsoleAccessToken, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateInstanceConsoleAccessTokenWithContext(context.Background(), createInstanceConsoleAccessTokenOptions) +// ListFloatingIps : List floating IPs +// This request lists floating IPs in the region. Floating IPs allow inbound and outbound traffic from the Internet to +// an instance. +func (vpc *VpcV1) ListFloatingIps(listFloatingIpsOptions *ListFloatingIpsOptions) (result *FloatingIPCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListFloatingIpsWithContext(context.Background(), listFloatingIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateInstanceConsoleAccessTokenWithContext is an alternate form of the CreateInstanceConsoleAccessToken method which supports a Context parameter -func (vpc *VpcV1) CreateInstanceConsoleAccessTokenWithContext(ctx context.Context, createInstanceConsoleAccessTokenOptions *CreateInstanceConsoleAccessTokenOptions) (result *InstanceConsoleAccessToken, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createInstanceConsoleAccessTokenOptions, "createInstanceConsoleAccessTokenOptions cannot be nil") +// ListFloatingIpsWithContext is an alternate form of the ListFloatingIps method which supports a Context parameter +func (vpc *VpcV1) ListFloatingIpsWithContext(ctx context.Context, listFloatingIpsOptions *ListFloatingIpsOptions) (result *FloatingIPCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listFloatingIpsOptions, "listFloatingIpsOptions") if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - err = core.ValidateStruct(createInstanceConsoleAccessTokenOptions, "createInstanceConsoleAccessTokenOptions") + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips`, nil) if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "instance_id": *createInstanceConsoleAccessTokenOptions.InstanceID, + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListFloatingIps") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range listFloatingIpsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listFloatingIpsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listFloatingIpsOptions.Start)) + } + if listFloatingIpsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listFloatingIpsOptions.Limit)) + } + if listFloatingIpsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listFloatingIpsOptions.ResourceGroupID)) + } + if listFloatingIpsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listFloatingIpsOptions.Sort)) + } + if listFloatingIpsOptions.TargetID != nil { + builder.AddQuery("target.id", fmt.Sprint(*listFloatingIpsOptions.TargetID)) + } + if listFloatingIpsOptions.TargetCRN != nil { + builder.AddQuery("target.crn", fmt.Sprint(*listFloatingIpsOptions.TargetCRN)) + } + if listFloatingIpsOptions.TargetName != nil { + builder.AddQuery("target.name", fmt.Sprint(*listFloatingIpsOptions.TargetName)) + } + if listFloatingIpsOptions.TargetResourceType != nil { + builder.AddQuery("target.resource_type", fmt.Sprint(*listFloatingIpsOptions.TargetResourceType)) + } + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "list_floating_ips", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// CreateFloatingIP : Reserve a floating IP +// This request reserves a new floating IP. +func (vpc *VpcV1) CreateFloatingIP(createFloatingIPOptions *CreateFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateFloatingIPWithContext(context.Background(), createFloatingIPOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// CreateFloatingIPWithContext is an alternate form of the CreateFloatingIP method which supports a Context parameter +func (vpc *VpcV1) CreateFloatingIPWithContext(ctx context.Context, createFloatingIPOptions *CreateFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createFloatingIPOptions, "createFloatingIPOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(createFloatingIPOptions, "createFloatingIPOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/console_access_token`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createInstanceConsoleAccessTokenOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceConsoleAccessToken") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7181,14 +7488,7 @@ func (vpc *VpcV1) CreateInstanceConsoleAccessTokenWithContext(ctx context.Contex builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createInstanceConsoleAccessTokenOptions.ConsoleType != nil { - body["console_type"] = createInstanceConsoleAccessTokenOptions.ConsoleType - } - if createInstanceConsoleAccessTokenOptions.Force != nil { - body["force"] = createInstanceConsoleAccessTokenOptions.Force - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(createFloatingIPOptions.FloatingIPPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -7203,12 +7503,12 @@ func (vpc *VpcV1) CreateInstanceConsoleAccessTokenWithContext(ctx context.Contex var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_instance_console_access_token", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceConsoleAccessToken) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7219,51 +7519,49 @@ func (vpc *VpcV1) CreateInstanceConsoleAccessTokenWithContext(ctx context.Contex return } -// ListInstanceDisks : List disks on an instance -// This request lists disks on an instance. A disk is a block device that is locally attached to the instance's -// physical host and is also referred to as instance storage. By default, the listed disks are sorted by their -// `created_at` property values, with the newest disk first. -func (vpc *VpcV1) ListInstanceDisks(listInstanceDisksOptions *ListInstanceDisksOptions) (result *InstanceDiskCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceDisksWithContext(context.Background(), listInstanceDisksOptions) +// DeleteFloatingIP : Delete a floating IP +// This request disassociates (if associated) and releases a floating IP. This operation cannot be reversed. For this +// request to succeed, the floating IP must not be required by another resource, such as a public gateway. +func (vpc *VpcV1) DeleteFloatingIP(deleteFloatingIPOptions *DeleteFloatingIPOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteFloatingIPWithContext(context.Background(), deleteFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceDisksWithContext is an alternate form of the ListInstanceDisks method which supports a Context parameter -func (vpc *VpcV1) ListInstanceDisksWithContext(ctx context.Context, listInstanceDisksOptions *ListInstanceDisksOptions) (result *InstanceDiskCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listInstanceDisksOptions, "listInstanceDisksOptions cannot be nil") +// DeleteFloatingIPWithContext is an alternate form of the DeleteFloatingIP method which supports a Context parameter +func (vpc *VpcV1) DeleteFloatingIPWithContext(ctx context.Context, deleteFloatingIPOptions *DeleteFloatingIPOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteFloatingIPOptions, "deleteFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listInstanceDisksOptions, "listInstanceDisksOptions") + err = core.ValidateStruct(deleteFloatingIPOptions, "deleteFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *listInstanceDisksOptions.InstanceID, + "id": *deleteFloatingIPOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/disks`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceDisksOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceDisks") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -7274,66 +7572,56 @@ func (vpc *VpcV1) ListInstanceDisksWithContext(ctx context.Context, listInstance return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_disks", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceDiskCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetInstanceDisk : Retrieve an instance disk -// This request retrieves a single instance disk specified by the identifier in the URL. -func (vpc *VpcV1) GetInstanceDisk(getInstanceDiskOptions *GetInstanceDiskOptions) (result *InstanceDisk, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceDiskWithContext(context.Background(), getInstanceDiskOptions) +// GetFloatingIP : Retrieve a floating IP +// This request retrieves a single floating IP specified by the identifier in the URL. +func (vpc *VpcV1) GetFloatingIP(getFloatingIPOptions *GetFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetFloatingIPWithContext(context.Background(), getFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceDiskWithContext is an alternate form of the GetInstanceDisk method which supports a Context parameter -func (vpc *VpcV1) GetInstanceDiskWithContext(ctx context.Context, getInstanceDiskOptions *GetInstanceDiskOptions) (result *InstanceDisk, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceDiskOptions, "getInstanceDiskOptions cannot be nil") +// GetFloatingIPWithContext is an alternate form of the GetFloatingIP method which supports a Context parameter +func (vpc *VpcV1) GetFloatingIPWithContext(ctx context.Context, getFloatingIPOptions *GetFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getFloatingIPOptions, "getFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceDiskOptions, "getInstanceDiskOptions") + err = core.ValidateStruct(getFloatingIPOptions, "getFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *getInstanceDiskOptions.InstanceID, - "id": *getInstanceDiskOptions.ID, + "id": *getFloatingIPOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/disks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceDiskOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceDisk") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7350,12 +7638,12 @@ func (vpc *VpcV1) GetInstanceDiskWithContext(ctx context.Context, getInstanceDis var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_disk", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceDisk) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7366,47 +7654,46 @@ func (vpc *VpcV1) GetInstanceDiskWithContext(ctx context.Context, getInstanceDis return } -// UpdateInstanceDisk : Update an instance disk -// This request updates the instance disk with the information in a provided patch. -func (vpc *VpcV1) UpdateInstanceDisk(updateInstanceDiskOptions *UpdateInstanceDiskOptions) (result *InstanceDisk, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateInstanceDiskWithContext(context.Background(), updateInstanceDiskOptions) +// UpdateFloatingIP : Update a floating IP +// This request updates a floating IP's name and/or target. +func (vpc *VpcV1) UpdateFloatingIP(updateFloatingIPOptions *UpdateFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateFloatingIPWithContext(context.Background(), updateFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateInstanceDiskWithContext is an alternate form of the UpdateInstanceDisk method which supports a Context parameter -func (vpc *VpcV1) UpdateInstanceDiskWithContext(ctx context.Context, updateInstanceDiskOptions *UpdateInstanceDiskOptions) (result *InstanceDisk, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateInstanceDiskOptions, "updateInstanceDiskOptions cannot be nil") +// UpdateFloatingIPWithContext is an alternate form of the UpdateFloatingIP method which supports a Context parameter +func (vpc *VpcV1) UpdateFloatingIPWithContext(ctx context.Context, updateFloatingIPOptions *UpdateFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateFloatingIPOptions, "updateFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateInstanceDiskOptions, "updateInstanceDiskOptions") + err = core.ValidateStruct(updateFloatingIPOptions, "updateFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *updateInstanceDiskOptions.InstanceID, - "id": *updateInstanceDiskOptions.ID, + "id": *updateFloatingIPOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/disks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateInstanceDiskOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceDisk") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7415,7 +7702,7 @@ func (vpc *VpcV1) UpdateInstanceDiskWithContext(ctx context.Context, updateInsta builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateInstanceDiskOptions.InstanceDiskPatch) + _, err = builder.SetBodyContentJSON(updateFloatingIPOptions.FloatingIPPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -7430,12 +7717,12 @@ func (vpc *VpcV1) UpdateInstanceDiskWithContext(ctx context.Context, updateInsta var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_instance_disk", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceDisk) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7446,57 +7733,73 @@ func (vpc *VpcV1) UpdateInstanceDiskWithContext(ctx context.Context, updateInsta return } -// ListInstanceNetworkAttachments : List network attachments on an instance -// This request lists network attachments on an instance. A network attachment represents a device on the instance to -// which a virtual network interface is attached. -// -// The network attachments will be sorted by their `created_at` property values, with newest network attachments first. -// Network attachments with identical `created_at` property values will in turn be sorted by ascending `name` property -// values. -func (vpc *VpcV1) ListInstanceNetworkAttachments(listInstanceNetworkAttachmentsOptions *ListInstanceNetworkAttachmentsOptions) (result *InstanceNetworkAttachmentCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceNetworkAttachmentsWithContext(context.Background(), listInstanceNetworkAttachmentsOptions) +// ListFlowLogCollectors : List flow log collectors +// This request lists flow log collectors in the region. A [flow log +// collector](https://cloud.ibm.com/docs/vpc?topic=vpc-flow-logs) summarizes TCP and UDP data sent over the instance +// network interfaces and instance network attachments contained within its target. The collected flow logs are written +// to a cloud object storage bucket, where they can be [viewed](https://cloud.ibm.com/docs/vpc?topic=vpc-fl-analyze). +func (vpc *VpcV1) ListFlowLogCollectors(listFlowLogCollectorsOptions *ListFlowLogCollectorsOptions) (result *FlowLogCollectorCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListFlowLogCollectorsWithContext(context.Background(), listFlowLogCollectorsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceNetworkAttachmentsWithContext is an alternate form of the ListInstanceNetworkAttachments method which supports a Context parameter -func (vpc *VpcV1) ListInstanceNetworkAttachmentsWithContext(ctx context.Context, listInstanceNetworkAttachmentsOptions *ListInstanceNetworkAttachmentsOptions) (result *InstanceNetworkAttachmentCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listInstanceNetworkAttachmentsOptions, "listInstanceNetworkAttachmentsOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(listInstanceNetworkAttachmentsOptions, "listInstanceNetworkAttachmentsOptions") +// ListFlowLogCollectorsWithContext is an alternate form of the ListFlowLogCollectors method which supports a Context parameter +func (vpc *VpcV1) ListFlowLogCollectorsWithContext(ctx context.Context, listFlowLogCollectorsOptions *ListFlowLogCollectorsOptions) (result *FlowLogCollectorCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listFlowLogCollectorsOptions, "listFlowLogCollectorsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "instance_id": *listInstanceNetworkAttachmentsOptions.InstanceID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceNetworkAttachmentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListFlowLogCollectors") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceNetworkAttachments") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listFlowLogCollectorsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listFlowLogCollectorsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listFlowLogCollectorsOptions.Start)) + } + if listFlowLogCollectorsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listFlowLogCollectorsOptions.Limit)) + } + if listFlowLogCollectorsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listFlowLogCollectorsOptions.ResourceGroupID)) + } + if listFlowLogCollectorsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listFlowLogCollectorsOptions.Name)) + } + if listFlowLogCollectorsOptions.VPCID != nil { + builder.AddQuery("vpc.id", fmt.Sprint(*listFlowLogCollectorsOptions.VPCID)) + } + if listFlowLogCollectorsOptions.VPCCRN != nil { + builder.AddQuery("vpc.crn", fmt.Sprint(*listFlowLogCollectorsOptions.VPCCRN)) + } + if listFlowLogCollectorsOptions.VPCName != nil { + builder.AddQuery("vpc.name", fmt.Sprint(*listFlowLogCollectorsOptions.VPCName)) + } + if listFlowLogCollectorsOptions.TargetID != nil { + builder.AddQuery("target.id", fmt.Sprint(*listFlowLogCollectorsOptions.TargetID)) + } + if listFlowLogCollectorsOptions.TargetResourceType != nil { + builder.AddQuery("target.resource_type", fmt.Sprint(*listFlowLogCollectorsOptions.TargetResourceType)) + } request, err := builder.Build() if err != nil { @@ -7507,12 +7810,12 @@ func (vpc *VpcV1) ListInstanceNetworkAttachmentsWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_network_attachments", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_flow_log_collectors", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceNetworkAttachmentCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFlowLogCollectorCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7523,48 +7826,44 @@ func (vpc *VpcV1) ListInstanceNetworkAttachmentsWithContext(ctx context.Context, return } -// CreateInstanceNetworkAttachment : Create a network attachment on an instance -// This request creates a new instance network attachment from an instance network attachment prototype object. The -// prototype object is structured in the same way as a retrieved instance network attachment, and contains the -// information necessary to create the new instance network attachment. -func (vpc *VpcV1) CreateInstanceNetworkAttachment(createInstanceNetworkAttachmentOptions *CreateInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateInstanceNetworkAttachmentWithContext(context.Background(), createInstanceNetworkAttachmentOptions) +// CreateFlowLogCollector : Create a flow log collector +// This request creates and starts a new flow log collector from a flow log collector prototype object. The prototype +// object is structured in the same way as a retrieved flow log collector, and contains the information necessary to +// create and start the new flow log collector. +func (vpc *VpcV1) CreateFlowLogCollector(createFlowLogCollectorOptions *CreateFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateFlowLogCollectorWithContext(context.Background(), createFlowLogCollectorOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateInstanceNetworkAttachmentWithContext is an alternate form of the CreateInstanceNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) CreateInstanceNetworkAttachmentWithContext(ctx context.Context, createInstanceNetworkAttachmentOptions *CreateInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createInstanceNetworkAttachmentOptions, "createInstanceNetworkAttachmentOptions cannot be nil") +// CreateFlowLogCollectorWithContext is an alternate form of the CreateFlowLogCollector method which supports a Context parameter +func (vpc *VpcV1) CreateFlowLogCollectorWithContext(ctx context.Context, createFlowLogCollectorOptions *CreateFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createFlowLogCollectorOptions, "createFlowLogCollectorOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createInstanceNetworkAttachmentOptions, "createInstanceNetworkAttachmentOptions") + err = core.ValidateStruct(createFlowLogCollectorOptions, "createFlowLogCollectorOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "instance_id": *createInstanceNetworkAttachmentOptions.InstanceID, - } - builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createInstanceNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateFlowLogCollector") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createFlowLogCollectorOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7574,11 +7873,20 @@ func (vpc *VpcV1) CreateInstanceNetworkAttachmentWithContext(ctx context.Context builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createInstanceNetworkAttachmentOptions.VirtualNetworkInterface != nil { - body["virtual_network_interface"] = createInstanceNetworkAttachmentOptions.VirtualNetworkInterface + if createFlowLogCollectorOptions.StorageBucket != nil { + body["storage_bucket"] = createFlowLogCollectorOptions.StorageBucket } - if createInstanceNetworkAttachmentOptions.Name != nil { - body["name"] = createInstanceNetworkAttachmentOptions.Name + if createFlowLogCollectorOptions.Target != nil { + body["target"] = createFlowLogCollectorOptions.Target + } + if createFlowLogCollectorOptions.Active != nil { + body["active"] = createFlowLogCollectorOptions.Active + } + if createFlowLogCollectorOptions.Name != nil { + body["name"] = createFlowLogCollectorOptions.Name + } + if createFlowLogCollectorOptions.ResourceGroup != nil { + body["resource_group"] = createFlowLogCollectorOptions.ResourceGroup } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -7595,12 +7903,12 @@ func (vpc *VpcV1) CreateInstanceNetworkAttachmentWithContext(ctx context.Context var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_instance_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_flow_log_collector", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFlowLogCollector) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7611,50 +7919,48 @@ func (vpc *VpcV1) CreateInstanceNetworkAttachmentWithContext(ctx context.Context return } -// DeleteInstanceNetworkAttachment : Delete an instance network attachment -// This request deletes an instance network attachment. This operation cannot be reversed. Any floating IPs associated -// with the instance network attachment are implicitly disassociated. All flow log collectors with `auto_delete` set to -// `true` targeting the instance network attachment are automatically deleted. The primary instance network attachment -// is not allowed to be deleted. -func (vpc *VpcV1) DeleteInstanceNetworkAttachment(deleteInstanceNetworkAttachmentOptions *DeleteInstanceNetworkAttachmentOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteInstanceNetworkAttachmentWithContext(context.Background(), deleteInstanceNetworkAttachmentOptions) +// DeleteFlowLogCollector : Delete a flow log collector +// This request stops and deletes a flow log collector. This operation cannot be reversed. +// +// Collected flow logs remain available within the flow log collector's Cloud Object Storage bucket. +func (vpc *VpcV1) DeleteFlowLogCollector(deleteFlowLogCollectorOptions *DeleteFlowLogCollectorOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteFlowLogCollectorWithContext(context.Background(), deleteFlowLogCollectorOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteInstanceNetworkAttachmentWithContext is an alternate form of the DeleteInstanceNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) DeleteInstanceNetworkAttachmentWithContext(ctx context.Context, deleteInstanceNetworkAttachmentOptions *DeleteInstanceNetworkAttachmentOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteInstanceNetworkAttachmentOptions, "deleteInstanceNetworkAttachmentOptions cannot be nil") +// DeleteFlowLogCollectorWithContext is an alternate form of the DeleteFlowLogCollector method which supports a Context parameter +func (vpc *VpcV1) DeleteFlowLogCollectorWithContext(ctx context.Context, deleteFlowLogCollectorOptions *DeleteFlowLogCollectorOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteFlowLogCollectorOptions, "deleteFlowLogCollectorOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteInstanceNetworkAttachmentOptions, "deleteInstanceNetworkAttachmentOptions") + err = core.ValidateStruct(deleteFlowLogCollectorOptions, "deleteFlowLogCollectorOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *deleteInstanceNetworkAttachmentOptions.InstanceID, - "id": *deleteInstanceNetworkAttachmentOptions.ID, + "id": *deleteFlowLogCollectorOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteInstanceNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteFlowLogCollector") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteFlowLogCollectorOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -7669,7 +7975,7 @@ func (vpc *VpcV1) DeleteInstanceNetworkAttachmentWithContext(ctx context.Context response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_instance_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_flow_log_collector", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -7677,47 +7983,46 @@ func (vpc *VpcV1) DeleteInstanceNetworkAttachmentWithContext(ctx context.Context return } -// GetInstanceNetworkAttachment : Retrieve an instance network attachment -// This request retrieves a single instance network attachment specified by the identifier in the URL. -func (vpc *VpcV1) GetInstanceNetworkAttachment(getInstanceNetworkAttachmentOptions *GetInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceNetworkAttachmentWithContext(context.Background(), getInstanceNetworkAttachmentOptions) +// GetFlowLogCollector : Retrieve a flow log collector +// This request retrieves a single flow log collector specified by the identifier in the URL. +func (vpc *VpcV1) GetFlowLogCollector(getFlowLogCollectorOptions *GetFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetFlowLogCollectorWithContext(context.Background(), getFlowLogCollectorOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceNetworkAttachmentWithContext is an alternate form of the GetInstanceNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) GetInstanceNetworkAttachmentWithContext(ctx context.Context, getInstanceNetworkAttachmentOptions *GetInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceNetworkAttachmentOptions, "getInstanceNetworkAttachmentOptions cannot be nil") +// GetFlowLogCollectorWithContext is an alternate form of the GetFlowLogCollector method which supports a Context parameter +func (vpc *VpcV1) GetFlowLogCollectorWithContext(ctx context.Context, getFlowLogCollectorOptions *GetFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getFlowLogCollectorOptions, "getFlowLogCollectorOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceNetworkAttachmentOptions, "getInstanceNetworkAttachmentOptions") + err = core.ValidateStruct(getFlowLogCollectorOptions, "getFlowLogCollectorOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *getInstanceNetworkAttachmentOptions.InstanceID, - "id": *getInstanceNetworkAttachmentOptions.ID, + "id": *getFlowLogCollectorOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetFlowLogCollector") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getFlowLogCollectorOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7734,12 +8039,12 @@ func (vpc *VpcV1) GetInstanceNetworkAttachmentWithContext(ctx context.Context, g var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_flow_log_collector", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFlowLogCollector) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7750,49 +8055,48 @@ func (vpc *VpcV1) GetInstanceNetworkAttachmentWithContext(ctx context.Context, g return } -// UpdateInstanceNetworkAttachment : Update an instance network attachment -// This request updates an instance network attachment with the information provided in an instance network interface -// patch object. The instance network attachment patch object is structured in the same way as a retrieved instance -// network attachment and needs to contain only the information to be updated. -func (vpc *VpcV1) UpdateInstanceNetworkAttachment(updateInstanceNetworkAttachmentOptions *UpdateInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateInstanceNetworkAttachmentWithContext(context.Background(), updateInstanceNetworkAttachmentOptions) +// UpdateFlowLogCollector : Update a flow log collector +// This request updates a flow log collector with the information in a provided flow log collector patch. The flow log +// collector patch object is structured in the same way as a retrieved flow log collector and contains only the +// information to be updated. +func (vpc *VpcV1) UpdateFlowLogCollector(updateFlowLogCollectorOptions *UpdateFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateFlowLogCollectorWithContext(context.Background(), updateFlowLogCollectorOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateInstanceNetworkAttachmentWithContext is an alternate form of the UpdateInstanceNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) UpdateInstanceNetworkAttachmentWithContext(ctx context.Context, updateInstanceNetworkAttachmentOptions *UpdateInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateInstanceNetworkAttachmentOptions, "updateInstanceNetworkAttachmentOptions cannot be nil") +// UpdateFlowLogCollectorWithContext is an alternate form of the UpdateFlowLogCollector method which supports a Context parameter +func (vpc *VpcV1) UpdateFlowLogCollectorWithContext(ctx context.Context, updateFlowLogCollectorOptions *UpdateFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateFlowLogCollectorOptions, "updateFlowLogCollectorOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateInstanceNetworkAttachmentOptions, "updateInstanceNetworkAttachmentOptions") + err = core.ValidateStruct(updateFlowLogCollectorOptions, "updateFlowLogCollectorOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *updateInstanceNetworkAttachmentOptions.InstanceID, - "id": *updateInstanceNetworkAttachmentOptions.ID, + "id": *updateFlowLogCollectorOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateInstanceNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateFlowLogCollector") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateFlowLogCollectorOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7801,7 +8105,7 @@ func (vpc *VpcV1) UpdateInstanceNetworkAttachmentWithContext(ctx context.Context builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateInstanceNetworkAttachmentOptions.InstanceNetworkAttachmentPatch) + _, err = builder.SetBodyContentJSON(updateFlowLogCollectorOptions.FlowLogCollectorPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -7816,12 +8120,12 @@ func (vpc *VpcV1) UpdateInstanceNetworkAttachmentWithContext(ctx context.Context var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_instance_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_flow_log_collector", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFlowLogCollector) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7832,53 +8136,41 @@ func (vpc *VpcV1) UpdateInstanceNetworkAttachmentWithContext(ctx context.Context return } -// ListInstanceNetworkInterfaces : List network interfaces on an instance -// This request lists network interfaces on an instance. An instance network interface is an abstract representation of -// a network device and attaches an instance to a single subnet. Each network interface on an instance can attach to any -// subnet in the zone, including subnets that are already attached to the instance. Multiple network interfaces on the -// instance may also attach to the same subnet. -// -// If this instance has network attachments, each returned network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface. -func (vpc *VpcV1) ListInstanceNetworkInterfaces(listInstanceNetworkInterfacesOptions *ListInstanceNetworkInterfacesOptions) (result *NetworkInterfaceUnpaginatedCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceNetworkInterfacesWithContext(context.Background(), listInstanceNetworkInterfacesOptions) +// ListRegions : List regions +// This request lists regions. Each region is a separate geographic area that contains multiple isolated zones. +// Resources can be provisioned into one or more zones in a region. Each zone is isolated, but connected to other zones +// in the same region with low-latency and high-bandwidth links. Regions represent the top-level of fault isolation +// available. Resources deployed within a single region also benefit from the low latency afforded by geographic +// proximity. +func (vpc *VpcV1) ListRegions(listRegionsOptions *ListRegionsOptions) (result *RegionCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListRegionsWithContext(context.Background(), listRegionsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceNetworkInterfacesWithContext is an alternate form of the ListInstanceNetworkInterfaces method which supports a Context parameter -func (vpc *VpcV1) ListInstanceNetworkInterfacesWithContext(ctx context.Context, listInstanceNetworkInterfacesOptions *ListInstanceNetworkInterfacesOptions) (result *NetworkInterfaceUnpaginatedCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listInstanceNetworkInterfacesOptions, "listInstanceNetworkInterfacesOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(listInstanceNetworkInterfacesOptions, "listInstanceNetworkInterfacesOptions") +// ListRegionsWithContext is an alternate form of the ListRegions method which supports a Context parameter +func (vpc *VpcV1) ListRegionsWithContext(ctx context.Context, listRegionsOptions *ListRegionsOptions) (result *RegionCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listRegionsOptions, "listRegionsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "instance_id": *listInstanceNetworkInterfacesOptions.InstanceID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/regions`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceNetworkInterfacesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListRegions") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceNetworkInterfaces") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listRegionsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -7895,12 +8187,12 @@ func (vpc *VpcV1) ListInstanceNetworkInterfacesWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_network_interfaces", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_regions", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkInterfaceUnpaginatedCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRegionCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -7911,83 +8203,53 @@ func (vpc *VpcV1) ListInstanceNetworkInterfacesWithContext(ctx context.Context, return } -// CreateInstanceNetworkInterface : Create a network interface on an instance -// This request creates a new instance network interface from an instance network interface prototype object. The -// prototype object is structured in the same way as a retrieved instance network interface, and contains the -// information necessary to create the new instance network interface. Any subnet in the instance's VPC may be -// specified. Addresses on the instance network interface must be within the specified subnet's CIDR blocks. -// -// If this instance has network attachments, each network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface, and new network interfaces are not allowed to be created. -func (vpc *VpcV1) CreateInstanceNetworkInterface(createInstanceNetworkInterfaceOptions *CreateInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateInstanceNetworkInterfaceWithContext(context.Background(), createInstanceNetworkInterfaceOptions) +// GetRegion : Retrieve a region +// This request retrieves a single region specified by the name in the URL. +func (vpc *VpcV1) GetRegion(getRegionOptions *GetRegionOptions) (result *Region, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetRegionWithContext(context.Background(), getRegionOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateInstanceNetworkInterfaceWithContext is an alternate form of the CreateInstanceNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) CreateInstanceNetworkInterfaceWithContext(ctx context.Context, createInstanceNetworkInterfaceOptions *CreateInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createInstanceNetworkInterfaceOptions, "createInstanceNetworkInterfaceOptions cannot be nil") +// GetRegionWithContext is an alternate form of the GetRegion method which supports a Context parameter +func (vpc *VpcV1) GetRegionWithContext(ctx context.Context, getRegionOptions *GetRegionOptions) (result *Region, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getRegionOptions, "getRegionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createInstanceNetworkInterfaceOptions, "createInstanceNetworkInterfaceOptions") + err = core.ValidateStruct(getRegionOptions, "getRegionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *createInstanceNetworkInterfaceOptions.InstanceID, + "name": *getRegionOptions.Name, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/regions/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createInstanceNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetRegion") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getRegionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createInstanceNetworkInterfaceOptions.Subnet != nil { - body["subnet"] = createInstanceNetworkInterfaceOptions.Subnet - } - if createInstanceNetworkInterfaceOptions.AllowIPSpoofing != nil { - body["allow_ip_spoofing"] = createInstanceNetworkInterfaceOptions.AllowIPSpoofing - } - if createInstanceNetworkInterfaceOptions.Name != nil { - body["name"] = createInstanceNetworkInterfaceOptions.Name - } - if createInstanceNetworkInterfaceOptions.PrimaryIP != nil { - body["primary_ip"] = createInstanceNetworkInterfaceOptions.PrimaryIP - } - if createInstanceNetworkInterfaceOptions.SecurityGroups != nil { - body["security_groups"] = createInstanceNetworkInterfaceOptions.SecurityGroups - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -7997,12 +8259,12 @@ func (vpc *VpcV1) CreateInstanceNetworkInterfaceWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_instance_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_region", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRegion) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8013,56 +8275,50 @@ func (vpc *VpcV1) CreateInstanceNetworkInterfaceWithContext(ctx context.Context, return } -// DeleteInstanceNetworkInterface : Delete an instance network interface -// This request deletes an instance network interface. This operation cannot be reversed. Any floating IPs associated -// with the instance network interface are implicitly disassociated. All flow log collectors with `auto_delete` set to -// `true` targeting the instance network interface are automatically deleted. The primary instance network interface is -// not allowed to be deleted. -// -// If this instance has network attachments, this network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface, and is not allowed to be deleted. -func (vpc *VpcV1) DeleteInstanceNetworkInterface(deleteInstanceNetworkInterfaceOptions *DeleteInstanceNetworkInterfaceOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteInstanceNetworkInterfaceWithContext(context.Background(), deleteInstanceNetworkInterfaceOptions) +// ListRegionZones : List zones in a region +// This request lists zones in a region. Zones represent logically-isolated data centers with high-bandwidth and +// low-latency interconnects to other zones in the same region. Faults in a zone do not affect other zones. +func (vpc *VpcV1) ListRegionZones(listRegionZonesOptions *ListRegionZonesOptions) (result *ZoneCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListRegionZonesWithContext(context.Background(), listRegionZonesOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteInstanceNetworkInterfaceWithContext is an alternate form of the DeleteInstanceNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) DeleteInstanceNetworkInterfaceWithContext(ctx context.Context, deleteInstanceNetworkInterfaceOptions *DeleteInstanceNetworkInterfaceOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteInstanceNetworkInterfaceOptions, "deleteInstanceNetworkInterfaceOptions cannot be nil") +// ListRegionZonesWithContext is an alternate form of the ListRegionZones method which supports a Context parameter +func (vpc *VpcV1) ListRegionZonesWithContext(ctx context.Context, listRegionZonesOptions *ListRegionZonesOptions) (result *ZoneCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listRegionZonesOptions, "listRegionZonesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteInstanceNetworkInterfaceOptions, "deleteInstanceNetworkInterfaceOptions") + err = core.ValidateStruct(listRegionZonesOptions, "listRegionZonesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *deleteInstanceNetworkInterfaceOptions.InstanceID, - "id": *deleteInstanceNetworkInterfaceOptions.ID, + "region_name": *listRegionZonesOptions.RegionName, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/regions/{region_name}/zones`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteInstanceNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListRegionZones") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listRegionZonesOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -8073,61 +8329,66 @@ func (vpc *VpcV1) DeleteInstanceNetworkInterfaceWithContext(ctx context.Context, return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_instance_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_region_zones", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalZoneCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetInstanceNetworkInterface : Retrieve an instance network interface -// This request retrieves a single instance network interface specified by the identifier in the URL. -// -// If this instance has network attachments, the retrieved network interface is a -// [read-only representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its -// corresponding network attachment and its attached virtual network interface. -func (vpc *VpcV1) GetInstanceNetworkInterface(getInstanceNetworkInterfaceOptions *GetInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceNetworkInterfaceWithContext(context.Background(), getInstanceNetworkInterfaceOptions) +// GetRegionZone : Retrieve a zone +// This request retrieves a single zone specified by the region and zone names in the URL. +func (vpc *VpcV1) GetRegionZone(getRegionZoneOptions *GetRegionZoneOptions) (result *Zone, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetRegionZoneWithContext(context.Background(), getRegionZoneOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceNetworkInterfaceWithContext is an alternate form of the GetInstanceNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) GetInstanceNetworkInterfaceWithContext(ctx context.Context, getInstanceNetworkInterfaceOptions *GetInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceNetworkInterfaceOptions, "getInstanceNetworkInterfaceOptions cannot be nil") +// GetRegionZoneWithContext is an alternate form of the GetRegionZone method which supports a Context parameter +func (vpc *VpcV1) GetRegionZoneWithContext(ctx context.Context, getRegionZoneOptions *GetRegionZoneOptions) (result *Zone, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getRegionZoneOptions, "getRegionZoneOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceNetworkInterfaceOptions, "getInstanceNetworkInterfaceOptions") + err = core.ValidateStruct(getRegionZoneOptions, "getRegionZoneOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *getInstanceNetworkInterfaceOptions.InstanceID, - "id": *getInstanceNetworkInterfaceOptions.ID, + "region_name": *getRegionZoneOptions.RegionName, + "name": *getRegionZoneOptions.Name, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/regions/{region_name}/zones/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetRegionZone") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getRegionZoneOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -8144,12 +8405,12 @@ func (vpc *VpcV1) GetInstanceNetworkInterfaceWithContext(ctx context.Context, ge var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_region_zone", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalZone) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8160,65 +8421,67 @@ func (vpc *VpcV1) GetInstanceNetworkInterfaceWithContext(ctx context.Context, ge return } -// UpdateInstanceNetworkInterface : Update an instance network interface -// This request updates an instance network interface with the information provided in an instance network interface -// patch object. The instance network interface patch object is structured in the same way as a retrieved instance -// network interface and needs to contain only the information to be updated. -// -// If this instance has network attachments, this network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface, and is not allowed to be updated. -func (vpc *VpcV1) UpdateInstanceNetworkInterface(updateInstanceNetworkInterfaceOptions *UpdateInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateInstanceNetworkInterfaceWithContext(context.Background(), updateInstanceNetworkInterfaceOptions) +// ListImages : List images +// This request lists images available in the region. An image provides source data for a volume. Images are either +// system-provided, or created from another source, such as importing from Cloud Object Storage. +func (vpc *VpcV1) ListImages(listImagesOptions *ListImagesOptions) (result *ImageCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListImagesWithContext(context.Background(), listImagesOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateInstanceNetworkInterfaceWithContext is an alternate form of the UpdateInstanceNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) UpdateInstanceNetworkInterfaceWithContext(ctx context.Context, updateInstanceNetworkInterfaceOptions *UpdateInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateInstanceNetworkInterfaceOptions, "updateInstanceNetworkInterfaceOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(updateInstanceNetworkInterfaceOptions, "updateInstanceNetworkInterfaceOptions") +// ListImagesWithContext is an alternate form of the ListImages method which supports a Context parameter +func (vpc *VpcV1) ListImagesWithContext(ctx context.Context, listImagesOptions *ListImagesOptions) (result *ImageCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listImagesOptions, "listImagesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "instance_id": *updateInstanceNetworkInterfaceOptions.InstanceID, - "id": *updateInstanceNetworkInterfaceOptions.ID, - } - - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateInstanceNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListImages") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listImagesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - _, err = builder.SetBodyContentJSON(updateInstanceNetworkInterfaceOptions.NetworkInterfacePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listImagesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listImagesOptions.Start)) + } + if listImagesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listImagesOptions.Limit)) + } + if listImagesOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listImagesOptions.ResourceGroupID)) + } + if listImagesOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listImagesOptions.Name)) + } + if listImagesOptions.Status != nil { + builder.AddQuery("status", strings.Join(listImagesOptions.Status, ",")) + } + if listImagesOptions.Visibility != nil { + builder.AddQuery("visibility", fmt.Sprint(*listImagesOptions.Visibility)) + } + if listImagesOptions.UserDataFormat != nil { + builder.AddQuery("user_data_format", strings.Join(listImagesOptions.UserDataFormat, ",")) + } + if listImagesOptions.RemoteAccountID != nil { + builder.AddQuery("remote.account.id", fmt.Sprint(*listImagesOptions.RemoteAccountID)) } request, err := builder.Build() @@ -8230,12 +8493,12 @@ func (vpc *VpcV1) UpdateInstanceNetworkInterfaceWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_instance_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_images", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8246,54 +8509,59 @@ func (vpc *VpcV1) UpdateInstanceNetworkInterfaceWithContext(ctx context.Context, return } -// ListInstanceNetworkInterfaceFloatingIps : List floating IPs associated with an instance network interface -// This request lists floating IPs associated with an instance network interface. -func (vpc *VpcV1) ListInstanceNetworkInterfaceFloatingIps(listInstanceNetworkInterfaceFloatingIpsOptions *ListInstanceNetworkInterfaceFloatingIpsOptions) (result *FloatingIPUnpaginatedCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceNetworkInterfaceFloatingIpsWithContext(context.Background(), listInstanceNetworkInterfaceFloatingIpsOptions) +// CreateImage : Create an image +// This request creates a new image from an image prototype object. The prototype object is structured in the same way +// as a retrieved image, and contains the information necessary to create the new image. If an image is being imported, +// a URL to the image file on object storage must be specified. If an image is being created from an existing volume, +// that volume must be specified. +func (vpc *VpcV1) CreateImage(createImageOptions *CreateImageOptions) (result *Image, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateImageWithContext(context.Background(), createImageOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceNetworkInterfaceFloatingIpsWithContext is an alternate form of the ListInstanceNetworkInterfaceFloatingIps method which supports a Context parameter -func (vpc *VpcV1) ListInstanceNetworkInterfaceFloatingIpsWithContext(ctx context.Context, listInstanceNetworkInterfaceFloatingIpsOptions *ListInstanceNetworkInterfaceFloatingIpsOptions) (result *FloatingIPUnpaginatedCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listInstanceNetworkInterfaceFloatingIpsOptions, "listInstanceNetworkInterfaceFloatingIpsOptions cannot be nil") +// CreateImageWithContext is an alternate form of the CreateImage method which supports a Context parameter +func (vpc *VpcV1) CreateImageWithContext(ctx context.Context, createImageOptions *CreateImageOptions) (result *Image, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createImageOptions, "createImageOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listInstanceNetworkInterfaceFloatingIpsOptions, "listInstanceNetworkInterfaceFloatingIpsOptions") + err = core.ValidateStruct(createImageOptions, "createImageOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "instance_id": *listInstanceNetworkInterfaceFloatingIpsOptions.InstanceID, - "network_interface_id": *listInstanceNetworkInterfaceFloatingIpsOptions.NetworkInterfaceID, - } - - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/floating_ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceNetworkInterfaceFloatingIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateImage") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceNetworkInterfaceFloatingIps") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createImageOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(createImageOptions.ImagePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -8303,12 +8571,12 @@ func (vpc *VpcV1) ListInstanceNetworkInterfaceFloatingIpsWithContext(ctx context var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_network_interface_floating_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_image", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPUnpaginatedCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImage) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8319,48 +8587,52 @@ func (vpc *VpcV1) ListInstanceNetworkInterfaceFloatingIpsWithContext(ctx context return } -// RemoveInstanceNetworkInterfaceFloatingIP : Disassociate a floating IP from an instance network interface -// This request disassociates the specified floating IP from the specified instance network interface. -func (vpc *VpcV1) RemoveInstanceNetworkInterfaceFloatingIP(removeInstanceNetworkInterfaceFloatingIPOptions *RemoveInstanceNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RemoveInstanceNetworkInterfaceFloatingIPWithContext(context.Background(), removeInstanceNetworkInterfaceFloatingIPOptions) +// DeleteImage : Delete an image +// This request deletes an image. Any active image export jobs will be completed first. This operation cannot be +// reversed. An image with `remote.account` set is not allowed to be deleted. Additionally, an image cannot be deleted +// if it: +// - has a `status` of `deleting` +// - has a `status` of `pending` with a `status_reasons` code of +// `image_request_in_progress` +// - has `catalog_offering.managed` set to `true`. +func (vpc *VpcV1) DeleteImage(deleteImageOptions *DeleteImageOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteImageWithContext(context.Background(), deleteImageOptions) err = core.RepurposeSDKProblem(err, "") return } -// RemoveInstanceNetworkInterfaceFloatingIPWithContext is an alternate form of the RemoveInstanceNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) RemoveInstanceNetworkInterfaceFloatingIPWithContext(ctx context.Context, removeInstanceNetworkInterfaceFloatingIPOptions *RemoveInstanceNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(removeInstanceNetworkInterfaceFloatingIPOptions, "removeInstanceNetworkInterfaceFloatingIPOptions cannot be nil") +// DeleteImageWithContext is an alternate form of the DeleteImage method which supports a Context parameter +func (vpc *VpcV1) DeleteImageWithContext(ctx context.Context, deleteImageOptions *DeleteImageOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteImageOptions, "deleteImageOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(removeInstanceNetworkInterfaceFloatingIPOptions, "removeInstanceNetworkInterfaceFloatingIPOptions") + err = core.ValidateStruct(deleteImageOptions, "deleteImageOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *removeInstanceNetworkInterfaceFloatingIPOptions.InstanceID, - "network_interface_id": *removeInstanceNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, - "id": *removeInstanceNetworkInterfaceFloatingIPOptions.ID, + "id": *deleteImageOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range removeInstanceNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteImage") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveInstanceNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteImageOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -8375,7 +8647,7 @@ func (vpc *VpcV1) RemoveInstanceNetworkInterfaceFloatingIPWithContext(ctx contex response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "remove_instance_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_image", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -8383,49 +8655,46 @@ func (vpc *VpcV1) RemoveInstanceNetworkInterfaceFloatingIPWithContext(ctx contex return } -// GetInstanceNetworkInterfaceFloatingIP : Retrieve associated floating IP -// This request retrieves a specified floating IP address if it is associated with the instance network interface and -// instance specified in the URL. -func (vpc *VpcV1) GetInstanceNetworkInterfaceFloatingIP(getInstanceNetworkInterfaceFloatingIPOptions *GetInstanceNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceNetworkInterfaceFloatingIPWithContext(context.Background(), getInstanceNetworkInterfaceFloatingIPOptions) +// GetImage : Retrieve an image +// This request retrieves a single image specified by the identifier in the URL. +func (vpc *VpcV1) GetImage(getImageOptions *GetImageOptions) (result *Image, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetImageWithContext(context.Background(), getImageOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceNetworkInterfaceFloatingIPWithContext is an alternate form of the GetInstanceNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) GetInstanceNetworkInterfaceFloatingIPWithContext(ctx context.Context, getInstanceNetworkInterfaceFloatingIPOptions *GetInstanceNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceNetworkInterfaceFloatingIPOptions, "getInstanceNetworkInterfaceFloatingIPOptions cannot be nil") +// GetImageWithContext is an alternate form of the GetImage method which supports a Context parameter +func (vpc *VpcV1) GetImageWithContext(ctx context.Context, getImageOptions *GetImageOptions) (result *Image, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getImageOptions, "getImageOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceNetworkInterfaceFloatingIPOptions, "getInstanceNetworkInterfaceFloatingIPOptions") + err = core.ValidateStruct(getImageOptions, "getImageOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *getInstanceNetworkInterfaceFloatingIPOptions.InstanceID, - "network_interface_id": *getInstanceNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, - "id": *getInstanceNetworkInterfaceFloatingIPOptions.ID, + "id": *getImageOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetImage") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getImageOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -8442,12 +8711,12 @@ func (vpc *VpcV1) GetInstanceNetworkInterfaceFloatingIPWithContext(ctx context.C var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_image", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImage) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8458,62 +8727,62 @@ func (vpc *VpcV1) GetInstanceNetworkInterfaceFloatingIPWithContext(ctx context.C return } -// AddInstanceNetworkInterfaceFloatingIP : Associate a floating IP with an instance network interface -// This request associates the specified floating IP with the specified instance network interface, replacing any -// existing association. -// -// The existing floating IP must: -// - not be required by another resource, such as a public gateway -// - be in the same `zone` as the instance -// -// A request body is not required, and if provided, is ignored. -func (vpc *VpcV1) AddInstanceNetworkInterfaceFloatingIP(addInstanceNetworkInterfaceFloatingIPOptions *AddInstanceNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.AddInstanceNetworkInterfaceFloatingIPWithContext(context.Background(), addInstanceNetworkInterfaceFloatingIPOptions) +// UpdateImage : Update an image +// This request updates an image with the information in a provided image patch. The image patch object is structured in +// the same way as a retrieved image and contains only the information to be updated. An image with `remote.account` set +// is not allowed to be updated. An image with a `status` of `deleting` cannot be updated. +func (vpc *VpcV1) UpdateImage(updateImageOptions *UpdateImageOptions) (result *Image, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateImageWithContext(context.Background(), updateImageOptions) err = core.RepurposeSDKProblem(err, "") return } -// AddInstanceNetworkInterfaceFloatingIPWithContext is an alternate form of the AddInstanceNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) AddInstanceNetworkInterfaceFloatingIPWithContext(ctx context.Context, addInstanceNetworkInterfaceFloatingIPOptions *AddInstanceNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(addInstanceNetworkInterfaceFloatingIPOptions, "addInstanceNetworkInterfaceFloatingIPOptions cannot be nil") +// UpdateImageWithContext is an alternate form of the UpdateImage method which supports a Context parameter +func (vpc *VpcV1) UpdateImageWithContext(ctx context.Context, updateImageOptions *UpdateImageOptions) (result *Image, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateImageOptions, "updateImageOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(addInstanceNetworkInterfaceFloatingIPOptions, "addInstanceNetworkInterfaceFloatingIPOptions") + err = core.ValidateStruct(updateImageOptions, "updateImageOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *addInstanceNetworkInterfaceFloatingIPOptions.InstanceID, - "network_interface_id": *addInstanceNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, - "id": *addInstanceNetworkInterfaceFloatingIPOptions.ID, + "id": *updateImageOptions.ID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range addInstanceNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateImage") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddInstanceNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateImageOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateImageOptions.ImagePatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -8523,12 +8792,12 @@ func (vpc *VpcV1) AddInstanceNetworkInterfaceFloatingIPWithContext(ctx context.C var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "add_instance_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_image", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImage) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8539,61 +8808,59 @@ func (vpc *VpcV1) AddInstanceNetworkInterfaceFloatingIPWithContext(ctx context.C return } -// ListInstanceNetworkInterfaceIps : List the primary reserved IP for an instance network interface -// This request lists the primary reserved IP for an instance network interface. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) ListInstanceNetworkInterfaceIps(listInstanceNetworkInterfaceIpsOptions *ListInstanceNetworkInterfaceIpsOptions) (result *ReservedIPCollectionInstanceNetworkInterfaceContext, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceNetworkInterfaceIpsWithContext(context.Background(), listInstanceNetworkInterfaceIpsOptions) +// ListImageBareMetalServerProfiles : List bare metal server profiles compatible with an image +// This request lists bare metal server profiles compatible with an image's +// `allowed_use.bare_metal_server`, `operating_system.architecture` and +// `user_data_format` properties, sorted by ascending `name` property values. +func (vpc *VpcV1) ListImageBareMetalServerProfiles(listImageBareMetalServerProfilesOptions *ListImageBareMetalServerProfilesOptions) (result *ImageBareMetalServerProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListImageBareMetalServerProfilesWithContext(context.Background(), listImageBareMetalServerProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceNetworkInterfaceIpsWithContext is an alternate form of the ListInstanceNetworkInterfaceIps method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) ListInstanceNetworkInterfaceIpsWithContext(ctx context.Context, listInstanceNetworkInterfaceIpsOptions *ListInstanceNetworkInterfaceIpsOptions) (result *ReservedIPCollectionInstanceNetworkInterfaceContext, response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: ListInstanceNetworkInterfaceIps") - err = core.ValidateNotNil(listInstanceNetworkInterfaceIpsOptions, "listInstanceNetworkInterfaceIpsOptions cannot be nil") +// ListImageBareMetalServerProfilesWithContext is an alternate form of the ListImageBareMetalServerProfiles method which supports a Context parameter +func (vpc *VpcV1) ListImageBareMetalServerProfilesWithContext(ctx context.Context, listImageBareMetalServerProfilesOptions *ListImageBareMetalServerProfilesOptions) (result *ImageBareMetalServerProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listImageBareMetalServerProfilesOptions, "listImageBareMetalServerProfilesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listInstanceNetworkInterfaceIpsOptions, "listInstanceNetworkInterfaceIpsOptions") + err = core.ValidateStruct(listImageBareMetalServerProfilesOptions, "listImageBareMetalServerProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *listInstanceNetworkInterfaceIpsOptions.InstanceID, - "network_interface_id": *listInstanceNetworkInterfaceIpsOptions.NetworkInterfaceID, + "id": *listImageBareMetalServerProfilesOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}/bare_metal_server_profiles`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceNetworkInterfaceIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListImageBareMetalServerProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceNetworkInterfaceIps") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listImageBareMetalServerProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listInstanceNetworkInterfaceIpsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listInstanceNetworkInterfaceIpsOptions.Start)) + if listImageBareMetalServerProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listImageBareMetalServerProfilesOptions.Start)) } - if listInstanceNetworkInterfaceIpsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listInstanceNetworkInterfaceIpsOptions.Limit)) + if listImageBareMetalServerProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listImageBareMetalServerProfilesOptions.Limit)) } request, err := builder.Build() @@ -8605,12 +8872,12 @@ func (vpc *VpcV1) ListInstanceNetworkInterfaceIpsWithContext(ctx context.Context var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_network_interface_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_image_bare_metal_server_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollectionInstanceNetworkInterfaceContext) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageBareMetalServerProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8621,57 +8888,130 @@ func (vpc *VpcV1) ListInstanceNetworkInterfaceIpsWithContext(ctx context.Context return } -// GetInstanceNetworkInterfaceIP : Retrieve the primary reserved IP -// This request retrieves the primary reserved IP for an instance network interface. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) GetInstanceNetworkInterfaceIP(getInstanceNetworkInterfaceIPOptions *GetInstanceNetworkInterfaceIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceNetworkInterfaceIPWithContext(context.Background(), getInstanceNetworkInterfaceIPOptions) +// DeprecateImage : Deprecate an image +// This request deprecates an image, resulting in its `status` becoming `deprecated` and +// `deprecation_at` being set to the current date and time. +// +// The image must: +// - have a `status` of `available` +// - have `catalog_offering.managed` set to `false` +// - not have `deprecation_at` set +// +// An image with `remote.account` set is not allowed to be deprecated. +func (vpc *VpcV1) DeprecateImage(deprecateImageOptions *DeprecateImageOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeprecateImageWithContext(context.Background(), deprecateImageOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceNetworkInterfaceIPWithContext is an alternate form of the GetInstanceNetworkInterfaceIP method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) GetInstanceNetworkInterfaceIPWithContext(ctx context.Context, getInstanceNetworkInterfaceIPOptions *GetInstanceNetworkInterfaceIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: GetInstanceNetworkInterfaceIP") - err = core.ValidateNotNil(getInstanceNetworkInterfaceIPOptions, "getInstanceNetworkInterfaceIPOptions cannot be nil") +// DeprecateImageWithContext is an alternate form of the DeprecateImage method which supports a Context parameter +func (vpc *VpcV1) DeprecateImageWithContext(ctx context.Context, deprecateImageOptions *DeprecateImageOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deprecateImageOptions, "deprecateImageOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceNetworkInterfaceIPOptions, "getInstanceNetworkInterfaceIPOptions") + err = core.ValidateStruct(deprecateImageOptions, "deprecateImageOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *getInstanceNetworkInterfaceIPOptions.InstanceID, - "network_interface_id": *getInstanceNetworkInterfaceIPOptions.NetworkInterfaceID, - "id": *getInstanceNetworkInterfaceIPOptions.ID, + "id": *deprecateImageOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}/deprecate`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceNetworkInterfaceIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeprecateImage") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceNetworkInterfaceIP") + for headerName, headerValue := range deprecateImageOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "deprecate_image", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// ListImageInstanceProfiles : List instance profiles compatible with an image +// This request lists instance profiles compatible with an image's +// `allowed_use.instance`, `operating_system.architecture` and +// `user_data_format` properties, sorted by ascending `name` property values. +func (vpc *VpcV1) ListImageInstanceProfiles(listImageInstanceProfilesOptions *ListImageInstanceProfilesOptions) (result *ImageInstanceProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListImageInstanceProfilesWithContext(context.Background(), listImageInstanceProfilesOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListImageInstanceProfilesWithContext is an alternate form of the ListImageInstanceProfiles method which supports a Context parameter +func (vpc *VpcV1) ListImageInstanceProfilesWithContext(ctx context.Context, listImageInstanceProfilesOptions *ListImageInstanceProfilesOptions) (result *ImageInstanceProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listImageInstanceProfilesOptions, "listImageInstanceProfilesOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listImageInstanceProfilesOptions, "listImageInstanceProfilesOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "id": *listImageInstanceProfilesOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}/instance_profiles`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListImageInstanceProfiles") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range listImageInstanceProfilesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listImageInstanceProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listImageInstanceProfilesOptions.Start)) + } + if listImageInstanceProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listImageInstanceProfilesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -8682,12 +9022,12 @@ func (vpc *VpcV1) GetInstanceNetworkInterfaceIPWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_network_interface_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_image_instance_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageInstanceProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8698,54 +9038,131 @@ func (vpc *VpcV1) GetInstanceNetworkInterfaceIPWithContext(ctx context.Context, return } -// ListInstanceVolumeAttachments : List volumes attachments on an instance -// This request lists volume attachments on an instance. A volume attachment connects a volume to an instance. Each -// instance may have many volume attachments but each volume attachment connects exactly one instance to exactly one -// volume. -func (vpc *VpcV1) ListInstanceVolumeAttachments(listInstanceVolumeAttachmentsOptions *ListInstanceVolumeAttachmentsOptions) (result *VolumeAttachmentCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListInstanceVolumeAttachmentsWithContext(context.Background(), listInstanceVolumeAttachmentsOptions) +// ObsoleteImage : Obsolete an image +// This request obsoletes an image, resulting in its `status` becoming `obsolete` and +// `obsolescence_at` being set to the current date and time. +// +// The image must: +// - have a `status` of `available` or `deprecated` +// - have `catalog_offering.managed` set to `false` +// - not have `deprecation_at` set in the future +// - not have `obsolescence_at` set +// +// An image with `remote.account` set is not allowed to be obsoleted. +func (vpc *VpcV1) ObsoleteImage(obsoleteImageOptions *ObsoleteImageOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.ObsoleteImageWithContext(context.Background(), obsoleteImageOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListInstanceVolumeAttachmentsWithContext is an alternate form of the ListInstanceVolumeAttachments method which supports a Context parameter -func (vpc *VpcV1) ListInstanceVolumeAttachmentsWithContext(ctx context.Context, listInstanceVolumeAttachmentsOptions *ListInstanceVolumeAttachmentsOptions) (result *VolumeAttachmentCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listInstanceVolumeAttachmentsOptions, "listInstanceVolumeAttachmentsOptions cannot be nil") +// ObsoleteImageWithContext is an alternate form of the ObsoleteImage method which supports a Context parameter +func (vpc *VpcV1) ObsoleteImageWithContext(ctx context.Context, obsoleteImageOptions *ObsoleteImageOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(obsoleteImageOptions, "obsoleteImageOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listInstanceVolumeAttachmentsOptions, "listInstanceVolumeAttachmentsOptions") + err = core.ValidateStruct(obsoleteImageOptions, "obsoleteImageOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *listInstanceVolumeAttachmentsOptions.InstanceID, + "id": *obsoleteImageOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{id}/obsolete`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listInstanceVolumeAttachmentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ObsoleteImage") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceVolumeAttachments") + for headerName, headerValue := range obsoleteImageOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "obsolete_image", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// ListImageExportJobs : List export jobs for an image +// This request lists export jobs for an image. Each job tracks the exporting of the image to another location, such as +// a bucket within cloud object storage. +// +// The jobs will be sorted by their `created_at` property values, with newest jobs first. Jobs with identical +// `created_at` property values will in turn be sorted by ascending +// `name` property values. +func (vpc *VpcV1) ListImageExportJobs(listImageExportJobsOptions *ListImageExportJobsOptions) (result *ImageExportJobUnpaginatedCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListImageExportJobsWithContext(context.Background(), listImageExportJobsOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListImageExportJobsWithContext is an alternate form of the ListImageExportJobs method which supports a Context parameter +func (vpc *VpcV1) ListImageExportJobsWithContext(ctx context.Context, listImageExportJobsOptions *ListImageExportJobsOptions) (result *ImageExportJobUnpaginatedCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listImageExportJobsOptions, "listImageExportJobsOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listImageExportJobsOptions, "listImageExportJobsOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "image_id": *listImageExportJobsOptions.ImageID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListImageExportJobs") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range listImageExportJobsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listImageExportJobsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listImageExportJobsOptions.Name)) + } request, err := builder.Build() if err != nil { @@ -8756,12 +9173,12 @@ func (vpc *VpcV1) ListInstanceVolumeAttachmentsWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_instance_volume_attachments", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_image_export_jobs", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeAttachmentCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageExportJobUnpaginatedCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8772,49 +9189,49 @@ func (vpc *VpcV1) ListInstanceVolumeAttachmentsWithContext(ctx context.Context, return } -// CreateInstanceVolumeAttachment : Create a volume attachment on an instance -// This request creates a new volume attachment from a volume attachment prototype object, connecting a volume to an -// instance. For this request to succeed, the specified volume must not be busy. The prototype object is structured in -// the same way as a retrieved volume attachment, and contains the information necessary to create the new volume -// attachment. -func (vpc *VpcV1) CreateInstanceVolumeAttachment(createInstanceVolumeAttachmentOptions *CreateInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateInstanceVolumeAttachmentWithContext(context.Background(), createInstanceVolumeAttachmentOptions) +// CreateImageExportJob : Create an export job for an image +// This request creates and queues a new export job for the image specified in the URL using the image export job +// prototype object. The image must be owned by the account and be in the `available`, `deprecated`, `obsolete`, or +// `unusable` state. The prototype object is structured in the same way as a retrieved image export job, and contains +// the information necessary to create and queue the new image export job. +func (vpc *VpcV1) CreateImageExportJob(createImageExportJobOptions *CreateImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateImageExportJobWithContext(context.Background(), createImageExportJobOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateInstanceVolumeAttachmentWithContext is an alternate form of the CreateInstanceVolumeAttachment method which supports a Context parameter -func (vpc *VpcV1) CreateInstanceVolumeAttachmentWithContext(ctx context.Context, createInstanceVolumeAttachmentOptions *CreateInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createInstanceVolumeAttachmentOptions, "createInstanceVolumeAttachmentOptions cannot be nil") +// CreateImageExportJobWithContext is an alternate form of the CreateImageExportJob method which supports a Context parameter +func (vpc *VpcV1) CreateImageExportJobWithContext(ctx context.Context, createImageExportJobOptions *CreateImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createImageExportJobOptions, "createImageExportJobOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createInstanceVolumeAttachmentOptions, "createInstanceVolumeAttachmentOptions") + err = core.ValidateStruct(createImageExportJobOptions, "createImageExportJobOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *createInstanceVolumeAttachmentOptions.InstanceID, + "image_id": *createImageExportJobOptions.ImageID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createInstanceVolumeAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateImageExportJob") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceVolumeAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createImageExportJobOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -8824,14 +9241,14 @@ func (vpc *VpcV1) CreateInstanceVolumeAttachmentWithContext(ctx context.Context, builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createInstanceVolumeAttachmentOptions.Volume != nil { - body["volume"] = createInstanceVolumeAttachmentOptions.Volume + if createImageExportJobOptions.StorageBucket != nil { + body["storage_bucket"] = createImageExportJobOptions.StorageBucket } - if createInstanceVolumeAttachmentOptions.DeleteVolumeOnInstanceDelete != nil { - body["delete_volume_on_instance_delete"] = createInstanceVolumeAttachmentOptions.DeleteVolumeOnInstanceDelete + if createImageExportJobOptions.Format != nil { + body["format"] = createImageExportJobOptions.Format } - if createInstanceVolumeAttachmentOptions.Name != nil { - body["name"] = createInstanceVolumeAttachmentOptions.Name + if createImageExportJobOptions.Name != nil { + body["name"] = createImageExportJobOptions.Name } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -8848,12 +9265,12 @@ func (vpc *VpcV1) CreateInstanceVolumeAttachmentWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_instance_volume_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_image_export_job", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageExportJob) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -8864,48 +9281,49 @@ func (vpc *VpcV1) CreateInstanceVolumeAttachmentWithContext(ctx context.Context, return } -// DeleteInstanceVolumeAttachment : Delete a volume attachment -// This request deletes a volume attachment. This operation cannot be reversed, but a new volume attachment may -// subsequently be created for the volume. For this request to succeed, the volume must not be busy. -func (vpc *VpcV1) DeleteInstanceVolumeAttachment(deleteInstanceVolumeAttachmentOptions *DeleteInstanceVolumeAttachmentOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteInstanceVolumeAttachmentWithContext(context.Background(), deleteInstanceVolumeAttachmentOptions) +// DeleteImageExportJob : Delete an image export job +// This request deletes an image export job. This operation cannot be reversed. If the job has not completed, the job +// will be canceled, and the incomplete exported image object deleted. If the job has completed, the exported image +// object will not be deleted. +func (vpc *VpcV1) DeleteImageExportJob(deleteImageExportJobOptions *DeleteImageExportJobOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteImageExportJobWithContext(context.Background(), deleteImageExportJobOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteInstanceVolumeAttachmentWithContext is an alternate form of the DeleteInstanceVolumeAttachment method which supports a Context parameter -func (vpc *VpcV1) DeleteInstanceVolumeAttachmentWithContext(ctx context.Context, deleteInstanceVolumeAttachmentOptions *DeleteInstanceVolumeAttachmentOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteInstanceVolumeAttachmentOptions, "deleteInstanceVolumeAttachmentOptions cannot be nil") +// DeleteImageExportJobWithContext is an alternate form of the DeleteImageExportJob method which supports a Context parameter +func (vpc *VpcV1) DeleteImageExportJobWithContext(ctx context.Context, deleteImageExportJobOptions *DeleteImageExportJobOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteImageExportJobOptions, "deleteImageExportJobOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteInstanceVolumeAttachmentOptions, "deleteInstanceVolumeAttachmentOptions") + err = core.ValidateStruct(deleteImageExportJobOptions, "deleteImageExportJobOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *deleteInstanceVolumeAttachmentOptions.InstanceID, - "id": *deleteInstanceVolumeAttachmentOptions.ID, + "image_id": *deleteImageExportJobOptions.ImageID, + "id": *deleteImageExportJobOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteInstanceVolumeAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteImageExportJob") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceVolumeAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteImageExportJobOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -8920,7 +9338,7 @@ func (vpc *VpcV1) DeleteInstanceVolumeAttachmentWithContext(ctx context.Context, response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_instance_volume_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_image_export_job", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -8928,47 +9346,47 @@ func (vpc *VpcV1) DeleteInstanceVolumeAttachmentWithContext(ctx context.Context, return } -// GetInstanceVolumeAttachment : Retrieve a volume attachment -// This request retrieves a single volume attachment specified by the identifier in the URL. -func (vpc *VpcV1) GetInstanceVolumeAttachment(getInstanceVolumeAttachmentOptions *GetInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetInstanceVolumeAttachmentWithContext(context.Background(), getInstanceVolumeAttachmentOptions) +// GetImageExportJob : Retrieve an image export job +// This request retrieves a single image export job specified by the identifier in the URL. +func (vpc *VpcV1) GetImageExportJob(getImageExportJobOptions *GetImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetImageExportJobWithContext(context.Background(), getImageExportJobOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetInstanceVolumeAttachmentWithContext is an alternate form of the GetInstanceVolumeAttachment method which supports a Context parameter -func (vpc *VpcV1) GetInstanceVolumeAttachmentWithContext(ctx context.Context, getInstanceVolumeAttachmentOptions *GetInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getInstanceVolumeAttachmentOptions, "getInstanceVolumeAttachmentOptions cannot be nil") +// GetImageExportJobWithContext is an alternate form of the GetImageExportJob method which supports a Context parameter +func (vpc *VpcV1) GetImageExportJobWithContext(ctx context.Context, getImageExportJobOptions *GetImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getImageExportJobOptions, "getImageExportJobOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getInstanceVolumeAttachmentOptions, "getInstanceVolumeAttachmentOptions") + err = core.ValidateStruct(getImageExportJobOptions, "getImageExportJobOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *getInstanceVolumeAttachmentOptions.InstanceID, - "id": *getInstanceVolumeAttachmentOptions.ID, + "image_id": *getImageExportJobOptions.ImageID, + "id": *getImageExportJobOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getInstanceVolumeAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetImageExportJob") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceVolumeAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getImageExportJobOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -8985,12 +9403,12 @@ func (vpc *VpcV1) GetInstanceVolumeAttachmentWithContext(ctx context.Context, ge var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_instance_volume_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_image_export_job", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageExportJob) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -9001,49 +9419,49 @@ func (vpc *VpcV1) GetInstanceVolumeAttachmentWithContext(ctx context.Context, ge return } -// UpdateInstanceVolumeAttachment : Update a volume attachment -// This request updates a volume attachment with the information provided in a volume attachment patch object. The -// volume attachment patch object is structured in the same way as a retrieved volume attachment and needs to contain -// only the information to be updated. -func (vpc *VpcV1) UpdateInstanceVolumeAttachment(updateInstanceVolumeAttachmentOptions *UpdateInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateInstanceVolumeAttachmentWithContext(context.Background(), updateInstanceVolumeAttachmentOptions) +// UpdateImageExportJob : Update an image export job +// This request updates an image export job with the information in a provided image export job patch. The image export +// job patch object is structured in the same way as a retrieved image export job and contains only the information to +// be updated. +func (vpc *VpcV1) UpdateImageExportJob(updateImageExportJobOptions *UpdateImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateImageExportJobWithContext(context.Background(), updateImageExportJobOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateInstanceVolumeAttachmentWithContext is an alternate form of the UpdateInstanceVolumeAttachment method which supports a Context parameter -func (vpc *VpcV1) UpdateInstanceVolumeAttachmentWithContext(ctx context.Context, updateInstanceVolumeAttachmentOptions *UpdateInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateInstanceVolumeAttachmentOptions, "updateInstanceVolumeAttachmentOptions cannot be nil") +// UpdateImageExportJobWithContext is an alternate form of the UpdateImageExportJob method which supports a Context parameter +func (vpc *VpcV1) UpdateImageExportJobWithContext(ctx context.Context, updateImageExportJobOptions *UpdateImageExportJobOptions) (result *ImageExportJob, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateImageExportJobOptions, "updateImageExportJobOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateInstanceVolumeAttachmentOptions, "updateInstanceVolumeAttachmentOptions") + err = core.ValidateStruct(updateImageExportJobOptions, "updateImageExportJobOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "instance_id": *updateInstanceVolumeAttachmentOptions.InstanceID, - "id": *updateInstanceVolumeAttachmentOptions.ID, + "image_id": *updateImageExportJobOptions.ImageID, + "id": *updateImageExportJobOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/images/{image_id}/export_jobs/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateInstanceVolumeAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateImageExportJob") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceVolumeAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateImageExportJobOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9052,7 +9470,7 @@ func (vpc *VpcV1) UpdateInstanceVolumeAttachmentWithContext(ctx context.Context, builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateInstanceVolumeAttachmentOptions.VolumeAttachmentPatch) + _, err = builder.SetBodyContentJSON(updateImageExportJobOptions.ImageExportJobPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -9067,12 +9485,153 @@ func (vpc *VpcV1) UpdateInstanceVolumeAttachmentWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_instance_volume_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_image_export_job", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalImageExportJob) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// ListOperatingSystems : List operating systems +// This request lists operating systems in the region. +func (vpc *VpcV1) ListOperatingSystems(listOperatingSystemsOptions *ListOperatingSystemsOptions) (result *OperatingSystemCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListOperatingSystemsWithContext(context.Background(), listOperatingSystemsOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListOperatingSystemsWithContext is an alternate form of the ListOperatingSystems method which supports a Context parameter +func (vpc *VpcV1) ListOperatingSystemsWithContext(ctx context.Context, listOperatingSystemsOptions *ListOperatingSystemsOptions) (result *OperatingSystemCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listOperatingSystemsOptions, "listOperatingSystemsOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/operating_systems`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListOperatingSystems") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range listOperatingSystemsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listOperatingSystemsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listOperatingSystemsOptions.Start)) + } + if listOperatingSystemsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listOperatingSystemsOptions.Limit)) + } + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "list_operating_systems", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalOperatingSystemCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// GetOperatingSystem : Retrieve an operating system +// This request retrieves a single operating system specified by the name in the URL. +func (vpc *VpcV1) GetOperatingSystem(getOperatingSystemOptions *GetOperatingSystemOptions) (result *OperatingSystem, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetOperatingSystemWithContext(context.Background(), getOperatingSystemOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetOperatingSystemWithContext is an alternate form of the GetOperatingSystem method which supports a Context parameter +func (vpc *VpcV1) GetOperatingSystemWithContext(ctx context.Context, getOperatingSystemOptions *GetOperatingSystemOptions) (result *OperatingSystem, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getOperatingSystemOptions, "getOperatingSystemOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getOperatingSystemOptions, "getOperatingSystemOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "name": *getOperatingSystemOptions.Name, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/operating_systems/{name}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetOperatingSystem") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range getOperatingSystemOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "get_operating_system", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalOperatingSystem) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -9108,12 +9667,12 @@ func (vpc *VpcV1) ListInstanceGroupsWithContext(ctx context.Context, listInstanc return } - for headerName, headerValue := range listInstanceGroupsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroups") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroups") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceGroupsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9182,12 +9741,12 @@ func (vpc *VpcV1) CreateInstanceGroupWithContext(ctx context.Context, createInst return } - for headerName, headerValue := range createInstanceGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9287,12 +9846,12 @@ func (vpc *VpcV1) DeleteInstanceGroupWithContext(ctx context.Context, deleteInst return } - for headerName, headerValue := range deleteInstanceGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -9349,12 +9908,12 @@ func (vpc *VpcV1) GetInstanceGroupWithContext(ctx context.Context, getInstanceGr return } - for headerName, headerValue := range getInstanceGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9422,12 +9981,12 @@ func (vpc *VpcV1) UpdateInstanceGroupWithContext(ctx context.Context, updateInst return } - for headerName, headerValue := range updateInstanceGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9501,12 +10060,12 @@ func (vpc *VpcV1) DeleteInstanceGroupLoadBalancerWithContext(ctx context.Context return } - for headerName, headerValue := range deleteInstanceGroupLoadBalancerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupLoadBalancer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupLoadBalancer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceGroupLoadBalancerOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -9563,12 +10122,12 @@ func (vpc *VpcV1) ListInstanceGroupManagersWithContext(ctx context.Context, list return } - for headerName, headerValue := range listInstanceGroupManagersOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroupManagers") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroupManagers") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceGroupManagersOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9641,12 +10200,12 @@ func (vpc *VpcV1) CreateInstanceGroupManagerWithContext(ctx context.Context, cre return } - for headerName, headerValue := range createInstanceGroupManagerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceGroupManager") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceGroupManager") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceGroupManagerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9721,12 +10280,12 @@ func (vpc *VpcV1) DeleteInstanceGroupManagerWithContext(ctx context.Context, del return } - for headerName, headerValue := range deleteInstanceGroupManagerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupManager") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupManager") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceGroupManagerOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -9784,12 +10343,12 @@ func (vpc *VpcV1) GetInstanceGroupManagerWithContext(ctx context.Context, getIns return } - for headerName, headerValue := range getInstanceGroupManagerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroupManager") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroupManager") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceGroupManagerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9857,12 +10416,12 @@ func (vpc *VpcV1) UpdateInstanceGroupManagerWithContext(ctx context.Context, upd return } - for headerName, headerValue := range updateInstanceGroupManagerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroupManager") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroupManager") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceGroupManagerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -9937,12 +10496,12 @@ func (vpc *VpcV1) ListInstanceGroupManagerActionsWithContext(ctx context.Context return } - for headerName, headerValue := range listInstanceGroupManagerActionsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroupManagerActions") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroupManagerActions") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceGroupManagerActionsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10016,12 +10575,12 @@ func (vpc *VpcV1) CreateInstanceGroupManagerActionWithContext(ctx context.Contex return } - for headerName, headerValue := range createInstanceGroupManagerActionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceGroupManagerAction") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceGroupManagerAction") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceGroupManagerActionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10097,12 +10656,12 @@ func (vpc *VpcV1) DeleteInstanceGroupManagerActionWithContext(ctx context.Contex return } - for headerName, headerValue := range deleteInstanceGroupManagerActionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupManagerAction") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupManagerAction") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceGroupManagerActionOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -10161,12 +10720,12 @@ func (vpc *VpcV1) GetInstanceGroupManagerActionWithContext(ctx context.Context, return } - for headerName, headerValue := range getInstanceGroupManagerActionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroupManagerAction") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroupManagerAction") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceGroupManagerActionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10235,12 +10794,12 @@ func (vpc *VpcV1) UpdateInstanceGroupManagerActionWithContext(ctx context.Contex return } - for headerName, headerValue := range updateInstanceGroupManagerActionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroupManagerAction") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroupManagerAction") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceGroupManagerActionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10315,12 +10874,12 @@ func (vpc *VpcV1) ListInstanceGroupManagerPoliciesWithContext(ctx context.Contex return } - for headerName, headerValue := range listInstanceGroupManagerPoliciesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroupManagerPolicies") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroupManagerPolicies") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceGroupManagerPoliciesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10394,12 +10953,12 @@ func (vpc *VpcV1) CreateInstanceGroupManagerPolicyWithContext(ctx context.Contex return } - for headerName, headerValue := range createInstanceGroupManagerPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceGroupManagerPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceGroupManagerPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceGroupManagerPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10475,12 +11034,12 @@ func (vpc *VpcV1) DeleteInstanceGroupManagerPolicyWithContext(ctx context.Contex return } - for headerName, headerValue := range deleteInstanceGroupManagerPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupManagerPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupManagerPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceGroupManagerPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -10539,12 +11098,12 @@ func (vpc *VpcV1) GetInstanceGroupManagerPolicyWithContext(ctx context.Context, return } - for headerName, headerValue := range getInstanceGroupManagerPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroupManagerPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroupManagerPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceGroupManagerPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10613,12 +11172,12 @@ func (vpc *VpcV1) UpdateInstanceGroupManagerPolicyWithContext(ctx context.Contex return } - for headerName, headerValue := range updateInstanceGroupManagerPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroupManagerPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroupManagerPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceGroupManagerPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10693,12 +11252,12 @@ func (vpc *VpcV1) DeleteInstanceGroupMembershipsWithContext(ctx context.Context, return } - for headerName, headerValue := range deleteInstanceGroupMembershipsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupMemberships") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupMemberships") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceGroupMembershipsOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -10755,12 +11314,12 @@ func (vpc *VpcV1) ListInstanceGroupMembershipsWithContext(ctx context.Context, l return } - for headerName, headerValue := range listInstanceGroupMembershipsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroupMemberships") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceGroupMemberships") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceGroupMembershipsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10835,12 +11394,12 @@ func (vpc *VpcV1) DeleteInstanceGroupMembershipWithContext(ctx context.Context, return } - for headerName, headerValue := range deleteInstanceGroupMembershipOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupMembership") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceGroupMembership") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceGroupMembershipOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -10898,12 +11457,12 @@ func (vpc *VpcV1) GetInstanceGroupMembershipWithContext(ctx context.Context, get return } - for headerName, headerValue := range getInstanceGroupMembershipOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroupMembership") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceGroupMembership") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceGroupMembershipOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -10971,12 +11530,12 @@ func (vpc *VpcV1) UpdateInstanceGroupMembershipWithContext(ctx context.Context, return } - for headerName, headerValue := range updateInstanceGroupMembershipOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroupMembership") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceGroupMembership") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceGroupMembershipOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -11016,21 +11575,17 @@ func (vpc *VpcV1) UpdateInstanceGroupMembershipWithContext(ctx context.Context, return } -// ListReservations : List reservations -// This request lists reservations in the region. A reservation provides reserved capacity for a specified profile in a -// specified zone. A reservation can also include a long-term committed use discount. -// -// The reservations will be sorted by their `created_at` property values, with newest reservations first. Reservations -// with identical `created_at` property values will in turn be sorted by ascending `name` property values. -func (vpc *VpcV1) ListReservations(listReservationsOptions *ListReservationsOptions) (result *ReservationCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListReservationsWithContext(context.Background(), listReservationsOptions) +// ListInstanceTemplates : List instance templates +// This request lists instance templates in the region. +func (vpc *VpcV1) ListInstanceTemplates(listInstanceTemplatesOptions *ListInstanceTemplatesOptions) (result *InstanceTemplateCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceTemplatesWithContext(context.Background(), listInstanceTemplatesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListReservationsWithContext is an alternate form of the ListReservations method which supports a Context parameter -func (vpc *VpcV1) ListReservationsWithContext(ctx context.Context, listReservationsOptions *ListReservationsOptions) (result *ReservationCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listReservationsOptions, "listReservationsOptions") +// ListInstanceTemplatesWithContext is an alternate form of the ListInstanceTemplates method which supports a Context parameter +func (vpc *VpcV1) ListInstanceTemplatesWithContext(ctx context.Context, listInstanceTemplatesOptions *ListInstanceTemplatesOptions) (result *InstanceTemplateCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listInstanceTemplatesOptions, "listInstanceTemplatesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -11039,45 +11594,24 @@ func (vpc *VpcV1) ListReservationsWithContext(ctx context.Context, listReservati builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listReservationsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceTemplates") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListReservations") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceTemplatesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listReservationsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listReservationsOptions.Start)) - } - if listReservationsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listReservationsOptions.Limit)) - } - if listReservationsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listReservationsOptions.Name)) - } - if listReservationsOptions.ProfileResourceType != nil { - builder.AddQuery("profile.resource_type", fmt.Sprint(*listReservationsOptions.ProfileResourceType)) - } - if listReservationsOptions.AffinityPolicy != nil { - builder.AddQuery("affinity_policy", fmt.Sprint(*listReservationsOptions.AffinityPolicy)) - } - if listReservationsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listReservationsOptions.ResourceGroupID)) - } - if listReservationsOptions.ZoneName != nil { - builder.AddQuery("zone.name", fmt.Sprint(*listReservationsOptions.ZoneName)) - } request, err := builder.Build() if err != nil { @@ -11088,12 +11622,12 @@ func (vpc *VpcV1) ListReservationsWithContext(ctx context.Context, listReservati var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_reservations", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_instance_templates", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservationCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceTemplateCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11104,23 +11638,26 @@ func (vpc *VpcV1) ListReservationsWithContext(ctx context.Context, listReservati return } -// CreateReservation : Create a reservation -// This request creates a new reservation from a reservation prototype object. The prototype object is structured in the -// same way as a retrieved reservation, and contains the information necessary to create the new reservation. -func (vpc *VpcV1) CreateReservation(createReservationOptions *CreateReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateReservationWithContext(context.Background(), createReservationOptions) +// CreateInstanceTemplate : Create an instance template +// This request creates a new instance template. The prototype object is structured in the same way as a retrieved +// instance template, and contains the information necessary to provision a new instance from the template. +// +// If a `source_template` is specified in the prototype object, its contents are copied into the new template prior to +// copying any other properties provided in the prototype object. +func (vpc *VpcV1) CreateInstanceTemplate(createInstanceTemplateOptions *CreateInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateInstanceTemplateWithContext(context.Background(), createInstanceTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateReservationWithContext is an alternate form of the CreateReservation method which supports a Context parameter -func (vpc *VpcV1) CreateReservationWithContext(ctx context.Context, createReservationOptions *CreateReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createReservationOptions, "createReservationOptions cannot be nil") +// CreateInstanceTemplateWithContext is an alternate form of the CreateInstanceTemplate method which supports a Context parameter +func (vpc *VpcV1) CreateInstanceTemplateWithContext(ctx context.Context, createInstanceTemplateOptions *CreateInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createInstanceTemplateOptions, "createInstanceTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createReservationOptions, "createReservationOptions") + err = core.ValidateStruct(createInstanceTemplateOptions, "createInstanceTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -11129,18 +11666,18 @@ func (vpc *VpcV1) CreateReservationWithContext(ctx context.Context, createReserv builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createReservationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateReservation") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -11149,29 +11686,7 @@ func (vpc *VpcV1) CreateReservationWithContext(ctx context.Context, createReserv builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createReservationOptions.Capacity != nil { - body["capacity"] = createReservationOptions.Capacity - } - if createReservationOptions.CommittedUse != nil { - body["committed_use"] = createReservationOptions.CommittedUse - } - if createReservationOptions.Profile != nil { - body["profile"] = createReservationOptions.Profile - } - if createReservationOptions.Zone != nil { - body["zone"] = createReservationOptions.Zone - } - if createReservationOptions.AffinityPolicy != nil { - body["affinity_policy"] = createReservationOptions.AffinityPolicy - } - if createReservationOptions.Name != nil { - body["name"] = createReservationOptions.Name - } - if createReservationOptions.ResourceGroup != nil { - body["resource_group"] = createReservationOptions.ResourceGroup - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(createInstanceTemplateOptions.InstanceTemplatePrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -11186,12 +11701,12 @@ func (vpc *VpcV1) CreateReservationWithContext(ctx context.Context, createReserv var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_reservation", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_instance_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservation) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceTemplate) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11202,50 +11717,48 @@ func (vpc *VpcV1) CreateReservationWithContext(ctx context.Context, createReserv return } -// DeleteReservation : Delete a reservation -// This request deletes a reservation. This operation cannot be reversed. Reservations with a `status` of `active` are -// not allowed to be deleted. -func (vpc *VpcV1) DeleteReservation(deleteReservationOptions *DeleteReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteReservationWithContext(context.Background(), deleteReservationOptions) +// DeleteInstanceTemplate : Delete an instance template +// This request deletes the instance template. This operation cannot be reversed. +func (vpc *VpcV1) DeleteInstanceTemplate(deleteInstanceTemplateOptions *DeleteInstanceTemplateOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteInstanceTemplateWithContext(context.Background(), deleteInstanceTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteReservationWithContext is an alternate form of the DeleteReservation method which supports a Context parameter -func (vpc *VpcV1) DeleteReservationWithContext(ctx context.Context, deleteReservationOptions *DeleteReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteReservationOptions, "deleteReservationOptions cannot be nil") +// DeleteInstanceTemplateWithContext is an alternate form of the DeleteInstanceTemplate method which supports a Context parameter +func (vpc *VpcV1) DeleteInstanceTemplateWithContext(ctx context.Context, deleteInstanceTemplateOptions *DeleteInstanceTemplateOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteInstanceTemplateOptions, "deleteInstanceTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteReservationOptions, "deleteReservationOptions") + err = core.ValidateStruct(deleteInstanceTemplateOptions, "deleteInstanceTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteReservationOptions.ID, + "id": *deleteInstanceTemplateOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteReservationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteReservation") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -11256,65 +11769,56 @@ func (vpc *VpcV1) DeleteReservationWithContext(ctx context.Context, deleteReserv return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_reservation", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_instance_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservation) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetReservation : Retrieve a reservation -// This request retrieves a single reservation specified by identifier in the URL. -func (vpc *VpcV1) GetReservation(getReservationOptions *GetReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetReservationWithContext(context.Background(), getReservationOptions) +// GetInstanceTemplate : Retrieve an instance template +// This request retrieves a single instance template specified by the identifier in the URL. +func (vpc *VpcV1) GetInstanceTemplate(getInstanceTemplateOptions *GetInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceTemplateWithContext(context.Background(), getInstanceTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetReservationWithContext is an alternate form of the GetReservation method which supports a Context parameter -func (vpc *VpcV1) GetReservationWithContext(ctx context.Context, getReservationOptions *GetReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getReservationOptions, "getReservationOptions cannot be nil") +// GetInstanceTemplateWithContext is an alternate form of the GetInstanceTemplate method which supports a Context parameter +func (vpc *VpcV1) GetInstanceTemplateWithContext(ctx context.Context, getInstanceTemplateOptions *GetInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceTemplateOptions, "getInstanceTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getReservationOptions, "getReservationOptions") + err = core.ValidateStruct(getInstanceTemplateOptions, "getInstanceTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getReservationOptions.ID, + "id": *getInstanceTemplateOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getReservationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetReservation") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -11331,12 +11835,12 @@ func (vpc *VpcV1) GetReservationWithContext(ctx context.Context, getReservationO var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_reservation", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservation) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceTemplate) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11347,47 +11851,48 @@ func (vpc *VpcV1) GetReservationWithContext(ctx context.Context, getReservationO return } -// UpdateReservation : Update a reservation -// This request updates a reservation with the information provided in a reservation patch object. The patch object is -// structured in the same way as a retrieved reservation and needs to contain only the information to be updated. -func (vpc *VpcV1) UpdateReservation(updateReservationOptions *UpdateReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateReservationWithContext(context.Background(), updateReservationOptions) +// UpdateInstanceTemplate : Update an instance template +// This request updates an instance template with the information provided in the instance template patch. The instance +// template patch object is structured in the same way as a retrieved instance template and contains only the +// information to be updated. +func (vpc *VpcV1) UpdateInstanceTemplate(updateInstanceTemplateOptions *UpdateInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateInstanceTemplateWithContext(context.Background(), updateInstanceTemplateOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateReservationWithContext is an alternate form of the UpdateReservation method which supports a Context parameter -func (vpc *VpcV1) UpdateReservationWithContext(ctx context.Context, updateReservationOptions *UpdateReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateReservationOptions, "updateReservationOptions cannot be nil") +// UpdateInstanceTemplateWithContext is an alternate form of the UpdateInstanceTemplate method which supports a Context parameter +func (vpc *VpcV1) UpdateInstanceTemplateWithContext(ctx context.Context, updateInstanceTemplateOptions *UpdateInstanceTemplateOptions) (result InstanceTemplateIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateInstanceTemplateOptions, "updateInstanceTemplateOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateReservationOptions, "updateReservationOptions") + err = core.ValidateStruct(updateInstanceTemplateOptions, "updateInstanceTemplateOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateReservationOptions.ID, + "id": *updateInstanceTemplateOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/templates/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateReservationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceTemplate") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateReservation") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceTemplateOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -11396,7 +11901,7 @@ func (vpc *VpcV1) UpdateReservationWithContext(ctx context.Context, updateReserv builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateReservationOptions.ReservationPatch) + _, err = builder.SetBodyContentJSON(updateInstanceTemplateOptions.InstanceTemplatePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -11411,12 +11916,12 @@ func (vpc *VpcV1) UpdateReservationWithContext(ctx context.Context, updateReserv var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_reservation", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_instance_template", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservation) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceTemplate) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11427,48 +11932,113 @@ func (vpc *VpcV1) UpdateReservationWithContext(ctx context.Context, updateReserv return } -// ActivateReservation : Activate a reservation -// This request activates a reservation. For this request to succeed, the reservation status must be `inactive`. -func (vpc *VpcV1) ActivateReservation(activateReservationOptions *ActivateReservationOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.ActivateReservationWithContext(context.Background(), activateReservationOptions) +// ListInstanceProfiles : List instance profiles +// This request lists provisionable [instance profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) in the +// region. An instance profile specifies the performance characteristics and pricing model for an instance. +func (vpc *VpcV1) ListInstanceProfiles(listInstanceProfilesOptions *ListInstanceProfilesOptions) (result *InstanceProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceProfilesWithContext(context.Background(), listInstanceProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ActivateReservationWithContext is an alternate form of the ActivateReservation method which supports a Context parameter -func (vpc *VpcV1) ActivateReservationWithContext(ctx context.Context, activateReservationOptions *ActivateReservationOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(activateReservationOptions, "activateReservationOptions cannot be nil") +// ListInstanceProfilesWithContext is an alternate form of the ListInstanceProfiles method which supports a Context parameter +func (vpc *VpcV1) ListInstanceProfilesWithContext(ctx context.Context, listInstanceProfilesOptions *ListInstanceProfilesOptions) (result *InstanceProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listInstanceProfilesOptions, "listInstanceProfilesOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/profiles`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceProfiles") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range listInstanceProfilesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "list_instance_profiles", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceProfileCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// GetInstanceProfile : Retrieve an instance profile +// This request retrieves a single instance profile specified by the name in the URL. +func (vpc *VpcV1) GetInstanceProfile(getInstanceProfileOptions *GetInstanceProfileOptions) (result *InstanceProfile, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceProfileWithContext(context.Background(), getInstanceProfileOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetInstanceProfileWithContext is an alternate form of the GetInstanceProfile method which supports a Context parameter +func (vpc *VpcV1) GetInstanceProfileWithContext(ctx context.Context, getInstanceProfileOptions *GetInstanceProfileOptions) (result *InstanceProfile, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceProfileOptions, "getInstanceProfileOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(activateReservationOptions, "activateReservationOptions") + err = core.ValidateStruct(getInstanceProfileOptions, "getInstanceProfileOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *activateReservationOptions.ID, + "name": *getInstanceProfileOptions.Name, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations/{id}/activate`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instance/profiles/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range activateReservationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ActivateReservation") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -11479,28 +12049,36 @@ func (vpc *VpcV1) ActivateReservationWithContext(ctx context.Context, activateRe return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "activate_reservation", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_profile", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceProfile) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListDedicatedHostGroups : List dedicated host groups -// This request lists dedicated host groups in the region. Each dedicated host must belong to exactly one group, which -// controls placement of instances. Dedicated host groups do not span zones. -func (vpc *VpcV1) ListDedicatedHostGroups(listDedicatedHostGroupsOptions *ListDedicatedHostGroupsOptions) (result *DedicatedHostGroupCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListDedicatedHostGroupsWithContext(context.Background(), listDedicatedHostGroupsOptions) +// ListInstances : List instances +// This request lists instances in the region. +func (vpc *VpcV1) ListInstances(listInstancesOptions *ListInstancesOptions) (result *InstanceCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstancesWithContext(context.Background(), listInstancesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListDedicatedHostGroupsWithContext is an alternate form of the ListDedicatedHostGroups method which supports a Context parameter -func (vpc *VpcV1) ListDedicatedHostGroupsWithContext(ctx context.Context, listDedicatedHostGroupsOptions *ListDedicatedHostGroupsOptions) (result *DedicatedHostGroupCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listDedicatedHostGroupsOptions, "listDedicatedHostGroupsOptions") +// ListInstancesWithContext is an alternate form of the ListInstances method which supports a Context parameter +func (vpc *VpcV1) ListInstancesWithContext(ctx context.Context, listInstancesOptions *ListInstancesOptions) (result *InstanceCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listInstancesOptions, "listInstancesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -11509,38 +12087,83 @@ func (vpc *VpcV1) ListDedicatedHostGroupsWithContext(ctx context.Context, listDe builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listDedicatedHostGroupsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstances") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListDedicatedHostGroups") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstancesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listDedicatedHostGroupsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listDedicatedHostGroupsOptions.Start)) + if listInstancesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listInstancesOptions.Start)) } - if listDedicatedHostGroupsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listDedicatedHostGroupsOptions.Limit)) + if listInstancesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listInstancesOptions.Limit)) } - if listDedicatedHostGroupsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listDedicatedHostGroupsOptions.ResourceGroupID)) + if listInstancesOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listInstancesOptions.ResourceGroupID)) } - if listDedicatedHostGroupsOptions.ZoneName != nil { - builder.AddQuery("zone.name", fmt.Sprint(*listDedicatedHostGroupsOptions.ZoneName)) + if listInstancesOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listInstancesOptions.Name)) } - if listDedicatedHostGroupsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listDedicatedHostGroupsOptions.Name)) + if listInstancesOptions.ClusterNetworkID != nil { + builder.AddQuery("cluster_network.id", fmt.Sprint(*listInstancesOptions.ClusterNetworkID)) + } + if listInstancesOptions.ClusterNetworkCRN != nil { + builder.AddQuery("cluster_network.crn", fmt.Sprint(*listInstancesOptions.ClusterNetworkCRN)) + } + if listInstancesOptions.ClusterNetworkName != nil { + builder.AddQuery("cluster_network.name", fmt.Sprint(*listInstancesOptions.ClusterNetworkName)) + } + if listInstancesOptions.DedicatedHostID != nil { + builder.AddQuery("dedicated_host.id", fmt.Sprint(*listInstancesOptions.DedicatedHostID)) + } + if listInstancesOptions.DedicatedHostCRN != nil { + builder.AddQuery("dedicated_host.crn", fmt.Sprint(*listInstancesOptions.DedicatedHostCRN)) + } + if listInstancesOptions.DedicatedHostName != nil { + builder.AddQuery("dedicated_host.name", fmt.Sprint(*listInstancesOptions.DedicatedHostName)) + } + if listInstancesOptions.PlacementGroupID != nil { + builder.AddQuery("placement_group.id", fmt.Sprint(*listInstancesOptions.PlacementGroupID)) + } + if listInstancesOptions.PlacementGroupCRN != nil { + builder.AddQuery("placement_group.crn", fmt.Sprint(*listInstancesOptions.PlacementGroupCRN)) + } + if listInstancesOptions.PlacementGroupName != nil { + builder.AddQuery("placement_group.name", fmt.Sprint(*listInstancesOptions.PlacementGroupName)) + } + if listInstancesOptions.ReservationAffinityPolicy != nil { + builder.AddQuery("reservation_affinity.policy", fmt.Sprint(*listInstancesOptions.ReservationAffinityPolicy)) + } + if listInstancesOptions.ReservationID != nil { + builder.AddQuery("reservation.id", fmt.Sprint(*listInstancesOptions.ReservationID)) + } + if listInstancesOptions.ReservationCRN != nil { + builder.AddQuery("reservation.crn", fmt.Sprint(*listInstancesOptions.ReservationCRN)) + } + if listInstancesOptions.ReservationName != nil { + builder.AddQuery("reservation.name", fmt.Sprint(*listInstancesOptions.ReservationName)) + } + if listInstancesOptions.VPCID != nil { + builder.AddQuery("vpc.id", fmt.Sprint(*listInstancesOptions.VPCID)) + } + if listInstancesOptions.VPCCRN != nil { + builder.AddQuery("vpc.crn", fmt.Sprint(*listInstancesOptions.VPCCRN)) + } + if listInstancesOptions.VPCName != nil { + builder.AddQuery("vpc.name", fmt.Sprint(*listInstancesOptions.VPCName)) } request, err := builder.Build() @@ -11552,12 +12175,12 @@ func (vpc *VpcV1) ListDedicatedHostGroupsWithContext(ctx context.Context, listDe var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_dedicated_host_groups", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_instances", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostGroupCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11568,22 +12191,27 @@ func (vpc *VpcV1) ListDedicatedHostGroupsWithContext(ctx context.Context, listDe return } -// CreateDedicatedHostGroup : Create a dedicated host group -// This request creates a new dedicated host group. -func (vpc *VpcV1) CreateDedicatedHostGroup(createDedicatedHostGroupOptions *CreateDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateDedicatedHostGroupWithContext(context.Background(), createDedicatedHostGroupOptions) +// CreateInstance : Create an instance +// This request provisions a new instance from an instance prototype object. The prototype object is structured in the +// same way as a retrieved instance, and contains the information necessary to provision the new instance. The instance +// is automatically started. +// +// For this request to succeed, the properties in the request must adhere to the source's +// `allowed_use` property. +func (vpc *VpcV1) CreateInstance(createInstanceOptions *CreateInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateInstanceWithContext(context.Background(), createInstanceOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateDedicatedHostGroupWithContext is an alternate form of the CreateDedicatedHostGroup method which supports a Context parameter -func (vpc *VpcV1) CreateDedicatedHostGroupWithContext(ctx context.Context, createDedicatedHostGroupOptions *CreateDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createDedicatedHostGroupOptions, "createDedicatedHostGroupOptions cannot be nil") +// CreateInstanceWithContext is an alternate form of the CreateInstance method which supports a Context parameter +func (vpc *VpcV1) CreateInstanceWithContext(ctx context.Context, createInstanceOptions *CreateInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createInstanceOptions, "createInstanceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createDedicatedHostGroupOptions, "createDedicatedHostGroupOptions") + err = core.ValidateStruct(createInstanceOptions, "createInstanceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -11592,18 +12220,18 @@ func (vpc *VpcV1) CreateDedicatedHostGroupWithContext(ctx context.Context, creat builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createDedicatedHostGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstance") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateDedicatedHostGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -11612,23 +12240,7 @@ func (vpc *VpcV1) CreateDedicatedHostGroupWithContext(ctx context.Context, creat builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createDedicatedHostGroupOptions.Class != nil { - body["class"] = createDedicatedHostGroupOptions.Class - } - if createDedicatedHostGroupOptions.Family != nil { - body["family"] = createDedicatedHostGroupOptions.Family - } - if createDedicatedHostGroupOptions.Zone != nil { - body["zone"] = createDedicatedHostGroupOptions.Zone - } - if createDedicatedHostGroupOptions.Name != nil { - body["name"] = createDedicatedHostGroupOptions.Name - } - if createDedicatedHostGroupOptions.ResourceGroup != nil { - body["resource_group"] = createDedicatedHostGroupOptions.ResourceGroup - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(createInstanceOptions.InstancePrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -11643,12 +12255,12 @@ func (vpc *VpcV1) CreateDedicatedHostGroupWithContext(ctx context.Context, creat var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_dedicated_host_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_instance", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstance) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11659,48 +12271,55 @@ func (vpc *VpcV1) CreateDedicatedHostGroupWithContext(ctx context.Context, creat return } -// DeleteDedicatedHostGroup : Delete a dedicated host group -// This request deletes a dedicated host group. -func (vpc *VpcV1) DeleteDedicatedHostGroup(deleteDedicatedHostGroupOptions *DeleteDedicatedHostGroupOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteDedicatedHostGroupWithContext(context.Background(), deleteDedicatedHostGroupOptions) +// DeleteInstance : Delete an instance +// This request deletes an instance. This operation cannot be reversed. Any floating IPs associated with instance +// network interfaces are implicitly disassociated. All virtual network interfaces with `auto_delete` set to `true` +// targeting instance network attachments on the instance are automatically deleted. All flow log collectors with +// `auto_delete` set to `true` targeting the instance, the instance network attachments, the instance network +// interfaces, or the automatically deleted virtual network interfaces are automatically deleted. +func (vpc *VpcV1) DeleteInstance(deleteInstanceOptions *DeleteInstanceOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteInstanceWithContext(context.Background(), deleteInstanceOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteDedicatedHostGroupWithContext is an alternate form of the DeleteDedicatedHostGroup method which supports a Context parameter -func (vpc *VpcV1) DeleteDedicatedHostGroupWithContext(ctx context.Context, deleteDedicatedHostGroupOptions *DeleteDedicatedHostGroupOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteDedicatedHostGroupOptions, "deleteDedicatedHostGroupOptions cannot be nil") +// DeleteInstanceWithContext is an alternate form of the DeleteInstance method which supports a Context parameter +func (vpc *VpcV1) DeleteInstanceWithContext(ctx context.Context, deleteInstanceOptions *DeleteInstanceOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteInstanceOptions, "deleteInstanceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteDedicatedHostGroupOptions, "deleteDedicatedHostGroupOptions") + err = core.ValidateStruct(deleteInstanceOptions, "deleteInstanceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteDedicatedHostGroupOptions.ID, + "id": *deleteInstanceOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteDedicatedHostGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstance") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteDedicatedHostGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceOptions.Headers { builder.AddHeader(headerName, headerValue) } + if deleteInstanceOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteInstanceOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -11713,7 +12332,7 @@ func (vpc *VpcV1) DeleteDedicatedHostGroupWithContext(ctx context.Context, delet response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_dedicated_host_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_instance", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -11721,46 +12340,46 @@ func (vpc *VpcV1) DeleteDedicatedHostGroupWithContext(ctx context.Context, delet return } -// GetDedicatedHostGroup : Retrieve a dedicated host group -// This request retrieves a single dedicated host group specified by the identifier in the URL. -func (vpc *VpcV1) GetDedicatedHostGroup(getDedicatedHostGroupOptions *GetDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetDedicatedHostGroupWithContext(context.Background(), getDedicatedHostGroupOptions) +// GetInstance : Retrieve an instance +// This request retrieves a single instance specified by the identifier in the URL. +func (vpc *VpcV1) GetInstance(getInstanceOptions *GetInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceWithContext(context.Background(), getInstanceOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetDedicatedHostGroupWithContext is an alternate form of the GetDedicatedHostGroup method which supports a Context parameter -func (vpc *VpcV1) GetDedicatedHostGroupWithContext(ctx context.Context, getDedicatedHostGroupOptions *GetDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getDedicatedHostGroupOptions, "getDedicatedHostGroupOptions cannot be nil") +// GetInstanceWithContext is an alternate form of the GetInstance method which supports a Context parameter +func (vpc *VpcV1) GetInstanceWithContext(ctx context.Context, getInstanceOptions *GetInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceOptions, "getInstanceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getDedicatedHostGroupOptions, "getDedicatedHostGroupOptions") + err = core.ValidateStruct(getInstanceOptions, "getInstanceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getDedicatedHostGroupOptions.ID, + "id": *getInstanceOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getDedicatedHostGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstance") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetDedicatedHostGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -11777,12 +12396,12 @@ func (vpc *VpcV1) GetDedicatedHostGroupWithContext(ctx context.Context, getDedic var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_dedicated_host_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstance) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11793,57 +12412,62 @@ func (vpc *VpcV1) GetDedicatedHostGroupWithContext(ctx context.Context, getDedic return } -// UpdateDedicatedHostGroup : Update a dedicated host group -// This request updates a dedicated host group with the information in a provided dedicated host group patch. The -// dedicated host group patch object is structured in the same way as a retrieved dedicated host group and contains only -// the information to be updated. -func (vpc *VpcV1) UpdateDedicatedHostGroup(updateDedicatedHostGroupOptions *UpdateDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateDedicatedHostGroupWithContext(context.Background(), updateDedicatedHostGroupOptions) +// UpdateInstance : Update an instance +// This request updates an instance with the information in a provided instance patch. The instance patch object is +// structured in the same way as a retrieved instance and contains only the information to be updated. +// +// For this request to succeed, the properties in the request must adhere to the +// `allowed_use` property in the volume referenced by `boot_volume_attachment.volume`. +func (vpc *VpcV1) UpdateInstance(updateInstanceOptions *UpdateInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateInstanceWithContext(context.Background(), updateInstanceOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateDedicatedHostGroupWithContext is an alternate form of the UpdateDedicatedHostGroup method which supports a Context parameter -func (vpc *VpcV1) UpdateDedicatedHostGroupWithContext(ctx context.Context, updateDedicatedHostGroupOptions *UpdateDedicatedHostGroupOptions) (result *DedicatedHostGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateDedicatedHostGroupOptions, "updateDedicatedHostGroupOptions cannot be nil") +// UpdateInstanceWithContext is an alternate form of the UpdateInstance method which supports a Context parameter +func (vpc *VpcV1) UpdateInstanceWithContext(ctx context.Context, updateInstanceOptions *UpdateInstanceOptions) (result *Instance, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateInstanceOptions, "updateInstanceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateDedicatedHostGroupOptions, "updateDedicatedHostGroupOptions") + err = core.ValidateStruct(updateInstanceOptions, "updateInstanceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateDedicatedHostGroupOptions.ID, + "id": *updateInstanceOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateDedicatedHostGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstance") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateDedicatedHostGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateInstanceOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateInstanceOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateDedicatedHostGroupOptions.DedicatedHostGroupPatch) + _, err = builder.SetBodyContentJSON(updateInstanceOptions.InstancePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -11858,12 +12482,12 @@ func (vpc *VpcV1) UpdateDedicatedHostGroupWithContext(ctx context.Context, updat var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_dedicated_host_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_instance", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstance) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11874,50 +12498,53 @@ func (vpc *VpcV1) UpdateDedicatedHostGroupWithContext(ctx context.Context, updat return } -// ListDedicatedHostProfiles : List dedicated host profiles -// This request lists provisionable [dedicated host profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-dh-profiles) in -// the region. A dedicated host profile specifies the hardware characteristics for a dedicated host. -func (vpc *VpcV1) ListDedicatedHostProfiles(listDedicatedHostProfilesOptions *ListDedicatedHostProfilesOptions) (result *DedicatedHostProfileCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListDedicatedHostProfilesWithContext(context.Background(), listDedicatedHostProfilesOptions) +// GetInstanceInitialization : Retrieve initialization configuration for an instance +// This request retrieves configuration used to initialize the instance, such as SSH keys and the Windows administrator +// password. These can subsequently be changed on the instance and therefore may not be current. +func (vpc *VpcV1) GetInstanceInitialization(getInstanceInitializationOptions *GetInstanceInitializationOptions) (result *InstanceInitialization, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceInitializationWithContext(context.Background(), getInstanceInitializationOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListDedicatedHostProfilesWithContext is an alternate form of the ListDedicatedHostProfiles method which supports a Context parameter -func (vpc *VpcV1) ListDedicatedHostProfilesWithContext(ctx context.Context, listDedicatedHostProfilesOptions *ListDedicatedHostProfilesOptions) (result *DedicatedHostProfileCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listDedicatedHostProfilesOptions, "listDedicatedHostProfilesOptions") +// GetInstanceInitializationWithContext is an alternate form of the GetInstanceInitialization method which supports a Context parameter +func (vpc *VpcV1) GetInstanceInitializationWithContext(ctx context.Context, getInstanceInitializationOptions *GetInstanceInitializationOptions) (result *InstanceInitialization, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceInitializationOptions, "getInstanceInitializationOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getInstanceInitializationOptions, "getInstanceInitializationOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "id": *getInstanceInitializationOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/profiles`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{id}/initialization`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listDedicatedHostProfilesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceInitialization") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListDedicatedHostProfiles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceInitializationOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listDedicatedHostProfilesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listDedicatedHostProfilesOptions.Start)) - } - if listDedicatedHostProfilesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listDedicatedHostProfilesOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -11928,12 +12555,12 @@ func (vpc *VpcV1) ListDedicatedHostProfilesWithContext(ctx context.Context, list var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_dedicated_host_profiles", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_initialization", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostProfileCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceInitialization) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -11944,53 +12571,68 @@ func (vpc *VpcV1) ListDedicatedHostProfilesWithContext(ctx context.Context, list return } -// GetDedicatedHostProfile : Retrieve a dedicated host profile -// This request retrieves a single dedicated host profile specified by the name in the URL. -func (vpc *VpcV1) GetDedicatedHostProfile(getDedicatedHostProfileOptions *GetDedicatedHostProfileOptions) (result *DedicatedHostProfile, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetDedicatedHostProfileWithContext(context.Background(), getDedicatedHostProfileOptions) +// CreateInstanceAction : Create an instance action +// This request creates a new action which will be queued up to run as soon as any pending or running actions have +// completed. +func (vpc *VpcV1) CreateInstanceAction(createInstanceActionOptions *CreateInstanceActionOptions) (result *InstanceAction, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateInstanceActionWithContext(context.Background(), createInstanceActionOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetDedicatedHostProfileWithContext is an alternate form of the GetDedicatedHostProfile method which supports a Context parameter -func (vpc *VpcV1) GetDedicatedHostProfileWithContext(ctx context.Context, getDedicatedHostProfileOptions *GetDedicatedHostProfileOptions) (result *DedicatedHostProfile, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getDedicatedHostProfileOptions, "getDedicatedHostProfileOptions cannot be nil") +// CreateInstanceActionWithContext is an alternate form of the CreateInstanceAction method which supports a Context parameter +func (vpc *VpcV1) CreateInstanceActionWithContext(ctx context.Context, createInstanceActionOptions *CreateInstanceActionOptions) (result *InstanceAction, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createInstanceActionOptions, "createInstanceActionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getDedicatedHostProfileOptions, "getDedicatedHostProfileOptions") + err = core.ValidateStruct(createInstanceActionOptions, "createInstanceActionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "name": *getDedicatedHostProfileOptions.Name, + "instance_id": *createInstanceActionOptions.InstanceID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_host/profiles/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/actions`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getDedicatedHostProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceAction") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetDedicatedHostProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceActionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createInstanceActionOptions.Type != nil { + body["type"] = createInstanceActionOptions.Type + } + if createInstanceActionOptions.Force != nil { + body["force"] = createInstanceActionOptions.Force + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -12000,12 +12642,12 @@ func (vpc *VpcV1) GetDedicatedHostProfileWithContext(ctx context.Context, getDed var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_dedicated_host_profile", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_instance_action", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostProfile) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceAction) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12016,60 +12658,58 @@ func (vpc *VpcV1) GetDedicatedHostProfileWithContext(ctx context.Context, getDed return } -// ListDedicatedHosts : List dedicated hosts -// This request lists dedicated hosts in the region. -func (vpc *VpcV1) ListDedicatedHosts(listDedicatedHostsOptions *ListDedicatedHostsOptions) (result *DedicatedHostCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListDedicatedHostsWithContext(context.Background(), listDedicatedHostsOptions) +// ListInstanceClusterNetworkAttachments : List cluster network attachments on an instance +// This request lists cluster network attachments on an instance. A cluster network attachment represents a device on +// the instance to which a cluster network interface is attached. +func (vpc *VpcV1) ListInstanceClusterNetworkAttachments(listInstanceClusterNetworkAttachmentsOptions *ListInstanceClusterNetworkAttachmentsOptions) (result *InstanceClusterNetworkAttachmentCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceClusterNetworkAttachmentsWithContext(context.Background(), listInstanceClusterNetworkAttachmentsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListDedicatedHostsWithContext is an alternate form of the ListDedicatedHosts method which supports a Context parameter -func (vpc *VpcV1) ListDedicatedHostsWithContext(ctx context.Context, listDedicatedHostsOptions *ListDedicatedHostsOptions) (result *DedicatedHostCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listDedicatedHostsOptions, "listDedicatedHostsOptions") +// ListInstanceClusterNetworkAttachmentsWithContext is an alternate form of the ListInstanceClusterNetworkAttachments method which supports a Context parameter +func (vpc *VpcV1) ListInstanceClusterNetworkAttachmentsWithContext(ctx context.Context, listInstanceClusterNetworkAttachmentsOptions *ListInstanceClusterNetworkAttachmentsOptions) (result *InstanceClusterNetworkAttachmentCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listInstanceClusterNetworkAttachmentsOptions, "listInstanceClusterNetworkAttachmentsOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listInstanceClusterNetworkAttachmentsOptions, "listInstanceClusterNetworkAttachmentsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "instance_id": *listInstanceClusterNetworkAttachmentsOptions.InstanceID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listDedicatedHostsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceClusterNetworkAttachments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListDedicatedHosts") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceClusterNetworkAttachmentsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listDedicatedHostsOptions.DedicatedHostGroupID != nil { - builder.AddQuery("dedicated_host_group.id", fmt.Sprint(*listDedicatedHostsOptions.DedicatedHostGroupID)) - } - if listDedicatedHostsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listDedicatedHostsOptions.Start)) - } - if listDedicatedHostsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listDedicatedHostsOptions.Limit)) - } - if listDedicatedHostsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listDedicatedHostsOptions.ResourceGroupID)) - } - if listDedicatedHostsOptions.ZoneName != nil { - builder.AddQuery("zone.name", fmt.Sprint(*listDedicatedHostsOptions.ZoneName)) + if listInstanceClusterNetworkAttachmentsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listInstanceClusterNetworkAttachmentsOptions.Start)) } - if listDedicatedHostsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listDedicatedHostsOptions.Name)) + if listInstanceClusterNetworkAttachmentsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listInstanceClusterNetworkAttachmentsOptions.Limit)) } request, err := builder.Build() @@ -12081,12 +12721,12 @@ func (vpc *VpcV1) ListDedicatedHostsWithContext(ctx context.Context, listDedicat var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_dedicated_hosts", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_instance_cluster_network_attachments", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachmentCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12097,42 +12737,50 @@ func (vpc *VpcV1) ListDedicatedHostsWithContext(ctx context.Context, listDedicat return } -// CreateDedicatedHost : Create a dedicated host -// This request creates a new dedicated host. -func (vpc *VpcV1) CreateDedicatedHost(createDedicatedHostOptions *CreateDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateDedicatedHostWithContext(context.Background(), createDedicatedHostOptions) +// CreateClusterNetworkAttachment : Create a cluster network attachment +// This request creates a cluster network attachment from an instance cluster network attachment prototype object. A +// cluster network attachment will attach the instance to a cluster network. The cluster network attachment prototype +// must specify a cluster network interface identity or a cluster network interface prototype. +// +// The instance must be in a `stopped` or `stopping` state to create an instance cluster network attachment. +func (vpc *VpcV1) CreateClusterNetworkAttachment(createClusterNetworkAttachmentOptions *CreateClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateClusterNetworkAttachmentWithContext(context.Background(), createClusterNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateDedicatedHostWithContext is an alternate form of the CreateDedicatedHost method which supports a Context parameter -func (vpc *VpcV1) CreateDedicatedHostWithContext(ctx context.Context, createDedicatedHostOptions *CreateDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createDedicatedHostOptions, "createDedicatedHostOptions cannot be nil") +// CreateClusterNetworkAttachmentWithContext is an alternate form of the CreateClusterNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) CreateClusterNetworkAttachmentWithContext(ctx context.Context, createClusterNetworkAttachmentOptions *CreateClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createClusterNetworkAttachmentOptions, "createClusterNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createDedicatedHostOptions, "createDedicatedHostOptions") + err = core.ValidateStruct(createClusterNetworkAttachmentOptions, "createClusterNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "instance_id": *createClusterNetworkAttachmentOptions.InstanceID, + } + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createDedicatedHostOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateDedicatedHost") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createClusterNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -12141,7 +12789,17 @@ func (vpc *VpcV1) CreateDedicatedHostWithContext(ctx context.Context, createDedi builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createDedicatedHostOptions.DedicatedHostPrototype) + body := make(map[string]interface{}) + if createClusterNetworkAttachmentOptions.ClusterNetworkInterface != nil { + body["cluster_network_interface"] = createClusterNetworkAttachmentOptions.ClusterNetworkInterface + } + if createClusterNetworkAttachmentOptions.Before != nil { + body["before"] = createClusterNetworkAttachmentOptions.Before + } + if createClusterNetworkAttachmentOptions.Name != nil { + body["name"] = createClusterNetworkAttachmentOptions.Name + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -12156,12 +12814,12 @@ func (vpc *VpcV1) CreateDedicatedHostWithContext(ctx context.Context, createDedi var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_dedicated_host", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_cluster_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHost) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12172,48 +12830,50 @@ func (vpc *VpcV1) CreateDedicatedHostWithContext(ctx context.Context, createDedi return } -// ListDedicatedHostDisks : List disks on a dedicated host -// This request lists disks on a dedicated host. A disk is a physical device that is locally attached to the compute -// node. By default, the listed disks are sorted by their -// `created_at` property values, with the newest disk first. -func (vpc *VpcV1) ListDedicatedHostDisks(listDedicatedHostDisksOptions *ListDedicatedHostDisksOptions) (result *DedicatedHostDiskCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListDedicatedHostDisksWithContext(context.Background(), listDedicatedHostDisksOptions) +// DeleteInstanceClusterNetworkAttachment : Delete an instance cluster network attachment +// This request deletes an instance cluster network attachment. The instance must be in a +// `stopped` or `stopping` state to delete an instance cluster network attachment. +// +// This operation cannot be reversed. +func (vpc *VpcV1) DeleteInstanceClusterNetworkAttachment(deleteInstanceClusterNetworkAttachmentOptions *DeleteInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteInstanceClusterNetworkAttachmentWithContext(context.Background(), deleteInstanceClusterNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListDedicatedHostDisksWithContext is an alternate form of the ListDedicatedHostDisks method which supports a Context parameter -func (vpc *VpcV1) ListDedicatedHostDisksWithContext(ctx context.Context, listDedicatedHostDisksOptions *ListDedicatedHostDisksOptions) (result *DedicatedHostDiskCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listDedicatedHostDisksOptions, "listDedicatedHostDisksOptions cannot be nil") +// DeleteInstanceClusterNetworkAttachmentWithContext is an alternate form of the DeleteInstanceClusterNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) DeleteInstanceClusterNetworkAttachmentWithContext(ctx context.Context, deleteInstanceClusterNetworkAttachmentOptions *DeleteInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteInstanceClusterNetworkAttachmentOptions, "deleteInstanceClusterNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listDedicatedHostDisksOptions, "listDedicatedHostDisksOptions") + err = core.ValidateStruct(deleteInstanceClusterNetworkAttachmentOptions, "deleteInstanceClusterNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "dedicated_host_id": *listDedicatedHostDisksOptions.DedicatedHostID, + "instance_id": *deleteInstanceClusterNetworkAttachmentOptions.InstanceID, + "id": *deleteInstanceClusterNetworkAttachmentOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{dedicated_host_id}/disks`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listDedicatedHostDisksOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceClusterNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListDedicatedHostDisks") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceClusterNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -12230,12 +12890,12 @@ func (vpc *VpcV1) ListDedicatedHostDisksWithContext(ctx context.Context, listDed var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_dedicated_host_disks", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_instance_cluster_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostDiskCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12246,47 +12906,47 @@ func (vpc *VpcV1) ListDedicatedHostDisksWithContext(ctx context.Context, listDed return } -// GetDedicatedHostDisk : Retrieve a dedicated host disk -// This request retrieves a single dedicated host disk specified by the identifier in the URL. -func (vpc *VpcV1) GetDedicatedHostDisk(getDedicatedHostDiskOptions *GetDedicatedHostDiskOptions) (result *DedicatedHostDisk, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetDedicatedHostDiskWithContext(context.Background(), getDedicatedHostDiskOptions) +// GetInstanceClusterNetworkAttachment : Retrieve an instance cluster network attachment +// This request retrieves a single instance cluster network attachment specified by the identifier in the URL. +func (vpc *VpcV1) GetInstanceClusterNetworkAttachment(getInstanceClusterNetworkAttachmentOptions *GetInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceClusterNetworkAttachmentWithContext(context.Background(), getInstanceClusterNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetDedicatedHostDiskWithContext is an alternate form of the GetDedicatedHostDisk method which supports a Context parameter -func (vpc *VpcV1) GetDedicatedHostDiskWithContext(ctx context.Context, getDedicatedHostDiskOptions *GetDedicatedHostDiskOptions) (result *DedicatedHostDisk, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getDedicatedHostDiskOptions, "getDedicatedHostDiskOptions cannot be nil") +// GetInstanceClusterNetworkAttachmentWithContext is an alternate form of the GetInstanceClusterNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) GetInstanceClusterNetworkAttachmentWithContext(ctx context.Context, getInstanceClusterNetworkAttachmentOptions *GetInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceClusterNetworkAttachmentOptions, "getInstanceClusterNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getDedicatedHostDiskOptions, "getDedicatedHostDiskOptions") + err = core.ValidateStruct(getInstanceClusterNetworkAttachmentOptions, "getInstanceClusterNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "dedicated_host_id": *getDedicatedHostDiskOptions.DedicatedHostID, - "id": *getDedicatedHostDiskOptions.ID, + "instance_id": *getInstanceClusterNetworkAttachmentOptions.InstanceID, + "id": *getInstanceClusterNetworkAttachmentOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{dedicated_host_id}/disks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getDedicatedHostDiskOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceClusterNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetDedicatedHostDisk") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceClusterNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -12303,12 +12963,12 @@ func (vpc *VpcV1) GetDedicatedHostDiskWithContext(ctx context.Context, getDedica var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_dedicated_host_disk", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_cluster_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostDisk) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12319,47 +12979,49 @@ func (vpc *VpcV1) GetDedicatedHostDiskWithContext(ctx context.Context, getDedica return } -// UpdateDedicatedHostDisk : Update a dedicated host disk -// This request updates the dedicated host disk with the information in a provided patch. -func (vpc *VpcV1) UpdateDedicatedHostDisk(updateDedicatedHostDiskOptions *UpdateDedicatedHostDiskOptions) (result *DedicatedHostDisk, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateDedicatedHostDiskWithContext(context.Background(), updateDedicatedHostDiskOptions) +// UpdateInstanceClusterNetworkAttachment : Update an instance cluster network attachment +// This request updates an instance cluster network attachment with the information provided in an instance network +// interface patch object. The instance cluster network attachment patch object is structured in the same way as a +// retrieved instance cluster network attachment and needs to contain only the information to be updated. +func (vpc *VpcV1) UpdateInstanceClusterNetworkAttachment(updateInstanceClusterNetworkAttachmentOptions *UpdateInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateInstanceClusterNetworkAttachmentWithContext(context.Background(), updateInstanceClusterNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateDedicatedHostDiskWithContext is an alternate form of the UpdateDedicatedHostDisk method which supports a Context parameter -func (vpc *VpcV1) UpdateDedicatedHostDiskWithContext(ctx context.Context, updateDedicatedHostDiskOptions *UpdateDedicatedHostDiskOptions) (result *DedicatedHostDisk, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateDedicatedHostDiskOptions, "updateDedicatedHostDiskOptions cannot be nil") +// UpdateInstanceClusterNetworkAttachmentWithContext is an alternate form of the UpdateInstanceClusterNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) UpdateInstanceClusterNetworkAttachmentWithContext(ctx context.Context, updateInstanceClusterNetworkAttachmentOptions *UpdateInstanceClusterNetworkAttachmentOptions) (result *InstanceClusterNetworkAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateInstanceClusterNetworkAttachmentOptions, "updateInstanceClusterNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateDedicatedHostDiskOptions, "updateDedicatedHostDiskOptions") + err = core.ValidateStruct(updateInstanceClusterNetworkAttachmentOptions, "updateInstanceClusterNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "dedicated_host_id": *updateDedicatedHostDiskOptions.DedicatedHostID, - "id": *updateDedicatedHostDiskOptions.ID, + "instance_id": *updateInstanceClusterNetworkAttachmentOptions.InstanceID, + "id": *updateInstanceClusterNetworkAttachmentOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{dedicated_host_id}/disks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/cluster_network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateDedicatedHostDiskOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceClusterNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateDedicatedHostDisk") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceClusterNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -12368,7 +13030,7 @@ func (vpc *VpcV1) UpdateDedicatedHostDiskWithContext(ctx context.Context, update builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateDedicatedHostDiskOptions.DedicatedHostDiskPatch) + _, err = builder.SetBodyContentJSON(updateInstanceClusterNetworkAttachmentOptions.InstanceClusterNetworkAttachmentPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -12383,12 +13045,12 @@ func (vpc *VpcV1) UpdateDedicatedHostDiskWithContext(ctx context.Context, update var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_dedicated_host_disk", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_instance_cluster_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHostDisk) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceClusterNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12399,111 +13061,212 @@ func (vpc *VpcV1) UpdateDedicatedHostDiskWithContext(ctx context.Context, update return } -// DeleteDedicatedHost : Delete a dedicated host -// This request deletes a dedicated host. This operation cannot be reversed. For this request to succeed, `instances` -// must be empty and `instance_placement_enabled` must be `false`. -func (vpc *VpcV1) DeleteDedicatedHost(deleteDedicatedHostOptions *DeleteDedicatedHostOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteDedicatedHostWithContext(context.Background(), deleteDedicatedHostOptions) +// CreateInstanceConsoleAccessToken : Create a console access token for an instance +// This request creates a new single-use console access token for an instance. All console configuration is provided at +// token create time, and the token is subsequently used in the `access_token` query parameter for the WebSocket +// request. The access token is only valid for a short period of time, and a maximum of one token is valid for a given +// instance at a time. +func (vpc *VpcV1) CreateInstanceConsoleAccessToken(createInstanceConsoleAccessTokenOptions *CreateInstanceConsoleAccessTokenOptions) (result *InstanceConsoleAccessToken, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateInstanceConsoleAccessTokenWithContext(context.Background(), createInstanceConsoleAccessTokenOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteDedicatedHostWithContext is an alternate form of the DeleteDedicatedHost method which supports a Context parameter -func (vpc *VpcV1) DeleteDedicatedHostWithContext(ctx context.Context, deleteDedicatedHostOptions *DeleteDedicatedHostOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteDedicatedHostOptions, "deleteDedicatedHostOptions cannot be nil") +// CreateInstanceConsoleAccessTokenWithContext is an alternate form of the CreateInstanceConsoleAccessToken method which supports a Context parameter +func (vpc *VpcV1) CreateInstanceConsoleAccessTokenWithContext(ctx context.Context, createInstanceConsoleAccessTokenOptions *CreateInstanceConsoleAccessTokenOptions) (result *InstanceConsoleAccessToken, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createInstanceConsoleAccessTokenOptions, "createInstanceConsoleAccessTokenOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteDedicatedHostOptions, "deleteDedicatedHostOptions") + err = core.ValidateStruct(createInstanceConsoleAccessTokenOptions, "createInstanceConsoleAccessTokenOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteDedicatedHostOptions.ID, + "instance_id": *createInstanceConsoleAccessTokenOptions.InstanceID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/console_access_token`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteDedicatedHostOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceConsoleAccessToken") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteDedicatedHost") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceConsoleAccessTokenOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createInstanceConsoleAccessTokenOptions.ConsoleType != nil { + body["console_type"] = createInstanceConsoleAccessTokenOptions.ConsoleType + } + if createInstanceConsoleAccessTokenOptions.Force != nil { + body["force"] = createInstanceConsoleAccessTokenOptions.Force + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_dedicated_host", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_instance_console_access_token", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - - return -} - -// GetDedicatedHost : Retrieve a dedicated host -// This request retrieves a single dedicated host specified by the identifiers in the URL. -func (vpc *VpcV1) GetDedicatedHost(getDedicatedHostOptions *GetDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetDedicatedHostWithContext(context.Background(), getDedicatedHostOptions) + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceConsoleAccessToken) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// ListInstanceDisks : List disks on an instance +// This request lists disks on an instance. A disk is a block device that is locally attached to the instance's +// physical host and is also referred to as instance storage. By default, the listed disks are sorted by their +// `created_at` property values, with the newest disk first. +func (vpc *VpcV1) ListInstanceDisks(listInstanceDisksOptions *ListInstanceDisksOptions) (result *InstanceDiskCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceDisksWithContext(context.Background(), listInstanceDisksOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetDedicatedHostWithContext is an alternate form of the GetDedicatedHost method which supports a Context parameter -func (vpc *VpcV1) GetDedicatedHostWithContext(ctx context.Context, getDedicatedHostOptions *GetDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getDedicatedHostOptions, "getDedicatedHostOptions cannot be nil") +// ListInstanceDisksWithContext is an alternate form of the ListInstanceDisks method which supports a Context parameter +func (vpc *VpcV1) ListInstanceDisksWithContext(ctx context.Context, listInstanceDisksOptions *ListInstanceDisksOptions) (result *InstanceDiskCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listInstanceDisksOptions, "listInstanceDisksOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getDedicatedHostOptions, "getDedicatedHostOptions") + err = core.ValidateStruct(listInstanceDisksOptions, "listInstanceDisksOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getDedicatedHostOptions.ID, + "instance_id": *listInstanceDisksOptions.InstanceID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/disks`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getDedicatedHostOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceDisks") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetDedicatedHost") + for headerName, headerValue := range listInstanceDisksOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "list_instance_disks", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceDiskCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// GetInstanceDisk : Retrieve an instance disk +// This request retrieves a single instance disk specified by the identifier in the URL. +func (vpc *VpcV1) GetInstanceDisk(getInstanceDiskOptions *GetInstanceDiskOptions) (result *InstanceDisk, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceDiskWithContext(context.Background(), getInstanceDiskOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetInstanceDiskWithContext is an alternate form of the GetInstanceDisk method which supports a Context parameter +func (vpc *VpcV1) GetInstanceDiskWithContext(ctx context.Context, getInstanceDiskOptions *GetInstanceDiskOptions) (result *InstanceDisk, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceDiskOptions, "getInstanceDiskOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getInstanceDiskOptions, "getInstanceDiskOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "instance_id": *getInstanceDiskOptions.InstanceID, + "id": *getInstanceDiskOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/disks/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceDisk") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range getInstanceDiskOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) @@ -12518,12 +13281,12 @@ func (vpc *VpcV1) GetDedicatedHostWithContext(ctx context.Context, getDedicatedH var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_dedicated_host", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_disk", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHost) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceDisk) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12534,48 +13297,47 @@ func (vpc *VpcV1) GetDedicatedHostWithContext(ctx context.Context, getDedicatedH return } -// UpdateDedicatedHost : Update a dedicated host -// This request updates a dedicated host with the information in a provided dedicated host patch. The dedicated host -// patch object is structured in the same way as a retrieved dedicated host and contains only the information to be -// updated. -func (vpc *VpcV1) UpdateDedicatedHost(updateDedicatedHostOptions *UpdateDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateDedicatedHostWithContext(context.Background(), updateDedicatedHostOptions) +// UpdateInstanceDisk : Update an instance disk +// This request updates the instance disk with the information in a provided patch. +func (vpc *VpcV1) UpdateInstanceDisk(updateInstanceDiskOptions *UpdateInstanceDiskOptions) (result *InstanceDisk, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateInstanceDiskWithContext(context.Background(), updateInstanceDiskOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateDedicatedHostWithContext is an alternate form of the UpdateDedicatedHost method which supports a Context parameter -func (vpc *VpcV1) UpdateDedicatedHostWithContext(ctx context.Context, updateDedicatedHostOptions *UpdateDedicatedHostOptions) (result *DedicatedHost, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateDedicatedHostOptions, "updateDedicatedHostOptions cannot be nil") +// UpdateInstanceDiskWithContext is an alternate form of the UpdateInstanceDisk method which supports a Context parameter +func (vpc *VpcV1) UpdateInstanceDiskWithContext(ctx context.Context, updateInstanceDiskOptions *UpdateInstanceDiskOptions) (result *InstanceDisk, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateInstanceDiskOptions, "updateInstanceDiskOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateDedicatedHostOptions, "updateDedicatedHostOptions") + err = core.ValidateStruct(updateInstanceDiskOptions, "updateInstanceDiskOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateDedicatedHostOptions.ID, + "instance_id": *updateInstanceDiskOptions.InstanceID, + "id": *updateInstanceDiskOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/dedicated_hosts/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/disks/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateDedicatedHostOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceDisk") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateDedicatedHost") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceDiskOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -12584,7 +13346,7 @@ func (vpc *VpcV1) UpdateDedicatedHostWithContext(ctx context.Context, updateDedi builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateDedicatedHostOptions.DedicatedHostPatch) + _, err = builder.SetBodyContentJSON(updateInstanceDiskOptions.InstanceDiskPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -12599,12 +13361,12 @@ func (vpc *VpcV1) UpdateDedicatedHostWithContext(ctx context.Context, updateDedi var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_dedicated_host", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_instance_disk", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDedicatedHost) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceDisk) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12615,49 +13377,57 @@ func (vpc *VpcV1) UpdateDedicatedHostWithContext(ctx context.Context, updateDedi return } -// ListPlacementGroups : List placement groups -// This request lists placement groups in the region. -func (vpc *VpcV1) ListPlacementGroups(listPlacementGroupsOptions *ListPlacementGroupsOptions) (result *PlacementGroupCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListPlacementGroupsWithContext(context.Background(), listPlacementGroupsOptions) +// ListInstanceNetworkAttachments : List network attachments on an instance +// This request lists network attachments on an instance. A network attachment represents a device on the instance to +// which a virtual network interface is attached. +// +// The network attachments will be sorted by their `created_at` property values, with newest network attachments first. +// Network attachments with identical `created_at` property values will in turn be sorted by ascending `name` property +// values. +func (vpc *VpcV1) ListInstanceNetworkAttachments(listInstanceNetworkAttachmentsOptions *ListInstanceNetworkAttachmentsOptions) (result *InstanceNetworkAttachmentCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceNetworkAttachmentsWithContext(context.Background(), listInstanceNetworkAttachmentsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListPlacementGroupsWithContext is an alternate form of the ListPlacementGroups method which supports a Context parameter -func (vpc *VpcV1) ListPlacementGroupsWithContext(ctx context.Context, listPlacementGroupsOptions *ListPlacementGroupsOptions) (result *PlacementGroupCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listPlacementGroupsOptions, "listPlacementGroupsOptions") +// ListInstanceNetworkAttachmentsWithContext is an alternate form of the ListInstanceNetworkAttachments method which supports a Context parameter +func (vpc *VpcV1) ListInstanceNetworkAttachmentsWithContext(ctx context.Context, listInstanceNetworkAttachmentsOptions *ListInstanceNetworkAttachmentsOptions) (result *InstanceNetworkAttachmentCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listInstanceNetworkAttachmentsOptions, "listInstanceNetworkAttachmentsOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listInstanceNetworkAttachmentsOptions, "listInstanceNetworkAttachmentsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "instance_id": *listInstanceNetworkAttachmentsOptions.InstanceID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listPlacementGroupsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceNetworkAttachments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPlacementGroups") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceNetworkAttachmentsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listPlacementGroupsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listPlacementGroupsOptions.Start)) - } - if listPlacementGroupsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listPlacementGroupsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -12668,12 +13438,12 @@ func (vpc *VpcV1) ListPlacementGroupsWithContext(ctx context.Context, listPlacem var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_placement_groups", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_instance_network_attachments", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPlacementGroupCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceNetworkAttachmentCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12684,42 +13454,48 @@ func (vpc *VpcV1) ListPlacementGroupsWithContext(ctx context.Context, listPlacem return } -// CreatePlacementGroup : Create a placement group -// This request creates a new placement group. -func (vpc *VpcV1) CreatePlacementGroup(createPlacementGroupOptions *CreatePlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreatePlacementGroupWithContext(context.Background(), createPlacementGroupOptions) +// CreateInstanceNetworkAttachment : Create a network attachment on an instance +// This request creates a new instance network attachment from an instance network attachment prototype object. The +// prototype object is structured in the same way as a retrieved instance network attachment, and contains the +// information necessary to create the new instance network attachment. +func (vpc *VpcV1) CreateInstanceNetworkAttachment(createInstanceNetworkAttachmentOptions *CreateInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateInstanceNetworkAttachmentWithContext(context.Background(), createInstanceNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreatePlacementGroupWithContext is an alternate form of the CreatePlacementGroup method which supports a Context parameter -func (vpc *VpcV1) CreatePlacementGroupWithContext(ctx context.Context, createPlacementGroupOptions *CreatePlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createPlacementGroupOptions, "createPlacementGroupOptions cannot be nil") +// CreateInstanceNetworkAttachmentWithContext is an alternate form of the CreateInstanceNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) CreateInstanceNetworkAttachmentWithContext(ctx context.Context, createInstanceNetworkAttachmentOptions *CreateInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createInstanceNetworkAttachmentOptions, "createInstanceNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createPlacementGroupOptions, "createPlacementGroupOptions") + err = core.ValidateStruct(createInstanceNetworkAttachmentOptions, "createInstanceNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "instance_id": *createInstanceNetworkAttachmentOptions.InstanceID, + } + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createPlacementGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePlacementGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -12729,14 +13505,11 @@ func (vpc *VpcV1) CreatePlacementGroupWithContext(ctx context.Context, createPla builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createPlacementGroupOptions.Strategy != nil { - body["strategy"] = createPlacementGroupOptions.Strategy - } - if createPlacementGroupOptions.Name != nil { - body["name"] = createPlacementGroupOptions.Name + if createInstanceNetworkAttachmentOptions.VirtualNetworkInterface != nil { + body["virtual_network_interface"] = createInstanceNetworkAttachmentOptions.VirtualNetworkInterface } - if createPlacementGroupOptions.ResourceGroup != nil { - body["resource_group"] = createPlacementGroupOptions.ResourceGroup + if createInstanceNetworkAttachmentOptions.Name != nil { + body["name"] = createInstanceNetworkAttachmentOptions.Name } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -12753,12 +13526,12 @@ func (vpc *VpcV1) CreatePlacementGroupWithContext(ctx context.Context, createPla var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_placement_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_instance_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPlacementGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12769,47 +13542,50 @@ func (vpc *VpcV1) CreatePlacementGroupWithContext(ctx context.Context, createPla return } -// DeletePlacementGroup : Delete a placement group -// This request deletes a placement group. This operation cannot be reversed. For this request to succeed, the placement -// group must not be associated with an instance. -func (vpc *VpcV1) DeletePlacementGroup(deletePlacementGroupOptions *DeletePlacementGroupOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeletePlacementGroupWithContext(context.Background(), deletePlacementGroupOptions) +// DeleteInstanceNetworkAttachment : Delete an instance network attachment +// This request deletes an instance network attachment. This operation cannot be reversed. Any floating IPs associated +// with the instance network attachment are implicitly disassociated. All flow log collectors with `auto_delete` set to +// `true` targeting the instance network attachment are automatically deleted. The primary instance network attachment +// is not allowed to be deleted. +func (vpc *VpcV1) DeleteInstanceNetworkAttachment(deleteInstanceNetworkAttachmentOptions *DeleteInstanceNetworkAttachmentOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteInstanceNetworkAttachmentWithContext(context.Background(), deleteInstanceNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeletePlacementGroupWithContext is an alternate form of the DeletePlacementGroup method which supports a Context parameter -func (vpc *VpcV1) DeletePlacementGroupWithContext(ctx context.Context, deletePlacementGroupOptions *DeletePlacementGroupOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deletePlacementGroupOptions, "deletePlacementGroupOptions cannot be nil") +// DeleteInstanceNetworkAttachmentWithContext is an alternate form of the DeleteInstanceNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) DeleteInstanceNetworkAttachmentWithContext(ctx context.Context, deleteInstanceNetworkAttachmentOptions *DeleteInstanceNetworkAttachmentOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteInstanceNetworkAttachmentOptions, "deleteInstanceNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deletePlacementGroupOptions, "deletePlacementGroupOptions") + err = core.ValidateStruct(deleteInstanceNetworkAttachmentOptions, "deleteInstanceNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deletePlacementGroupOptions.ID, + "instance_id": *deleteInstanceNetworkAttachmentOptions.InstanceID, + "id": *deleteInstanceNetworkAttachmentOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deletePlacementGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePlacementGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -12824,7 +13600,7 @@ func (vpc *VpcV1) DeletePlacementGroupWithContext(ctx context.Context, deletePla response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_placement_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_instance_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -12832,46 +13608,47 @@ func (vpc *VpcV1) DeletePlacementGroupWithContext(ctx context.Context, deletePla return } -// GetPlacementGroup : Retrieve a placement group -// This request retrieves a single placement group specified by identifier in the URL. -func (vpc *VpcV1) GetPlacementGroup(getPlacementGroupOptions *GetPlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetPlacementGroupWithContext(context.Background(), getPlacementGroupOptions) +// GetInstanceNetworkAttachment : Retrieve an instance network attachment +// This request retrieves a single instance network attachment specified by the identifier in the URL. +func (vpc *VpcV1) GetInstanceNetworkAttachment(getInstanceNetworkAttachmentOptions *GetInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceNetworkAttachmentWithContext(context.Background(), getInstanceNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetPlacementGroupWithContext is an alternate form of the GetPlacementGroup method which supports a Context parameter -func (vpc *VpcV1) GetPlacementGroupWithContext(ctx context.Context, getPlacementGroupOptions *GetPlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getPlacementGroupOptions, "getPlacementGroupOptions cannot be nil") +// GetInstanceNetworkAttachmentWithContext is an alternate form of the GetInstanceNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) GetInstanceNetworkAttachmentWithContext(ctx context.Context, getInstanceNetworkAttachmentOptions *GetInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceNetworkAttachmentOptions, "getInstanceNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getPlacementGroupOptions, "getPlacementGroupOptions") + err = core.ValidateStruct(getInstanceNetworkAttachmentOptions, "getInstanceNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getPlacementGroupOptions.ID, + "instance_id": *getInstanceNetworkAttachmentOptions.InstanceID, + "id": *getInstanceNetworkAttachmentOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getPlacementGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPlacementGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -12888,12 +13665,12 @@ func (vpc *VpcV1) GetPlacementGroupWithContext(ctx context.Context, getPlacement var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_placement_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPlacementGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12904,47 +13681,49 @@ func (vpc *VpcV1) GetPlacementGroupWithContext(ctx context.Context, getPlacement return } -// UpdatePlacementGroup : Update a placement group -// This request updates a placement group with the information provided placement group patch. The placement group patch -// object is structured in the same way as a retrieved placement group and contains only the information to be updated. -func (vpc *VpcV1) UpdatePlacementGroup(updatePlacementGroupOptions *UpdatePlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdatePlacementGroupWithContext(context.Background(), updatePlacementGroupOptions) +// UpdateInstanceNetworkAttachment : Update an instance network attachment +// This request updates an instance network attachment with the information provided in an instance network interface +// patch object. The instance network attachment patch object is structured in the same way as a retrieved instance +// network attachment and needs to contain only the information to be updated. +func (vpc *VpcV1) UpdateInstanceNetworkAttachment(updateInstanceNetworkAttachmentOptions *UpdateInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateInstanceNetworkAttachmentWithContext(context.Background(), updateInstanceNetworkAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdatePlacementGroupWithContext is an alternate form of the UpdatePlacementGroup method which supports a Context parameter -func (vpc *VpcV1) UpdatePlacementGroupWithContext(ctx context.Context, updatePlacementGroupOptions *UpdatePlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updatePlacementGroupOptions, "updatePlacementGroupOptions cannot be nil") +// UpdateInstanceNetworkAttachmentWithContext is an alternate form of the UpdateInstanceNetworkAttachment method which supports a Context parameter +func (vpc *VpcV1) UpdateInstanceNetworkAttachmentWithContext(ctx context.Context, updateInstanceNetworkAttachmentOptions *UpdateInstanceNetworkAttachmentOptions) (result *InstanceNetworkAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateInstanceNetworkAttachmentOptions, "updateInstanceNetworkAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updatePlacementGroupOptions, "updatePlacementGroupOptions") + err = core.ValidateStruct(updateInstanceNetworkAttachmentOptions, "updateInstanceNetworkAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updatePlacementGroupOptions.ID, + "instance_id": *updateInstanceNetworkAttachmentOptions.InstanceID, + "id": *updateInstanceNetworkAttachmentOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updatePlacementGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceNetworkAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePlacementGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceNetworkAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -12953,7 +13732,7 @@ func (vpc *VpcV1) UpdatePlacementGroupWithContext(ctx context.Context, updatePla builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updatePlacementGroupOptions.PlacementGroupPatch) + _, err = builder.SetBodyContentJSON(updateInstanceNetworkAttachmentOptions.InstanceNetworkAttachmentPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -12968,12 +13747,12 @@ func (vpc *VpcV1) UpdatePlacementGroupWithContext(ctx context.Context, updatePla var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_placement_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_instance_network_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPlacementGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalInstanceNetworkAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -12984,51 +13763,59 @@ func (vpc *VpcV1) UpdatePlacementGroupWithContext(ctx context.Context, updatePla return } -// ListBareMetalServerProfiles : List bare metal server profiles -// This request lists [bare metal server profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-bare-metal-servers-profile) -// available in the region. A bare metal server profile specifies the performance characteristics and pricing model for -// a bare metal server. -func (vpc *VpcV1) ListBareMetalServerProfiles(listBareMetalServerProfilesOptions *ListBareMetalServerProfilesOptions) (result *BareMetalServerProfileCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBareMetalServerProfilesWithContext(context.Background(), listBareMetalServerProfilesOptions) +// ListInstanceNetworkInterfaces : List network interfaces on an instance +// This request lists network interfaces on an instance. An instance network interface is an abstract representation of +// a network device and attaches an instance to a single subnet. Each network interface on an instance can attach to any +// subnet in the zone, including subnets that are already attached to the instance. Multiple network interfaces on the +// instance may also attach to the same subnet. +// +// If this instance has network attachments, each returned network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface. +func (vpc *VpcV1) ListInstanceNetworkInterfaces(listInstanceNetworkInterfacesOptions *ListInstanceNetworkInterfacesOptions) (result *NetworkInterfaceUnpaginatedCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceNetworkInterfacesWithContext(context.Background(), listInstanceNetworkInterfacesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBareMetalServerProfilesWithContext is an alternate form of the ListBareMetalServerProfiles method which supports a Context parameter -func (vpc *VpcV1) ListBareMetalServerProfilesWithContext(ctx context.Context, listBareMetalServerProfilesOptions *ListBareMetalServerProfilesOptions) (result *BareMetalServerProfileCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listBareMetalServerProfilesOptions, "listBareMetalServerProfilesOptions") +// ListInstanceNetworkInterfacesWithContext is an alternate form of the ListInstanceNetworkInterfaces method which supports a Context parameter +func (vpc *VpcV1) ListInstanceNetworkInterfacesWithContext(ctx context.Context, listInstanceNetworkInterfacesOptions *ListInstanceNetworkInterfacesOptions) (result *NetworkInterfaceUnpaginatedCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listInstanceNetworkInterfacesOptions, "listInstanceNetworkInterfacesOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listInstanceNetworkInterfacesOptions, "listInstanceNetworkInterfacesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "instance_id": *listInstanceNetworkInterfacesOptions.InstanceID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_server/profiles`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBareMetalServerProfilesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceNetworkInterfaces") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerProfiles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceNetworkInterfacesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listBareMetalServerProfilesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listBareMetalServerProfilesOptions.Start)) - } - if listBareMetalServerProfilesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listBareMetalServerProfilesOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -13039,12 +13826,12 @@ func (vpc *VpcV1) ListBareMetalServerProfilesWithContext(ctx context.Context, li var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_bare_metal_server_profiles", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_instance_network_interfaces", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerProfileCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkInterfaceUnpaginatedCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13055,53 +13842,83 @@ func (vpc *VpcV1) ListBareMetalServerProfilesWithContext(ctx context.Context, li return } -// GetBareMetalServerProfile : Retrieve a bare metal server profile -// This request retrieves a single bare metal server profile specified by the name in the URL. -func (vpc *VpcV1) GetBareMetalServerProfile(getBareMetalServerProfileOptions *GetBareMetalServerProfileOptions) (result *BareMetalServerProfile, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBareMetalServerProfileWithContext(context.Background(), getBareMetalServerProfileOptions) +// CreateInstanceNetworkInterface : Create a network interface on an instance +// This request creates a new instance network interface from an instance network interface prototype object. The +// prototype object is structured in the same way as a retrieved instance network interface, and contains the +// information necessary to create the new instance network interface. Any subnet in the instance's VPC may be +// specified. Addresses on the instance network interface must be within the specified subnet's CIDR blocks. +// +// If this instance has network attachments, each network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface, and new network interfaces are not allowed to be created. +func (vpc *VpcV1) CreateInstanceNetworkInterface(createInstanceNetworkInterfaceOptions *CreateInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateInstanceNetworkInterfaceWithContext(context.Background(), createInstanceNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBareMetalServerProfileWithContext is an alternate form of the GetBareMetalServerProfile method which supports a Context parameter -func (vpc *VpcV1) GetBareMetalServerProfileWithContext(ctx context.Context, getBareMetalServerProfileOptions *GetBareMetalServerProfileOptions) (result *BareMetalServerProfile, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBareMetalServerProfileOptions, "getBareMetalServerProfileOptions cannot be nil") +// CreateInstanceNetworkInterfaceWithContext is an alternate form of the CreateInstanceNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) CreateInstanceNetworkInterfaceWithContext(ctx context.Context, createInstanceNetworkInterfaceOptions *CreateInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createInstanceNetworkInterfaceOptions, "createInstanceNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getBareMetalServerProfileOptions, "getBareMetalServerProfileOptions") + err = core.ValidateStruct(createInstanceNetworkInterfaceOptions, "createInstanceNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "name": *getBareMetalServerProfileOptions.Name, + "instance_id": *createInstanceNetworkInterfaceOptions.InstanceID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_server/profiles/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBareMetalServerProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createInstanceNetworkInterfaceOptions.Subnet != nil { + body["subnet"] = createInstanceNetworkInterfaceOptions.Subnet + } + if createInstanceNetworkInterfaceOptions.AllowIPSpoofing != nil { + body["allow_ip_spoofing"] = createInstanceNetworkInterfaceOptions.AllowIPSpoofing + } + if createInstanceNetworkInterfaceOptions.Name != nil { + body["name"] = createInstanceNetworkInterfaceOptions.Name + } + if createInstanceNetworkInterfaceOptions.PrimaryIP != nil { + body["primary_ip"] = createInstanceNetworkInterfaceOptions.PrimaryIP + } + if createInstanceNetworkInterfaceOptions.SecurityGroups != nil { + body["security_groups"] = createInstanceNetworkInterfaceOptions.SecurityGroups + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -13111,12 +13928,12 @@ func (vpc *VpcV1) GetBareMetalServerProfileWithContext(ctx context.Context, getB var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_bare_metal_server_profile", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_instance_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerProfile) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13127,73 +13944,59 @@ func (vpc *VpcV1) GetBareMetalServerProfileWithContext(ctx context.Context, getB return } -// ListBareMetalServers : List bare metal servers -// This request lists bare metal servers in the region. -func (vpc *VpcV1) ListBareMetalServers(listBareMetalServersOptions *ListBareMetalServersOptions) (result *BareMetalServerCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBareMetalServersWithContext(context.Background(), listBareMetalServersOptions) +// DeleteInstanceNetworkInterface : Delete an instance network interface +// This request deletes an instance network interface. This operation cannot be reversed. Any floating IPs associated +// with the instance network interface are implicitly disassociated. All flow log collectors with `auto_delete` set to +// `true` targeting the instance network interface are automatically deleted. The primary instance network interface is +// not allowed to be deleted. +// +// If this instance has network attachments, this network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface, and is not allowed to be deleted. +func (vpc *VpcV1) DeleteInstanceNetworkInterface(deleteInstanceNetworkInterfaceOptions *DeleteInstanceNetworkInterfaceOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteInstanceNetworkInterfaceWithContext(context.Background(), deleteInstanceNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBareMetalServersWithContext is an alternate form of the ListBareMetalServers method which supports a Context parameter -func (vpc *VpcV1) ListBareMetalServersWithContext(ctx context.Context, listBareMetalServersOptions *ListBareMetalServersOptions) (result *BareMetalServerCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listBareMetalServersOptions, "listBareMetalServersOptions") +// DeleteInstanceNetworkInterfaceWithContext is an alternate form of the DeleteInstanceNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) DeleteInstanceNetworkInterfaceWithContext(ctx context.Context, deleteInstanceNetworkInterfaceOptions *DeleteInstanceNetworkInterfaceOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteInstanceNetworkInterfaceOptions, "deleteInstanceNetworkInterfaceOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteInstanceNetworkInterfaceOptions, "deleteInstanceNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "instance_id": *deleteInstanceNetworkInterfaceOptions.InstanceID, + "id": *deleteInstanceNetworkInterfaceOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBareMetalServersOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServers") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listBareMetalServersOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listBareMetalServersOptions.Start)) - } - if listBareMetalServersOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listBareMetalServersOptions.Limit)) - } - if listBareMetalServersOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listBareMetalServersOptions.ResourceGroupID)) - } - if listBareMetalServersOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listBareMetalServersOptions.Name)) - } - if listBareMetalServersOptions.ReservationID != nil { - builder.AddQuery("reservation.id", fmt.Sprint(*listBareMetalServersOptions.ReservationID)) - } - if listBareMetalServersOptions.ReservationCRN != nil { - builder.AddQuery("reservation.crn", fmt.Sprint(*listBareMetalServersOptions.ReservationCRN)) - } - if listBareMetalServersOptions.ReservationName != nil { - builder.AddQuery("reservation.name", fmt.Sprint(*listBareMetalServersOptions.ReservationName)) - } - if listBareMetalServersOptions.VPCID != nil { - builder.AddQuery("vpc.id", fmt.Sprint(*listBareMetalServersOptions.VPCID)) - } - if listBareMetalServersOptions.VPCCRN != nil { - builder.AddQuery("vpc.crn", fmt.Sprint(*listBareMetalServersOptions.VPCCRN)) - } - if listBareMetalServersOptions.VPCName != nil { - builder.AddQuery("vpc.name", fmt.Sprint(*listBareMetalServersOptions.VPCName)) - } request, err := builder.Build() if err != nil { @@ -13201,77 +14004,68 @@ func (vpc *VpcV1) ListBareMetalServersWithContext(ctx context.Context, listBareM return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_bare_metal_servers", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_instance_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateBareMetalServer : Create a bare metal server -// This request provisions a new bare metal server from a prototype object. The prototype object is structured in the -// same way as a retrieved bare metal server, and contains the information necessary to provision the new bare metal -// server. The bare metal server is automatically started. -func (vpc *VpcV1) CreateBareMetalServer(createBareMetalServerOptions *CreateBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateBareMetalServerWithContext(context.Background(), createBareMetalServerOptions) +// GetInstanceNetworkInterface : Retrieve an instance network interface +// This request retrieves a single instance network interface specified by the identifier in the URL. +// +// If this instance has network attachments, the retrieved network interface is a +// [read-only representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its +// corresponding network attachment and its attached virtual network interface. +func (vpc *VpcV1) GetInstanceNetworkInterface(getInstanceNetworkInterfaceOptions *GetInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceNetworkInterfaceWithContext(context.Background(), getInstanceNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateBareMetalServerWithContext is an alternate form of the CreateBareMetalServer method which supports a Context parameter -func (vpc *VpcV1) CreateBareMetalServerWithContext(ctx context.Context, createBareMetalServerOptions *CreateBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createBareMetalServerOptions, "createBareMetalServerOptions cannot be nil") +// GetInstanceNetworkInterfaceWithContext is an alternate form of the GetInstanceNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) GetInstanceNetworkInterfaceWithContext(ctx context.Context, getInstanceNetworkInterfaceOptions *GetInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceNetworkInterfaceOptions, "getInstanceNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createBareMetalServerOptions, "createBareMetalServerOptions") + err = core.ValidateStruct(getInstanceNetworkInterfaceOptions, "getInstanceNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "instance_id": *getInstanceNetworkInterfaceOptions.InstanceID, + "id": *getInstanceNetworkInterfaceOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createBareMetalServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBareMetalServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createBareMetalServerOptions.BareMetalServerPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -13281,12 +14075,12 @@ func (vpc *VpcV1) CreateBareMetalServerWithContext(ctx context.Context, createBa var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_bare_metal_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServer) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13297,66 +14091,62 @@ func (vpc *VpcV1) CreateBareMetalServerWithContext(ctx context.Context, createBa return } -// CreateBareMetalServerConsoleAccessToken : Create a console access token for a bare metal server -// This request creates a new single-use console access token for a bare metal server. All console configuration is -// provided at token create time, and the token is subsequently used in the `access_token` query parameter for the -// WebSocket request. The access token is only valid for a short period of time, and a maximum of one token is valid -// for a given bare metal server at a time. For this request to succeed, the server must have a `status` of `stopped`, -// `starting`, or `running`. -func (vpc *VpcV1) CreateBareMetalServerConsoleAccessToken(createBareMetalServerConsoleAccessTokenOptions *CreateBareMetalServerConsoleAccessTokenOptions) (result *BareMetalServerConsoleAccessToken, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateBareMetalServerConsoleAccessTokenWithContext(context.Background(), createBareMetalServerConsoleAccessTokenOptions) +// UpdateInstanceNetworkInterface : Update an instance network interface +// This request updates an instance network interface with the information provided in an instance network interface +// patch object. The instance network interface patch object is structured in the same way as a retrieved instance +// network interface and needs to contain only the information to be updated. +// +// If this instance has network attachments, this network interface is a [read-only +// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network +// attachment and its attached virtual network interface, and is not allowed to be updated. +func (vpc *VpcV1) UpdateInstanceNetworkInterface(updateInstanceNetworkInterfaceOptions *UpdateInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateInstanceNetworkInterfaceWithContext(context.Background(), updateInstanceNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateBareMetalServerConsoleAccessTokenWithContext is an alternate form of the CreateBareMetalServerConsoleAccessToken method which supports a Context parameter -func (vpc *VpcV1) CreateBareMetalServerConsoleAccessTokenWithContext(ctx context.Context, createBareMetalServerConsoleAccessTokenOptions *CreateBareMetalServerConsoleAccessTokenOptions) (result *BareMetalServerConsoleAccessToken, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createBareMetalServerConsoleAccessTokenOptions, "createBareMetalServerConsoleAccessTokenOptions cannot be nil") +// UpdateInstanceNetworkInterfaceWithContext is an alternate form of the UpdateInstanceNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) UpdateInstanceNetworkInterfaceWithContext(ctx context.Context, updateInstanceNetworkInterfaceOptions *UpdateInstanceNetworkInterfaceOptions) (result *NetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateInstanceNetworkInterfaceOptions, "updateInstanceNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createBareMetalServerConsoleAccessTokenOptions, "createBareMetalServerConsoleAccessTokenOptions") + err = core.ValidateStruct(updateInstanceNetworkInterfaceOptions, "updateInstanceNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *createBareMetalServerConsoleAccessTokenOptions.BareMetalServerID, + "instance_id": *updateInstanceNetworkInterfaceOptions.InstanceID, + "id": *updateInstanceNetworkInterfaceOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/console_access_token`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createBareMetalServerConsoleAccessTokenOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBareMetalServerConsoleAccessToken") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createBareMetalServerConsoleAccessTokenOptions.ConsoleType != nil { - body["console_type"] = createBareMetalServerConsoleAccessTokenOptions.ConsoleType - } - if createBareMetalServerConsoleAccessTokenOptions.Force != nil { - body["force"] = createBareMetalServerConsoleAccessTokenOptions.Force - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(updateInstanceNetworkInterfaceOptions.NetworkInterfacePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -13371,12 +14161,12 @@ func (vpc *VpcV1) CreateBareMetalServerConsoleAccessTokenWithContext(ctx context var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_bare_metal_server_console_access_token", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_instance_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerConsoleAccessToken) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13387,47 +14177,47 @@ func (vpc *VpcV1) CreateBareMetalServerConsoleAccessTokenWithContext(ctx context return } -// ListBareMetalServerDisks : List disks on a bare metal server -// This request lists disks on a bare metal server. A disk is a block device that is locally attached to the physical -// server. By default, the listed disks are sorted by their `created_at` property values, with the newest disk first. -func (vpc *VpcV1) ListBareMetalServerDisks(listBareMetalServerDisksOptions *ListBareMetalServerDisksOptions) (result *BareMetalServerDiskCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBareMetalServerDisksWithContext(context.Background(), listBareMetalServerDisksOptions) +// ListInstanceNetworkInterfaceFloatingIps : List floating IPs associated with an instance network interface +// This request lists floating IPs associated with an instance network interface. +func (vpc *VpcV1) ListInstanceNetworkInterfaceFloatingIps(listInstanceNetworkInterfaceFloatingIpsOptions *ListInstanceNetworkInterfaceFloatingIpsOptions) (result *FloatingIPUnpaginatedCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceNetworkInterfaceFloatingIpsWithContext(context.Background(), listInstanceNetworkInterfaceFloatingIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBareMetalServerDisksWithContext is an alternate form of the ListBareMetalServerDisks method which supports a Context parameter -func (vpc *VpcV1) ListBareMetalServerDisksWithContext(ctx context.Context, listBareMetalServerDisksOptions *ListBareMetalServerDisksOptions) (result *BareMetalServerDiskCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listBareMetalServerDisksOptions, "listBareMetalServerDisksOptions cannot be nil") +// ListInstanceNetworkInterfaceFloatingIpsWithContext is an alternate form of the ListInstanceNetworkInterfaceFloatingIps method which supports a Context parameter +func (vpc *VpcV1) ListInstanceNetworkInterfaceFloatingIpsWithContext(ctx context.Context, listInstanceNetworkInterfaceFloatingIpsOptions *ListInstanceNetworkInterfaceFloatingIpsOptions) (result *FloatingIPUnpaginatedCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listInstanceNetworkInterfaceFloatingIpsOptions, "listInstanceNetworkInterfaceFloatingIpsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listBareMetalServerDisksOptions, "listBareMetalServerDisksOptions") + err = core.ValidateStruct(listInstanceNetworkInterfaceFloatingIpsOptions, "listInstanceNetworkInterfaceFloatingIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *listBareMetalServerDisksOptions.BareMetalServerID, + "instance_id": *listInstanceNetworkInterfaceFloatingIpsOptions.InstanceID, + "network_interface_id": *listInstanceNetworkInterfaceFloatingIpsOptions.NetworkInterfaceID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/disks`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/floating_ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBareMetalServerDisksOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceNetworkInterfaceFloatingIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerDisks") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceNetworkInterfaceFloatingIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -13444,12 +14234,12 @@ func (vpc *VpcV1) ListBareMetalServerDisksWithContext(ctx context.Context, listB var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_bare_metal_server_disks", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_instance_network_interface_floating_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerDiskCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPUnpaginatedCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13460,50 +14250,50 @@ func (vpc *VpcV1) ListBareMetalServerDisksWithContext(ctx context.Context, listB return } -// GetBareMetalServerDisk : Retrieve a bare metal server disk -// This request retrieves a single disk specified by the identifier in the URL. -func (vpc *VpcV1) GetBareMetalServerDisk(getBareMetalServerDiskOptions *GetBareMetalServerDiskOptions) (result *BareMetalServerDisk, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBareMetalServerDiskWithContext(context.Background(), getBareMetalServerDiskOptions) +// RemoveInstanceNetworkInterfaceFloatingIP : Disassociate a floating IP from an instance network interface +// This request disassociates the specified floating IP from the specified instance network interface. +func (vpc *VpcV1) RemoveInstanceNetworkInterfaceFloatingIP(removeInstanceNetworkInterfaceFloatingIPOptions *RemoveInstanceNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RemoveInstanceNetworkInterfaceFloatingIPWithContext(context.Background(), removeInstanceNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBareMetalServerDiskWithContext is an alternate form of the GetBareMetalServerDisk method which supports a Context parameter -func (vpc *VpcV1) GetBareMetalServerDiskWithContext(ctx context.Context, getBareMetalServerDiskOptions *GetBareMetalServerDiskOptions) (result *BareMetalServerDisk, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBareMetalServerDiskOptions, "getBareMetalServerDiskOptions cannot be nil") +// RemoveInstanceNetworkInterfaceFloatingIPWithContext is an alternate form of the RemoveInstanceNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) RemoveInstanceNetworkInterfaceFloatingIPWithContext(ctx context.Context, removeInstanceNetworkInterfaceFloatingIPOptions *RemoveInstanceNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(removeInstanceNetworkInterfaceFloatingIPOptions, "removeInstanceNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getBareMetalServerDiskOptions, "getBareMetalServerDiskOptions") + err = core.ValidateStruct(removeInstanceNetworkInterfaceFloatingIPOptions, "removeInstanceNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *getBareMetalServerDiskOptions.BareMetalServerID, - "id": *getBareMetalServerDiskOptions.ID, + "instance_id": *removeInstanceNetworkInterfaceFloatingIPOptions.InstanceID, + "network_interface_id": *removeInstanceNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, + "id": *removeInstanceNetworkInterfaceFloatingIPOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/disks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBareMetalServerDiskOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveInstanceNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerDisk") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range removeInstanceNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -13514,80 +14304,66 @@ func (vpc *VpcV1) GetBareMetalServerDiskWithContext(ctx context.Context, getBare return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_bare_metal_server_disk", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "remove_instance_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerDisk) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// UpdateBareMetalServerDisk : Update a bare metal server disk -// This request updates the bare metal server disk with the information in a provided patch. -func (vpc *VpcV1) UpdateBareMetalServerDisk(updateBareMetalServerDiskOptions *UpdateBareMetalServerDiskOptions) (result *BareMetalServerDisk, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateBareMetalServerDiskWithContext(context.Background(), updateBareMetalServerDiskOptions) +// GetInstanceNetworkInterfaceFloatingIP : Retrieve associated floating IP +// This request retrieves a specified floating IP address if it is associated with the instance network interface and +// instance specified in the URL. +func (vpc *VpcV1) GetInstanceNetworkInterfaceFloatingIP(getInstanceNetworkInterfaceFloatingIPOptions *GetInstanceNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceNetworkInterfaceFloatingIPWithContext(context.Background(), getInstanceNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateBareMetalServerDiskWithContext is an alternate form of the UpdateBareMetalServerDisk method which supports a Context parameter -func (vpc *VpcV1) UpdateBareMetalServerDiskWithContext(ctx context.Context, updateBareMetalServerDiskOptions *UpdateBareMetalServerDiskOptions) (result *BareMetalServerDisk, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateBareMetalServerDiskOptions, "updateBareMetalServerDiskOptions cannot be nil") +// GetInstanceNetworkInterfaceFloatingIPWithContext is an alternate form of the GetInstanceNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) GetInstanceNetworkInterfaceFloatingIPWithContext(ctx context.Context, getInstanceNetworkInterfaceFloatingIPOptions *GetInstanceNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceNetworkInterfaceFloatingIPOptions, "getInstanceNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateBareMetalServerDiskOptions, "updateBareMetalServerDiskOptions") + err = core.ValidateStruct(getInstanceNetworkInterfaceFloatingIPOptions, "getInstanceNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *updateBareMetalServerDiskOptions.BareMetalServerID, - "id": *updateBareMetalServerDiskOptions.ID, + "instance_id": *getInstanceNetworkInterfaceFloatingIPOptions.InstanceID, + "network_interface_id": *getInstanceNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, + "id": *getInstanceNetworkInterfaceFloatingIPOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/disks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateBareMetalServerDiskOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBareMetalServerDisk") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateBareMetalServerDiskOptions.BareMetalServerDiskPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -13597,12 +14373,12 @@ func (vpc *VpcV1) UpdateBareMetalServerDiskWithContext(ctx context.Context, upda var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_bare_metal_server_disk", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerDisk) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13613,65 +14389,61 @@ func (vpc *VpcV1) UpdateBareMetalServerDiskWithContext(ctx context.Context, upda return } -// ListBareMetalServerNetworkAttachments : List network attachments on a bare metal server -// This request lists network attachments on a bare metal server. A bare metal server network attachment is an abstract -// representation of a network device and attaches a bare metal server to a single subnet. Each network interface on a -// bare metal server can attach to any subnet in the zone, including subnets that are already attached to the bare metal -// server. +// AddInstanceNetworkInterfaceFloatingIP : Associate a floating IP with an instance network interface +// This request associates the specified floating IP with the specified instance network interface, replacing any +// existing association. // -// The network attachments will be sorted by their `created_at` property values, with newest network attachments first. -// Network attachments with identical `created_at` property values will in turn be sorted by ascending `name` property -// values. -func (vpc *VpcV1) ListBareMetalServerNetworkAttachments(listBareMetalServerNetworkAttachmentsOptions *ListBareMetalServerNetworkAttachmentsOptions) (result *BareMetalServerNetworkAttachmentCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBareMetalServerNetworkAttachmentsWithContext(context.Background(), listBareMetalServerNetworkAttachmentsOptions) +// The existing floating IP must: +// - not be required by another resource, such as a public gateway +// - be in the same `zone` as the instance +// +// A request body is not required, and if provided, is ignored. +func (vpc *VpcV1) AddInstanceNetworkInterfaceFloatingIP(addInstanceNetworkInterfaceFloatingIPOptions *AddInstanceNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.AddInstanceNetworkInterfaceFloatingIPWithContext(context.Background(), addInstanceNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBareMetalServerNetworkAttachmentsWithContext is an alternate form of the ListBareMetalServerNetworkAttachments method which supports a Context parameter -func (vpc *VpcV1) ListBareMetalServerNetworkAttachmentsWithContext(ctx context.Context, listBareMetalServerNetworkAttachmentsOptions *ListBareMetalServerNetworkAttachmentsOptions) (result *BareMetalServerNetworkAttachmentCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listBareMetalServerNetworkAttachmentsOptions, "listBareMetalServerNetworkAttachmentsOptions cannot be nil") +// AddInstanceNetworkInterfaceFloatingIPWithContext is an alternate form of the AddInstanceNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) AddInstanceNetworkInterfaceFloatingIPWithContext(ctx context.Context, addInstanceNetworkInterfaceFloatingIPOptions *AddInstanceNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(addInstanceNetworkInterfaceFloatingIPOptions, "addInstanceNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listBareMetalServerNetworkAttachmentsOptions, "listBareMetalServerNetworkAttachmentsOptions") + err = core.ValidateStruct(addInstanceNetworkInterfaceFloatingIPOptions, "addInstanceNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *listBareMetalServerNetworkAttachmentsOptions.BareMetalServerID, + "instance_id": *addInstanceNetworkInterfaceFloatingIPOptions.InstanceID, + "network_interface_id": *addInstanceNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, + "id": *addInstanceNetworkInterfaceFloatingIPOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBareMetalServerNetworkAttachmentsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddInstanceNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerNetworkAttachments") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range addInstanceNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listBareMetalServerNetworkAttachmentsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listBareMetalServerNetworkAttachmentsOptions.Start)) - } - if listBareMetalServerNetworkAttachmentsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listBareMetalServerNetworkAttachmentsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -13682,12 +14454,12 @@ func (vpc *VpcV1) ListBareMetalServerNetworkAttachmentsWithContext(ctx context.C var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_bare_metal_server_network_attachments", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "add_instance_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkAttachmentCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13698,60 +14470,61 @@ func (vpc *VpcV1) ListBareMetalServerNetworkAttachmentsWithContext(ctx context.C return } -// CreateBareMetalServerNetworkAttachment : Create a network attachment on a bare metal server -// This request creates a new bare metal server network attachment from a bare metal server network attachment prototype -// object. The prototype object is structured in the same way as a retrieved bare metal server network attachment, and -// contains the information necessary to create the new bare metal server network attachment. -func (vpc *VpcV1) CreateBareMetalServerNetworkAttachment(createBareMetalServerNetworkAttachmentOptions *CreateBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateBareMetalServerNetworkAttachmentWithContext(context.Background(), createBareMetalServerNetworkAttachmentOptions) +// ListInstanceNetworkInterfaceIps : List the primary reserved IP for an instance network interface +// This request lists the primary reserved IP for an instance network interface. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) ListInstanceNetworkInterfaceIps(listInstanceNetworkInterfaceIpsOptions *ListInstanceNetworkInterfaceIpsOptions) (result *ReservedIPCollectionInstanceNetworkInterfaceContext, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceNetworkInterfaceIpsWithContext(context.Background(), listInstanceNetworkInterfaceIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateBareMetalServerNetworkAttachmentWithContext is an alternate form of the CreateBareMetalServerNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) CreateBareMetalServerNetworkAttachmentWithContext(ctx context.Context, createBareMetalServerNetworkAttachmentOptions *CreateBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createBareMetalServerNetworkAttachmentOptions, "createBareMetalServerNetworkAttachmentOptions cannot be nil") +// ListInstanceNetworkInterfaceIpsWithContext is an alternate form of the ListInstanceNetworkInterfaceIps method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) ListInstanceNetworkInterfaceIpsWithContext(ctx context.Context, listInstanceNetworkInterfaceIpsOptions *ListInstanceNetworkInterfaceIpsOptions) (result *ReservedIPCollectionInstanceNetworkInterfaceContext, response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: ListInstanceNetworkInterfaceIps") + err = core.ValidateNotNil(listInstanceNetworkInterfaceIpsOptions, "listInstanceNetworkInterfaceIpsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createBareMetalServerNetworkAttachmentOptions, "createBareMetalServerNetworkAttachmentOptions") + err = core.ValidateStruct(listInstanceNetworkInterfaceIpsOptions, "listInstanceNetworkInterfaceIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *createBareMetalServerNetworkAttachmentOptions.BareMetalServerID, + "instance_id": *listInstanceNetworkInterfaceIpsOptions.InstanceID, + "network_interface_id": *listInstanceNetworkInterfaceIpsOptions.NetworkInterfaceID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createBareMetalServerNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceNetworkInterfaceIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBareMetalServerNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceNetworkInterfaceIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - _, err = builder.SetBodyContentJSON(createBareMetalServerNetworkAttachmentOptions.BareMetalServerNetworkAttachmentPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listInstanceNetworkInterfaceIpsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listInstanceNetworkInterfaceIpsOptions.Start)) + } + if listInstanceNetworkInterfaceIpsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listInstanceNetworkInterfaceIpsOptions.Limit)) } request, err := builder.Build() @@ -13763,12 +14536,12 @@ func (vpc *VpcV1) CreateBareMetalServerNetworkAttachmentWithContext(ctx context. var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_bare_metal_server_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_instance_network_interface_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollectionInstanceNetworkInterfaceContext) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13779,52 +14552,54 @@ func (vpc *VpcV1) CreateBareMetalServerNetworkAttachmentWithContext(ctx context. return } -// DeleteBareMetalServerNetworkAttachment : Delete a bare metal server network attachment -// This request deletes a bare metal server network attachment. This operation cannot be reversed. Any floating IPs -// associated with the bare metal server network attachment are implicitly disassociated. -// -// The bare metal server's primary network attachment cannot be deleted. -func (vpc *VpcV1) DeleteBareMetalServerNetworkAttachment(deleteBareMetalServerNetworkAttachmentOptions *DeleteBareMetalServerNetworkAttachmentOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteBareMetalServerNetworkAttachmentWithContext(context.Background(), deleteBareMetalServerNetworkAttachmentOptions) +// GetInstanceNetworkInterfaceIP : Retrieve the primary reserved IP +// This request retrieves the primary reserved IP for an instance network interface. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) GetInstanceNetworkInterfaceIP(getInstanceNetworkInterfaceIPOptions *GetInstanceNetworkInterfaceIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceNetworkInterfaceIPWithContext(context.Background(), getInstanceNetworkInterfaceIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteBareMetalServerNetworkAttachmentWithContext is an alternate form of the DeleteBareMetalServerNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) DeleteBareMetalServerNetworkAttachmentWithContext(ctx context.Context, deleteBareMetalServerNetworkAttachmentOptions *DeleteBareMetalServerNetworkAttachmentOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteBareMetalServerNetworkAttachmentOptions, "deleteBareMetalServerNetworkAttachmentOptions cannot be nil") +// GetInstanceNetworkInterfaceIPWithContext is an alternate form of the GetInstanceNetworkInterfaceIP method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) GetInstanceNetworkInterfaceIPWithContext(ctx context.Context, getInstanceNetworkInterfaceIPOptions *GetInstanceNetworkInterfaceIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: GetInstanceNetworkInterfaceIP") + err = core.ValidateNotNil(getInstanceNetworkInterfaceIPOptions, "getInstanceNetworkInterfaceIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteBareMetalServerNetworkAttachmentOptions, "deleteBareMetalServerNetworkAttachmentOptions") + err = core.ValidateStruct(getInstanceNetworkInterfaceIPOptions, "getInstanceNetworkInterfaceIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *deleteBareMetalServerNetworkAttachmentOptions.BareMetalServerID, - "id": *deleteBareMetalServerNetworkAttachmentOptions.ID, + "instance_id": *getInstanceNetworkInterfaceIPOptions.InstanceID, + "network_interface_id": *getInstanceNetworkInterfaceIPOptions.NetworkInterfaceID, + "id": *getInstanceNetworkInterfaceIPOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/network_interfaces/{network_interface_id}/ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteBareMetalServerNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceNetworkInterfaceIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBareMetalServerNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceNetworkInterfaceIPOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -13835,57 +14610,67 @@ func (vpc *VpcV1) DeleteBareMetalServerNetworkAttachmentWithContext(ctx context. return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_bare_metal_server_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_network_interface_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetBareMetalServerNetworkAttachment : Retrieve a bare metal server network attachment -// This request retrieves a single bare metal server network attachment specified by the identifier in the URL. -func (vpc *VpcV1) GetBareMetalServerNetworkAttachment(getBareMetalServerNetworkAttachmentOptions *GetBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBareMetalServerNetworkAttachmentWithContext(context.Background(), getBareMetalServerNetworkAttachmentOptions) +// ListInstanceVolumeAttachments : List volumes attachments on an instance +// This request lists volume attachments on an instance. A volume attachment connects a volume to an instance. Each +// instance may have many volume attachments but each volume attachment connects exactly one instance to exactly one +// volume. +func (vpc *VpcV1) ListInstanceVolumeAttachments(listInstanceVolumeAttachmentsOptions *ListInstanceVolumeAttachmentsOptions) (result *VolumeAttachmentCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListInstanceVolumeAttachmentsWithContext(context.Background(), listInstanceVolumeAttachmentsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBareMetalServerNetworkAttachmentWithContext is an alternate form of the GetBareMetalServerNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) GetBareMetalServerNetworkAttachmentWithContext(ctx context.Context, getBareMetalServerNetworkAttachmentOptions *GetBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBareMetalServerNetworkAttachmentOptions, "getBareMetalServerNetworkAttachmentOptions cannot be nil") +// ListInstanceVolumeAttachmentsWithContext is an alternate form of the ListInstanceVolumeAttachments method which supports a Context parameter +func (vpc *VpcV1) ListInstanceVolumeAttachmentsWithContext(ctx context.Context, listInstanceVolumeAttachmentsOptions *ListInstanceVolumeAttachmentsOptions) (result *VolumeAttachmentCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listInstanceVolumeAttachmentsOptions, "listInstanceVolumeAttachmentsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getBareMetalServerNetworkAttachmentOptions, "getBareMetalServerNetworkAttachmentOptions") + err = core.ValidateStruct(listInstanceVolumeAttachmentsOptions, "listInstanceVolumeAttachmentsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *getBareMetalServerNetworkAttachmentOptions.BareMetalServerID, - "id": *getBareMetalServerNetworkAttachmentOptions.ID, + "instance_id": *listInstanceVolumeAttachmentsOptions.InstanceID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBareMetalServerNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListInstanceVolumeAttachments") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listInstanceVolumeAttachmentsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -13902,12 +14687,12 @@ func (vpc *VpcV1) GetBareMetalServerNetworkAttachmentWithContext(ctx context.Con var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_bare_metal_server_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_instance_volume_attachments", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeAttachmentCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -13918,58 +14703,68 @@ func (vpc *VpcV1) GetBareMetalServerNetworkAttachmentWithContext(ctx context.Con return } -// UpdateBareMetalServerNetworkAttachment : Update a bare metal server network attachment -// This request updates a bare metal server network attachment with the information provided in a bare metal server -// network attachment patch object. The bare metal server network attachment patch object is structured in the same way -// as a retrieved bare metal server network attachment and contains only the information to be updated. -func (vpc *VpcV1) UpdateBareMetalServerNetworkAttachment(updateBareMetalServerNetworkAttachmentOptions *UpdateBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateBareMetalServerNetworkAttachmentWithContext(context.Background(), updateBareMetalServerNetworkAttachmentOptions) +// CreateInstanceVolumeAttachment : Create a volume attachment on an instance +// This request creates a new volume attachment from a volume attachment prototype object, connecting a volume to an +// instance. For this request to succeed, the specified volume must not be busy. The prototype object is structured in +// the same way as a retrieved volume attachment, and contains the information necessary to create the new volume +// attachment. +func (vpc *VpcV1) CreateInstanceVolumeAttachment(createInstanceVolumeAttachmentOptions *CreateInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateInstanceVolumeAttachmentWithContext(context.Background(), createInstanceVolumeAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateBareMetalServerNetworkAttachmentWithContext is an alternate form of the UpdateBareMetalServerNetworkAttachment method which supports a Context parameter -func (vpc *VpcV1) UpdateBareMetalServerNetworkAttachmentWithContext(ctx context.Context, updateBareMetalServerNetworkAttachmentOptions *UpdateBareMetalServerNetworkAttachmentOptions) (result BareMetalServerNetworkAttachmentIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateBareMetalServerNetworkAttachmentOptions, "updateBareMetalServerNetworkAttachmentOptions cannot be nil") +// CreateInstanceVolumeAttachmentWithContext is an alternate form of the CreateInstanceVolumeAttachment method which supports a Context parameter +func (vpc *VpcV1) CreateInstanceVolumeAttachmentWithContext(ctx context.Context, createInstanceVolumeAttachmentOptions *CreateInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createInstanceVolumeAttachmentOptions, "createInstanceVolumeAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateBareMetalServerNetworkAttachmentOptions, "updateBareMetalServerNetworkAttachmentOptions") + err = core.ValidateStruct(createInstanceVolumeAttachmentOptions, "createInstanceVolumeAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *updateBareMetalServerNetworkAttachmentOptions.BareMetalServerID, - "id": *updateBareMetalServerNetworkAttachmentOptions.ID, + "instance_id": *createInstanceVolumeAttachmentOptions.InstanceID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_attachments/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateBareMetalServerNetworkAttachmentOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateInstanceVolumeAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBareMetalServerNetworkAttachment") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createInstanceVolumeAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateBareMetalServerNetworkAttachmentOptions.BareMetalServerNetworkAttachmentPatch) + body := make(map[string]interface{}) + if createInstanceVolumeAttachmentOptions.Volume != nil { + body["volume"] = createInstanceVolumeAttachmentOptions.Volume + } + if createInstanceVolumeAttachmentOptions.DeleteVolumeOnInstanceDelete != nil { + body["delete_volume_on_instance_delete"] = createInstanceVolumeAttachmentOptions.DeleteVolumeOnInstanceDelete + } + if createInstanceVolumeAttachmentOptions.Name != nil { + body["name"] = createInstanceVolumeAttachmentOptions.Name + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -13984,12 +14779,12 @@ func (vpc *VpcV1) UpdateBareMetalServerNetworkAttachmentWithContext(ctx context. var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_bare_metal_server_network_attachment", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_instance_volume_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkAttachment) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14000,65 +14795,53 @@ func (vpc *VpcV1) UpdateBareMetalServerNetworkAttachmentWithContext(ctx context. return } -// ListBareMetalServerNetworkInterfaces : List network interfaces on a bare metal server -// This request lists network interfaces on a bare metal server. A bare metal server network interface is an abstract -// representation of a network device and attaches a bare metal server to a single subnet. Each network interface on a -// bare metal server can attach to any subnet in the zone, including subnets that are already attached to the bare metal -// server. -// -// If this bare metal server has network attachments, each returned network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface. -func (vpc *VpcV1) ListBareMetalServerNetworkInterfaces(listBareMetalServerNetworkInterfacesOptions *ListBareMetalServerNetworkInterfacesOptions) (result *BareMetalServerNetworkInterfaceCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBareMetalServerNetworkInterfacesWithContext(context.Background(), listBareMetalServerNetworkInterfacesOptions) +// DeleteInstanceVolumeAttachment : Delete a volume attachment +// This request deletes a volume attachment. This operation cannot be reversed, but a new volume attachment may +// subsequently be created for the volume. For this request to succeed, the volume must not be busy. +func (vpc *VpcV1) DeleteInstanceVolumeAttachment(deleteInstanceVolumeAttachmentOptions *DeleteInstanceVolumeAttachmentOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteInstanceVolumeAttachmentWithContext(context.Background(), deleteInstanceVolumeAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBareMetalServerNetworkInterfacesWithContext is an alternate form of the ListBareMetalServerNetworkInterfaces method which supports a Context parameter -func (vpc *VpcV1) ListBareMetalServerNetworkInterfacesWithContext(ctx context.Context, listBareMetalServerNetworkInterfacesOptions *ListBareMetalServerNetworkInterfacesOptions) (result *BareMetalServerNetworkInterfaceCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listBareMetalServerNetworkInterfacesOptions, "listBareMetalServerNetworkInterfacesOptions cannot be nil") +// DeleteInstanceVolumeAttachmentWithContext is an alternate form of the DeleteInstanceVolumeAttachment method which supports a Context parameter +func (vpc *VpcV1) DeleteInstanceVolumeAttachmentWithContext(ctx context.Context, deleteInstanceVolumeAttachmentOptions *DeleteInstanceVolumeAttachmentOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteInstanceVolumeAttachmentOptions, "deleteInstanceVolumeAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listBareMetalServerNetworkInterfacesOptions, "listBareMetalServerNetworkInterfacesOptions") + err = core.ValidateStruct(deleteInstanceVolumeAttachmentOptions, "deleteInstanceVolumeAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *listBareMetalServerNetworkInterfacesOptions.BareMetalServerID, + "instance_id": *deleteInstanceVolumeAttachmentOptions.InstanceID, + "id": *deleteInstanceVolumeAttachmentOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBareMetalServerNetworkInterfacesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteInstanceVolumeAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerNetworkInterfaces") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteInstanceVolumeAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listBareMetalServerNetworkInterfacesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listBareMetalServerNetworkInterfacesOptions.Start)) - } - if listBareMetalServerNetworkInterfacesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listBareMetalServerNetworkInterfacesOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -14066,87 +14849,64 @@ func (vpc *VpcV1) ListBareMetalServerNetworkInterfacesWithContext(ctx context.Co return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_bare_metal_server_network_interfaces", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_instance_volume_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkInterfaceCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateBareMetalServerNetworkInterface : Create a network interface on a bare metal server -// This request creates a new bare metal server network interface from a bare metal server network interface prototype -// object. The prototype object is structured in the same way as a retrieved bare metal server network interface, and -// contains the information necessary to create the new bare metal server network interface. Any subnet in the bare -// metal server's VPC may be specified, even if it is already attached to another bare metal server network interface. -// Addresses on the bare metal server network interface must be within the specified subnet's CIDR blocks. -// -// If this bare metal server has network attachments, each network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface, and new network interfaces are not allowed to be created. -func (vpc *VpcV1) CreateBareMetalServerNetworkInterface(createBareMetalServerNetworkInterfaceOptions *CreateBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateBareMetalServerNetworkInterfaceWithContext(context.Background(), createBareMetalServerNetworkInterfaceOptions) +// GetInstanceVolumeAttachment : Retrieve a volume attachment +// This request retrieves a single volume attachment specified by the identifier in the URL. +func (vpc *VpcV1) GetInstanceVolumeAttachment(getInstanceVolumeAttachmentOptions *GetInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetInstanceVolumeAttachmentWithContext(context.Background(), getInstanceVolumeAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateBareMetalServerNetworkInterfaceWithContext is an alternate form of the CreateBareMetalServerNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) CreateBareMetalServerNetworkInterfaceWithContext(ctx context.Context, createBareMetalServerNetworkInterfaceOptions *CreateBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createBareMetalServerNetworkInterfaceOptions, "createBareMetalServerNetworkInterfaceOptions cannot be nil") +// GetInstanceVolumeAttachmentWithContext is an alternate form of the GetInstanceVolumeAttachment method which supports a Context parameter +func (vpc *VpcV1) GetInstanceVolumeAttachmentWithContext(ctx context.Context, getInstanceVolumeAttachmentOptions *GetInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getInstanceVolumeAttachmentOptions, "getInstanceVolumeAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createBareMetalServerNetworkInterfaceOptions, "createBareMetalServerNetworkInterfaceOptions") + err = core.ValidateStruct(getInstanceVolumeAttachmentOptions, "getInstanceVolumeAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *createBareMetalServerNetworkInterfaceOptions.BareMetalServerID, + "instance_id": *getInstanceVolumeAttachmentOptions.InstanceID, + "id": *getInstanceVolumeAttachmentOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createBareMetalServerNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetInstanceVolumeAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBareMetalServerNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getInstanceVolumeAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createBareMetalServerNetworkInterfaceOptions.BareMetalServerNetworkInterfacePrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -14156,12 +14916,12 @@ func (vpc *VpcV1) CreateBareMetalServerNetworkInterfaceWithContext(ctx context.C var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_bare_metal_server_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_instance_volume_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeAttachment) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14172,126 +14932,135 @@ func (vpc *VpcV1) CreateBareMetalServerNetworkInterfaceWithContext(ctx context.C return } -// DeleteBareMetalServerNetworkInterface : Delete a bare metal server network interface -// This request deletes a bare metal server network interface. This operation cannot be reversed. Any floating IPs -// associated with the bare metal server network interface are implicitly disassociated. The primary bare metal server -// network interface is not allowed to be deleted. -// -// If this bare metal server has network attachments, this network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface, and is not allowed to be deleted. -func (vpc *VpcV1) DeleteBareMetalServerNetworkInterface(deleteBareMetalServerNetworkInterfaceOptions *DeleteBareMetalServerNetworkInterfaceOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteBareMetalServerNetworkInterfaceWithContext(context.Background(), deleteBareMetalServerNetworkInterfaceOptions) +// UpdateInstanceVolumeAttachment : Update a volume attachment +// This request updates a volume attachment with the information provided in a volume attachment patch object. The +// volume attachment patch object is structured in the same way as a retrieved volume attachment and needs to contain +// only the information to be updated. +func (vpc *VpcV1) UpdateInstanceVolumeAttachment(updateInstanceVolumeAttachmentOptions *UpdateInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateInstanceVolumeAttachmentWithContext(context.Background(), updateInstanceVolumeAttachmentOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteBareMetalServerNetworkInterfaceWithContext is an alternate form of the DeleteBareMetalServerNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) DeleteBareMetalServerNetworkInterfaceWithContext(ctx context.Context, deleteBareMetalServerNetworkInterfaceOptions *DeleteBareMetalServerNetworkInterfaceOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteBareMetalServerNetworkInterfaceOptions, "deleteBareMetalServerNetworkInterfaceOptions cannot be nil") +// UpdateInstanceVolumeAttachmentWithContext is an alternate form of the UpdateInstanceVolumeAttachment method which supports a Context parameter +func (vpc *VpcV1) UpdateInstanceVolumeAttachmentWithContext(ctx context.Context, updateInstanceVolumeAttachmentOptions *UpdateInstanceVolumeAttachmentOptions) (result *VolumeAttachment, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateInstanceVolumeAttachmentOptions, "updateInstanceVolumeAttachmentOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteBareMetalServerNetworkInterfaceOptions, "deleteBareMetalServerNetworkInterfaceOptions") + err = core.ValidateStruct(updateInstanceVolumeAttachmentOptions, "updateInstanceVolumeAttachmentOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *deleteBareMetalServerNetworkInterfaceOptions.BareMetalServerID, - "id": *deleteBareMetalServerNetworkInterfaceOptions.ID, + "instance_id": *updateInstanceVolumeAttachmentOptions.InstanceID, + "id": *updateInstanceVolumeAttachmentOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/instances/{instance_id}/volume_attachments/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteBareMetalServerNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateInstanceVolumeAttachment") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBareMetalServerNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateInstanceVolumeAttachmentOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateInstanceVolumeAttachmentOptions.VolumeAttachmentPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_bare_metal_server_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_instance_volume_attachment", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeAttachment) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetBareMetalServerNetworkInterface : Retrieve a bare metal server network interface -// This request retrieves a single bare metal server network interface specified by the identifier in the URL. -// -// If this bare metal server has network attachments, the retrieved network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface. -func (vpc *VpcV1) GetBareMetalServerNetworkInterface(getBareMetalServerNetworkInterfaceOptions *GetBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBareMetalServerNetworkInterfaceWithContext(context.Background(), getBareMetalServerNetworkInterfaceOptions) +// ListKeys : List keys +// This request lists keys in the region. A key contains a public SSH key which may be installed on instances when they +// are created. Private keys are not stored. +func (vpc *VpcV1) ListKeys(listKeysOptions *ListKeysOptions) (result *KeyCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListKeysWithContext(context.Background(), listKeysOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBareMetalServerNetworkInterfaceWithContext is an alternate form of the GetBareMetalServerNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceWithContext(ctx context.Context, getBareMetalServerNetworkInterfaceOptions *GetBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBareMetalServerNetworkInterfaceOptions, "getBareMetalServerNetworkInterfaceOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getBareMetalServerNetworkInterfaceOptions, "getBareMetalServerNetworkInterfaceOptions") +// ListKeysWithContext is an alternate form of the ListKeys method which supports a Context parameter +func (vpc *VpcV1) ListKeysWithContext(ctx context.Context, listKeysOptions *ListKeysOptions) (result *KeyCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listKeysOptions, "listKeysOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "bare_metal_server_id": *getBareMetalServerNetworkInterfaceOptions.BareMetalServerID, - "id": *getBareMetalServerNetworkInterfaceOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBareMetalServerNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListKeys") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listKeysOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listKeysOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listKeysOptions.Start)) + } + if listKeysOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listKeysOptions.Limit)) + } + if listKeysOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listKeysOptions.ResourceGroupID)) + } request, err := builder.Build() if err != nil { @@ -14302,12 +15071,12 @@ func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceWithContext(ctx context.Cont var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_bare_metal_server_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_keys", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKeyCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14318,62 +15087,66 @@ func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceWithContext(ctx context.Cont return } -// UpdateBareMetalServerNetworkInterface : Update a bare metal server network interface -// This request updates a bare metal server network interface with the information provided in a bare metal server -// network interface patch object. The bare metal server network interface patch object is structured in the same way as -// a retrieved bare metal server network interface and needs to contain only the information to be updated. -// -// If this bare metal server has network attachments, this network interface is a [read-only -// representation](https://cloud.ibm.com/docs/vpc?topic=vpc-vni-about#vni-old-api-clients) of its corresponding network -// attachment and its attached virtual network interface, and is not allowed to be updated. -func (vpc *VpcV1) UpdateBareMetalServerNetworkInterface(updateBareMetalServerNetworkInterfaceOptions *UpdateBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateBareMetalServerNetworkInterfaceWithContext(context.Background(), updateBareMetalServerNetworkInterfaceOptions) +// CreateKey : Create a key +// This request creates a new SSH key from an key prototype object. The prototype object is structured in the same way +// as a retrieved key, and contains the information necessary to create the new key. The public key value must be +// provided. +func (vpc *VpcV1) CreateKey(createKeyOptions *CreateKeyOptions) (result *Key, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateKeyWithContext(context.Background(), createKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateBareMetalServerNetworkInterfaceWithContext is an alternate form of the UpdateBareMetalServerNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) UpdateBareMetalServerNetworkInterfaceWithContext(ctx context.Context, updateBareMetalServerNetworkInterfaceOptions *UpdateBareMetalServerNetworkInterfaceOptions) (result BareMetalServerNetworkInterfaceIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateBareMetalServerNetworkInterfaceOptions, "updateBareMetalServerNetworkInterfaceOptions cannot be nil") +// CreateKeyWithContext is an alternate form of the CreateKey method which supports a Context parameter +func (vpc *VpcV1) CreateKeyWithContext(ctx context.Context, createKeyOptions *CreateKeyOptions) (result *Key, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createKeyOptions, "createKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateBareMetalServerNetworkInterfaceOptions, "updateBareMetalServerNetworkInterfaceOptions") + err = core.ValidateStruct(createKeyOptions, "createKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "bare_metal_server_id": *updateBareMetalServerNetworkInterfaceOptions.BareMetalServerID, - "id": *updateBareMetalServerNetworkInterfaceOptions.ID, - } - - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateBareMetalServerNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateKey") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBareMetalServerNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createKeyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateBareMetalServerNetworkInterfaceOptions.BareMetalServerNetworkInterfacePatch) + body := make(map[string]interface{}) + if createKeyOptions.PublicKey != nil { + body["public_key"] = createKeyOptions.PublicKey + } + if createKeyOptions.Name != nil { + body["name"] = createKeyOptions.Name + } + if createKeyOptions.ResourceGroup != nil { + body["resource_group"] = createKeyOptions.ResourceGroup + } + if createKeyOptions.Type != nil { + body["type"] = createKeyOptions.Type + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -14388,12 +15161,12 @@ func (vpc *VpcV1) UpdateBareMetalServerNetworkInterfaceWithContext(ctx context.C var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_bare_metal_server_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKey) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14404,49 +15177,110 @@ func (vpc *VpcV1) UpdateBareMetalServerNetworkInterfaceWithContext(ctx context.C return } -// ListBareMetalServerNetworkInterfaceFloatingIps : List floating IPs associated with a bare metal server network interface -// This request lists floating IPs associated with a bare metal server network interface. -func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceFloatingIps(listBareMetalServerNetworkInterfaceFloatingIpsOptions *ListBareMetalServerNetworkInterfaceFloatingIpsOptions) (result *FloatingIPUnpaginatedCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBareMetalServerNetworkInterfaceFloatingIpsWithContext(context.Background(), listBareMetalServerNetworkInterfaceFloatingIpsOptions) +// DeleteKey : Delete a key +// This request deletes a key. This operation cannot be reversed. +func (vpc *VpcV1) DeleteKey(deleteKeyOptions *DeleteKeyOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteKeyWithContext(context.Background(), deleteKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBareMetalServerNetworkInterfaceFloatingIpsWithContext is an alternate form of the ListBareMetalServerNetworkInterfaceFloatingIps method which supports a Context parameter -func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceFloatingIpsWithContext(ctx context.Context, listBareMetalServerNetworkInterfaceFloatingIpsOptions *ListBareMetalServerNetworkInterfaceFloatingIpsOptions) (result *FloatingIPUnpaginatedCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listBareMetalServerNetworkInterfaceFloatingIpsOptions, "listBareMetalServerNetworkInterfaceFloatingIpsOptions cannot be nil") +// DeleteKeyWithContext is an alternate form of the DeleteKey method which supports a Context parameter +func (vpc *VpcV1) DeleteKeyWithContext(ctx context.Context, deleteKeyOptions *DeleteKeyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteKeyOptions, "deleteKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listBareMetalServerNetworkInterfaceFloatingIpsOptions, "listBareMetalServerNetworkInterfaceFloatingIpsOptions") + err = core.ValidateStruct(deleteKeyOptions, "deleteKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *listBareMetalServerNetworkInterfaceFloatingIpsOptions.BareMetalServerID, - "network_interface_id": *listBareMetalServerNetworkInterfaceFloatingIpsOptions.NetworkInterfaceID, + "id": *deleteKeyOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/floating_ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBareMetalServerNetworkInterfaceFloatingIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteKey") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerNetworkInterfaceFloatingIps") + for headerName, headerValue := range deleteKeyOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "delete_key", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// GetKey : Retrieve a key +// This request retrieves a single key specified by the identifier in the URL. +func (vpc *VpcV1) GetKey(getKeyOptions *GetKeyOptions) (result *Key, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetKeyWithContext(context.Background(), getKeyOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetKeyWithContext is an alternate form of the GetKey method which supports a Context parameter +func (vpc *VpcV1) GetKeyWithContext(ctx context.Context, getKeyOptions *GetKeyOptions) (result *Key, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getKeyOptions, "getKeyOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getKeyOptions, "getKeyOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "id": *getKeyOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetKey") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range getKeyOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) @@ -14461,12 +15295,12 @@ func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceFloatingIpsWithContext(ctx var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_bare_metal_server_network_interface_floating_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPUnpaginatedCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKey) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14477,119 +15311,129 @@ func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceFloatingIpsWithContext(ctx return } -// RemoveBareMetalServerNetworkInterfaceFloatingIP : Disassociate a floating IP from a bare metal server network interface -// This request disassociates the specified floating IP from the specified bare metal server network interface. -func (vpc *VpcV1) RemoveBareMetalServerNetworkInterfaceFloatingIP(removeBareMetalServerNetworkInterfaceFloatingIPOptions *RemoveBareMetalServerNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RemoveBareMetalServerNetworkInterfaceFloatingIPWithContext(context.Background(), removeBareMetalServerNetworkInterfaceFloatingIPOptions) +// UpdateKey : Update a key +// This request updates a key's name. +func (vpc *VpcV1) UpdateKey(updateKeyOptions *UpdateKeyOptions) (result *Key, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateKeyWithContext(context.Background(), updateKeyOptions) err = core.RepurposeSDKProblem(err, "") return } -// RemoveBareMetalServerNetworkInterfaceFloatingIPWithContext is an alternate form of the RemoveBareMetalServerNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) RemoveBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx context.Context, removeBareMetalServerNetworkInterfaceFloatingIPOptions *RemoveBareMetalServerNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(removeBareMetalServerNetworkInterfaceFloatingIPOptions, "removeBareMetalServerNetworkInterfaceFloatingIPOptions cannot be nil") +// UpdateKeyWithContext is an alternate form of the UpdateKey method which supports a Context parameter +func (vpc *VpcV1) UpdateKeyWithContext(ctx context.Context, updateKeyOptions *UpdateKeyOptions) (result *Key, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateKeyOptions, "updateKeyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(removeBareMetalServerNetworkInterfaceFloatingIPOptions, "removeBareMetalServerNetworkInterfaceFloatingIPOptions") + err = core.ValidateStruct(updateKeyOptions, "updateKeyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *removeBareMetalServerNetworkInterfaceFloatingIPOptions.BareMetalServerID, - "network_interface_id": *removeBareMetalServerNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, - "id": *removeBareMetalServerNetworkInterfaceFloatingIPOptions.ID, + "id": *updateKeyOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/keys/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range removeBareMetalServerNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateKey") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveBareMetalServerNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateKeyOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateKeyOptions.KeyPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "remove_bare_metal_server_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_key", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKey) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetBareMetalServerNetworkInterfaceFloatingIP : Retrieve associated floating IP -// This request retrieves a specified floating IP if it is associated with the bare metal server network interface -// specified in the URL. -func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceFloatingIP(getBareMetalServerNetworkInterfaceFloatingIPOptions *GetBareMetalServerNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBareMetalServerNetworkInterfaceFloatingIPWithContext(context.Background(), getBareMetalServerNetworkInterfaceFloatingIPOptions) +// ListLoadBalancerProfiles : List load balancer profiles +// This request lists load balancer profiles available in the region. A load balancer profile specifies the performance +// characteristics and pricing model for a load balancer. +func (vpc *VpcV1) ListLoadBalancerProfiles(listLoadBalancerProfilesOptions *ListLoadBalancerProfilesOptions) (result *LoadBalancerProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListLoadBalancerProfilesWithContext(context.Background(), listLoadBalancerProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBareMetalServerNetworkInterfaceFloatingIPWithContext is an alternate form of the GetBareMetalServerNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx context.Context, getBareMetalServerNetworkInterfaceFloatingIPOptions *GetBareMetalServerNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBareMetalServerNetworkInterfaceFloatingIPOptions, "getBareMetalServerNetworkInterfaceFloatingIPOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getBareMetalServerNetworkInterfaceFloatingIPOptions, "getBareMetalServerNetworkInterfaceFloatingIPOptions") +// ListLoadBalancerProfilesWithContext is an alternate form of the ListLoadBalancerProfiles method which supports a Context parameter +func (vpc *VpcV1) ListLoadBalancerProfilesWithContext(ctx context.Context, listLoadBalancerProfilesOptions *ListLoadBalancerProfilesOptions) (result *LoadBalancerProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listLoadBalancerProfilesOptions, "listLoadBalancerProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "bare_metal_server_id": *getBareMetalServerNetworkInterfaceFloatingIPOptions.BareMetalServerID, - "network_interface_id": *getBareMetalServerNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, - "id": *getBareMetalServerNetworkInterfaceFloatingIPOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancer/profiles`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBareMetalServerNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listLoadBalancerProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listLoadBalancerProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listLoadBalancerProfilesOptions.Start)) + } + if listLoadBalancerProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listLoadBalancerProfilesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -14600,12 +15444,12 @@ func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_bare_metal_server_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_load_balancer_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14616,56 +15460,46 @@ func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx co return } -// AddBareMetalServerNetworkInterfaceFloatingIP : Associate a floating IP with a bare metal server network interface -// This request associates the specified floating IP with the specified bare metal server network interface. If -// `enable_infrastructure_nat` is `false`, this adds the IP to any existing associations. If `enable_infrastructure_nat` -// is `true`, this replaces any existing association. -// -// The existing floating IP must: -// - not be required by another resource, such as a public gateway -// - be in the same `zone` as the bare metal server -// -// A request body is not required, and if provided, is ignored. -func (vpc *VpcV1) AddBareMetalServerNetworkInterfaceFloatingIP(addBareMetalServerNetworkInterfaceFloatingIPOptions *AddBareMetalServerNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.AddBareMetalServerNetworkInterfaceFloatingIPWithContext(context.Background(), addBareMetalServerNetworkInterfaceFloatingIPOptions) +// GetLoadBalancerProfile : Retrieve a load balancer profile +// This request retrieves a load balancer profile specified by the name in the URL. +func (vpc *VpcV1) GetLoadBalancerProfile(getLoadBalancerProfileOptions *GetLoadBalancerProfileOptions) (result *LoadBalancerProfile, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetLoadBalancerProfileWithContext(context.Background(), getLoadBalancerProfileOptions) err = core.RepurposeSDKProblem(err, "") return } -// AddBareMetalServerNetworkInterfaceFloatingIPWithContext is an alternate form of the AddBareMetalServerNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) AddBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx context.Context, addBareMetalServerNetworkInterfaceFloatingIPOptions *AddBareMetalServerNetworkInterfaceFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(addBareMetalServerNetworkInterfaceFloatingIPOptions, "addBareMetalServerNetworkInterfaceFloatingIPOptions cannot be nil") +// GetLoadBalancerProfileWithContext is an alternate form of the GetLoadBalancerProfile method which supports a Context parameter +func (vpc *VpcV1) GetLoadBalancerProfileWithContext(ctx context.Context, getLoadBalancerProfileOptions *GetLoadBalancerProfileOptions) (result *LoadBalancerProfile, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLoadBalancerProfileOptions, "getLoadBalancerProfileOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(addBareMetalServerNetworkInterfaceFloatingIPOptions, "addBareMetalServerNetworkInterfaceFloatingIPOptions") + err = core.ValidateStruct(getLoadBalancerProfileOptions, "getLoadBalancerProfileOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "bare_metal_server_id": *addBareMetalServerNetworkInterfaceFloatingIPOptions.BareMetalServerID, - "network_interface_id": *addBareMetalServerNetworkInterfaceFloatingIPOptions.NetworkInterfaceID, - "id": *addBareMetalServerNetworkInterfaceFloatingIPOptions.ID, + "name": *getLoadBalancerProfileOptions.Name, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancer/profiles/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range addBareMetalServerNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddBareMetalServerNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLoadBalancerProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -14682,12 +15516,12 @@ func (vpc *VpcV1) AddBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "add_bare_metal_server_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_load_balancer_profile", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerProfile) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14698,56 +15532,49 @@ func (vpc *VpcV1) AddBareMetalServerNetworkInterfaceFloatingIPWithContext(ctx co return } -// ListBareMetalServerNetworkInterfaceIps : List the primary reserved IP for a bare metal server network interface -// This request lists the primary reserved IP for a bare metal server network interface. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceIps(listBareMetalServerNetworkInterfaceIpsOptions *ListBareMetalServerNetworkInterfaceIpsOptions) (result *ReservedIPCollectionBareMetalServerNetworkInterfaceContext, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBareMetalServerNetworkInterfaceIpsWithContext(context.Background(), listBareMetalServerNetworkInterfaceIpsOptions) +// ListLoadBalancers : List load balancers +// This request lists load balancers in the region. +func (vpc *VpcV1) ListLoadBalancers(listLoadBalancersOptions *ListLoadBalancersOptions) (result *LoadBalancerCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListLoadBalancersWithContext(context.Background(), listLoadBalancersOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBareMetalServerNetworkInterfaceIpsWithContext is an alternate form of the ListBareMetalServerNetworkInterfaceIps method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceIpsWithContext(ctx context.Context, listBareMetalServerNetworkInterfaceIpsOptions *ListBareMetalServerNetworkInterfaceIpsOptions) (result *ReservedIPCollectionBareMetalServerNetworkInterfaceContext, response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: ListBareMetalServerNetworkInterfaceIps") - err = core.ValidateNotNil(listBareMetalServerNetworkInterfaceIpsOptions, "listBareMetalServerNetworkInterfaceIpsOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(listBareMetalServerNetworkInterfaceIpsOptions, "listBareMetalServerNetworkInterfaceIpsOptions") +// ListLoadBalancersWithContext is an alternate form of the ListLoadBalancers method which supports a Context parameter +func (vpc *VpcV1) ListLoadBalancersWithContext(ctx context.Context, listLoadBalancersOptions *ListLoadBalancersOptions) (result *LoadBalancerCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listLoadBalancersOptions, "listLoadBalancersOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "bare_metal_server_id": *listBareMetalServerNetworkInterfaceIpsOptions.BareMetalServerID, - "network_interface_id": *listBareMetalServerNetworkInterfaceIpsOptions.NetworkInterfaceID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBareMetalServerNetworkInterfaceIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancers") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBareMetalServerNetworkInterfaceIps") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listLoadBalancersOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listLoadBalancersOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listLoadBalancersOptions.Start)) + } + if listLoadBalancersOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listLoadBalancersOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -14758,12 +15585,12 @@ func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceIpsWithContext(ctx context. var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_bare_metal_server_network_interface_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_load_balancers", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollectionBareMetalServerNetworkInterfaceContext) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14774,58 +15601,93 @@ func (vpc *VpcV1) ListBareMetalServerNetworkInterfaceIpsWithContext(ctx context. return } -// GetBareMetalServerNetworkInterfaceIP : Retrieve the primary reserved IP -// This request retrieves the primary reserved IP for a bare metal server network interface. -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceIP(getBareMetalServerNetworkInterfaceIPOptions *GetBareMetalServerNetworkInterfaceIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBareMetalServerNetworkInterfaceIPWithContext(context.Background(), getBareMetalServerNetworkInterfaceIPOptions) +// CreateLoadBalancer : Create a load balancer +// This request creates and provisions a new load balancer. +func (vpc *VpcV1) CreateLoadBalancer(createLoadBalancerOptions *CreateLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateLoadBalancerWithContext(context.Background(), createLoadBalancerOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBareMetalServerNetworkInterfaceIPWithContext is an alternate form of the GetBareMetalServerNetworkInterfaceIP method which supports a Context parameter -// Deprecated: this method is deprecated and may be removed in a future release. -func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceIPWithContext(ctx context.Context, getBareMetalServerNetworkInterfaceIPOptions *GetBareMetalServerNetworkInterfaceIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - core.GetLogger().Warn("A deprecated operation has been invoked: GetBareMetalServerNetworkInterfaceIP") - err = core.ValidateNotNil(getBareMetalServerNetworkInterfaceIPOptions, "getBareMetalServerNetworkInterfaceIPOptions cannot be nil") +// CreateLoadBalancerWithContext is an alternate form of the CreateLoadBalancer method which supports a Context parameter +func (vpc *VpcV1) CreateLoadBalancerWithContext(ctx context.Context, createLoadBalancerOptions *CreateLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createLoadBalancerOptions, "createLoadBalancerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getBareMetalServerNetworkInterfaceIPOptions, "getBareMetalServerNetworkInterfaceIPOptions") + err = core.ValidateStruct(createLoadBalancerOptions, "createLoadBalancerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "bare_metal_server_id": *getBareMetalServerNetworkInterfaceIPOptions.BareMetalServerID, - "network_interface_id": *getBareMetalServerNetworkInterfaceIPOptions.NetworkInterfaceID, - "id": *getBareMetalServerNetworkInterfaceIPOptions.ID, - } - - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{bare_metal_server_id}/network_interfaces/{network_interface_id}/ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBareMetalServerNetworkInterfaceIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerNetworkInterfaceIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createLoadBalancerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createLoadBalancerOptions.IsPublic != nil { + body["is_public"] = createLoadBalancerOptions.IsPublic + } + if createLoadBalancerOptions.Subnets != nil { + body["subnets"] = createLoadBalancerOptions.Subnets + } + if createLoadBalancerOptions.Dns != nil { + body["dns"] = createLoadBalancerOptions.Dns + } + if createLoadBalancerOptions.IsPrivatePath != nil { + body["is_private_path"] = createLoadBalancerOptions.IsPrivatePath + } + if createLoadBalancerOptions.Listeners != nil { + body["listeners"] = createLoadBalancerOptions.Listeners + } + if createLoadBalancerOptions.Logging != nil { + body["logging"] = createLoadBalancerOptions.Logging + } + if createLoadBalancerOptions.Name != nil { + body["name"] = createLoadBalancerOptions.Name + } + if createLoadBalancerOptions.Pools != nil { + body["pools"] = createLoadBalancerOptions.Pools + } + if createLoadBalancerOptions.Profile != nil { + body["profile"] = createLoadBalancerOptions.Profile + } + if createLoadBalancerOptions.ResourceGroup != nil { + body["resource_group"] = createLoadBalancerOptions.ResourceGroup + } + if createLoadBalancerOptions.RouteMode != nil { + body["route_mode"] = createLoadBalancerOptions.RouteMode + } + if createLoadBalancerOptions.SecurityGroups != nil { + body["security_groups"] = createLoadBalancerOptions.SecurityGroups + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -14835,12 +15697,12 @@ func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceIPWithContext(ctx context.Co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_bare_metal_server_network_interface_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_load_balancer", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14851,49 +15713,52 @@ func (vpc *VpcV1) GetBareMetalServerNetworkInterfaceIPWithContext(ctx context.Co return } -// DeleteBareMetalServer : Delete a bare metal server -// This request deletes a bare metal server. This operation cannot be reversed. Any floating IPs associated with the -// bare metal server network interfaces are implicitly disassociated. -func (vpc *VpcV1) DeleteBareMetalServer(deleteBareMetalServerOptions *DeleteBareMetalServerOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteBareMetalServerWithContext(context.Background(), deleteBareMetalServerOptions) +// DeleteLoadBalancer : Delete a load balancer +// This request deletes a load balancer. This operation cannot be reversed. A load balancer cannot be deleted if its +// `provisioning_status` is `delete_pending` or it is referenced by a resource. +func (vpc *VpcV1) DeleteLoadBalancer(deleteLoadBalancerOptions *DeleteLoadBalancerOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteLoadBalancerWithContext(context.Background(), deleteLoadBalancerOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteBareMetalServerWithContext is an alternate form of the DeleteBareMetalServer method which supports a Context parameter -func (vpc *VpcV1) DeleteBareMetalServerWithContext(ctx context.Context, deleteBareMetalServerOptions *DeleteBareMetalServerOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteBareMetalServerOptions, "deleteBareMetalServerOptions cannot be nil") +// DeleteLoadBalancerWithContext is an alternate form of the DeleteLoadBalancer method which supports a Context parameter +func (vpc *VpcV1) DeleteLoadBalancerWithContext(ctx context.Context, deleteLoadBalancerOptions *DeleteLoadBalancerOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteLoadBalancerOptions, "deleteLoadBalancerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteBareMetalServerOptions, "deleteBareMetalServerOptions") + err = core.ValidateStruct(deleteLoadBalancerOptions, "deleteLoadBalancerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteBareMetalServerOptions.ID, + "id": *deleteLoadBalancerOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteBareMetalServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBareMetalServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteLoadBalancerOptions.Headers { builder.AddHeader(headerName, headerValue) } + if deleteLoadBalancerOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteLoadBalancerOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -14906,7 +15771,7 @@ func (vpc *VpcV1) DeleteBareMetalServerWithContext(ctx context.Context, deleteBa response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_bare_metal_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_load_balancer", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -14914,46 +15779,46 @@ func (vpc *VpcV1) DeleteBareMetalServerWithContext(ctx context.Context, deleteBa return } -// GetBareMetalServer : Retrieve a bare metal server -// This request retrieves a single bare metal server specified by the identifier in the URL. -func (vpc *VpcV1) GetBareMetalServer(getBareMetalServerOptions *GetBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBareMetalServerWithContext(context.Background(), getBareMetalServerOptions) +// GetLoadBalancer : Retrieve a load balancer +// This request retrieves a single load balancer specified by the identifier in the URL path. +func (vpc *VpcV1) GetLoadBalancer(getLoadBalancerOptions *GetLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetLoadBalancerWithContext(context.Background(), getLoadBalancerOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBareMetalServerWithContext is an alternate form of the GetBareMetalServer method which supports a Context parameter -func (vpc *VpcV1) GetBareMetalServerWithContext(ctx context.Context, getBareMetalServerOptions *GetBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBareMetalServerOptions, "getBareMetalServerOptions cannot be nil") +// GetLoadBalancerWithContext is an alternate form of the GetLoadBalancer method which supports a Context parameter +func (vpc *VpcV1) GetLoadBalancerWithContext(ctx context.Context, getLoadBalancerOptions *GetLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLoadBalancerOptions, "getLoadBalancerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getBareMetalServerOptions, "getBareMetalServerOptions") + err = core.ValidateStruct(getLoadBalancerOptions, "getLoadBalancerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getBareMetalServerOptions.ID, + "id": *getLoadBalancerOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBareMetalServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLoadBalancerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -14970,12 +15835,12 @@ func (vpc *VpcV1) GetBareMetalServerWithContext(ctx context.Context, getBareMeta var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_bare_metal_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_load_balancer", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServer) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -14986,56 +15851,60 @@ func (vpc *VpcV1) GetBareMetalServerWithContext(ctx context.Context, getBareMeta return } -// UpdateBareMetalServer : Update a bare metal server -// This request updates a bare metal server with the information in a provided patch. The bare metal server patch object -// is structured in the same way as a retrieved bare metal server and contains only the information to be updated. -func (vpc *VpcV1) UpdateBareMetalServer(updateBareMetalServerOptions *UpdateBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateBareMetalServerWithContext(context.Background(), updateBareMetalServerOptions) +// UpdateLoadBalancer : Update a load balancer +// This request updates a load balancer with the information in a provided load balancer patch. The load balancer patch +// object is structured in the same way as a retrieved load balancer and contains only the information to be updated. A +// load balancer can only be updated if its `provisioning_status` is `active`. +func (vpc *VpcV1) UpdateLoadBalancer(updateLoadBalancerOptions *UpdateLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateLoadBalancerWithContext(context.Background(), updateLoadBalancerOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateBareMetalServerWithContext is an alternate form of the UpdateBareMetalServer method which supports a Context parameter -func (vpc *VpcV1) UpdateBareMetalServerWithContext(ctx context.Context, updateBareMetalServerOptions *UpdateBareMetalServerOptions) (result *BareMetalServer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateBareMetalServerOptions, "updateBareMetalServerOptions cannot be nil") +// UpdateLoadBalancerWithContext is an alternate form of the UpdateLoadBalancer method which supports a Context parameter +func (vpc *VpcV1) UpdateLoadBalancerWithContext(ctx context.Context, updateLoadBalancerOptions *UpdateLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateLoadBalancerOptions, "updateLoadBalancerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateBareMetalServerOptions, "updateBareMetalServerOptions") + err = core.ValidateStruct(updateLoadBalancerOptions, "updateLoadBalancerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateBareMetalServerOptions.ID, + "id": *updateLoadBalancerOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateBareMetalServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBareMetalServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateLoadBalancerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateLoadBalancerOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateLoadBalancerOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateBareMetalServerOptions.BareMetalServerPatch) + _, err = builder.SetBodyContentJSON(updateLoadBalancerOptions.LoadBalancerPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -15050,12 +15919,12 @@ func (vpc *VpcV1) UpdateBareMetalServerWithContext(ctx context.Context, updateBa var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_bare_metal_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_load_balancer", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServer) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -15066,121 +15935,118 @@ func (vpc *VpcV1) UpdateBareMetalServerWithContext(ctx context.Context, updateBa return } -// UpdateFirmwareForBareMetalServer : Update firmware for a bare metal server -// This request updates a bare metal server to the latest available firmware. The server must be stopped. -func (vpc *VpcV1) UpdateFirmwareForBareMetalServer(updateFirmwareForBareMetalServerOptions *UpdateFirmwareForBareMetalServerOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.UpdateFirmwareForBareMetalServerWithContext(context.Background(), updateFirmwareForBareMetalServerOptions) +// GetLoadBalancerStatistics : List statistics of a load balancer +// This request lists statistics of a load balancer. +func (vpc *VpcV1) GetLoadBalancerStatistics(getLoadBalancerStatisticsOptions *GetLoadBalancerStatisticsOptions) (result *LoadBalancerStatistics, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetLoadBalancerStatisticsWithContext(context.Background(), getLoadBalancerStatisticsOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateFirmwareForBareMetalServerWithContext is an alternate form of the UpdateFirmwareForBareMetalServer method which supports a Context parameter -func (vpc *VpcV1) UpdateFirmwareForBareMetalServerWithContext(ctx context.Context, updateFirmwareForBareMetalServerOptions *UpdateFirmwareForBareMetalServerOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateFirmwareForBareMetalServerOptions, "updateFirmwareForBareMetalServerOptions cannot be nil") +// GetLoadBalancerStatisticsWithContext is an alternate form of the GetLoadBalancerStatistics method which supports a Context parameter +func (vpc *VpcV1) GetLoadBalancerStatisticsWithContext(ctx context.Context, getLoadBalancerStatisticsOptions *GetLoadBalancerStatisticsOptions) (result *LoadBalancerStatistics, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLoadBalancerStatisticsOptions, "getLoadBalancerStatisticsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateFirmwareForBareMetalServerOptions, "updateFirmwareForBareMetalServerOptions") + err = core.ValidateStruct(getLoadBalancerStatisticsOptions, "getLoadBalancerStatisticsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateFirmwareForBareMetalServerOptions.ID, + "id": *getLoadBalancerStatisticsOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/firmware/update`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{id}/statistics`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateFirmwareForBareMetalServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerStatistics") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateFirmwareForBareMetalServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLoadBalancerStatisticsOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if updateFirmwareForBareMetalServerOptions.AutoStart != nil { - body["auto_start"] = updateFirmwareForBareMetalServerOptions.AutoStart - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_firmware_for_bare_metal_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_load_balancer_statistics", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerStatistics) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetBareMetalServerInitialization : Retrieve initialization configuration for a bare metal server -// This request retrieves configuration used to initialize the bare metal server, such as the image used, SSH keys, and -// any configured usernames and passwords. These can subsequently be changed on the server and therefore may not be -// current. -func (vpc *VpcV1) GetBareMetalServerInitialization(getBareMetalServerInitializationOptions *GetBareMetalServerInitializationOptions) (result *BareMetalServerInitialization, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBareMetalServerInitializationWithContext(context.Background(), getBareMetalServerInitializationOptions) +// ListLoadBalancerListeners : List listeners for a load balancer +// This request lists listeners for a load balancer. +func (vpc *VpcV1) ListLoadBalancerListeners(listLoadBalancerListenersOptions *ListLoadBalancerListenersOptions) (result *LoadBalancerListenerCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListLoadBalancerListenersWithContext(context.Background(), listLoadBalancerListenersOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBareMetalServerInitializationWithContext is an alternate form of the GetBareMetalServerInitialization method which supports a Context parameter -func (vpc *VpcV1) GetBareMetalServerInitializationWithContext(ctx context.Context, getBareMetalServerInitializationOptions *GetBareMetalServerInitializationOptions) (result *BareMetalServerInitialization, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBareMetalServerInitializationOptions, "getBareMetalServerInitializationOptions cannot be nil") +// ListLoadBalancerListenersWithContext is an alternate form of the ListLoadBalancerListeners method which supports a Context parameter +func (vpc *VpcV1) ListLoadBalancerListenersWithContext(ctx context.Context, listLoadBalancerListenersOptions *ListLoadBalancerListenersOptions) (result *LoadBalancerListenerCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listLoadBalancerListenersOptions, "listLoadBalancerListenersOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getBareMetalServerInitializationOptions, "getBareMetalServerInitializationOptions") + err = core.ValidateStruct(listLoadBalancerListenersOptions, "listLoadBalancerListenersOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getBareMetalServerInitializationOptions.ID, + "load_balancer_id": *listLoadBalancerListenersOptions.LoadBalancerID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/initialization`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBareMetalServerInitializationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerListeners") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBareMetalServerInitialization") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listLoadBalancerListenersOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -15197,12 +16063,12 @@ func (vpc *VpcV1) GetBareMetalServerInitializationWithContext(ctx context.Contex var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_bare_metal_server_initialization", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_load_balancer_listeners", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerInitialization) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -15213,47 +16079,46 @@ func (vpc *VpcV1) GetBareMetalServerInitializationWithContext(ctx context.Contex return } -// ReplaceBareMetalServerInitialization : Reinitialize a bare metal server -// This request reinitializes a bare metal server with the specified image and SSH keys. The server must be stopped. -// Upon successful reinitiatilization, the bare metal server will be started automatically. -func (vpc *VpcV1) ReplaceBareMetalServerInitialization(replaceBareMetalServerInitializationOptions *ReplaceBareMetalServerInitializationOptions) (result *BareMetalServerInitialization, response *core.DetailedResponse, err error) { - result, response, err = vpc.ReplaceBareMetalServerInitializationWithContext(context.Background(), replaceBareMetalServerInitializationOptions) +// CreateLoadBalancerListener : Create a listener for a load balancer +// This request creates a new listener for a load balancer. +func (vpc *VpcV1) CreateLoadBalancerListener(createLoadBalancerListenerOptions *CreateLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateLoadBalancerListenerWithContext(context.Background(), createLoadBalancerListenerOptions) err = core.RepurposeSDKProblem(err, "") return } -// ReplaceBareMetalServerInitializationWithContext is an alternate form of the ReplaceBareMetalServerInitialization method which supports a Context parameter -func (vpc *VpcV1) ReplaceBareMetalServerInitializationWithContext(ctx context.Context, replaceBareMetalServerInitializationOptions *ReplaceBareMetalServerInitializationOptions) (result *BareMetalServerInitialization, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(replaceBareMetalServerInitializationOptions, "replaceBareMetalServerInitializationOptions cannot be nil") +// CreateLoadBalancerListenerWithContext is an alternate form of the CreateLoadBalancerListener method which supports a Context parameter +func (vpc *VpcV1) CreateLoadBalancerListenerWithContext(ctx context.Context, createLoadBalancerListenerOptions *CreateLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createLoadBalancerListenerOptions, "createLoadBalancerListenerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(replaceBareMetalServerInitializationOptions, "replaceBareMetalServerInitializationOptions") + err = core.ValidateStruct(createLoadBalancerListenerOptions, "createLoadBalancerListenerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *replaceBareMetalServerInitializationOptions.ID, + "load_balancer_id": *createLoadBalancerListenerOptions.LoadBalancerID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/initialization`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range replaceBareMetalServerInitializationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerListener") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ReplaceBareMetalServerInitialization") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createLoadBalancerListenerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -15263,14 +16128,38 @@ func (vpc *VpcV1) ReplaceBareMetalServerInitializationWithContext(ctx context.Co builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if replaceBareMetalServerInitializationOptions.Image != nil { - body["image"] = replaceBareMetalServerInitializationOptions.Image + if createLoadBalancerListenerOptions.Protocol != nil { + body["protocol"] = createLoadBalancerListenerOptions.Protocol } - if replaceBareMetalServerInitializationOptions.Keys != nil { - body["keys"] = replaceBareMetalServerInitializationOptions.Keys + if createLoadBalancerListenerOptions.AcceptProxyProtocol != nil { + body["accept_proxy_protocol"] = createLoadBalancerListenerOptions.AcceptProxyProtocol } - if replaceBareMetalServerInitializationOptions.UserData != nil { - body["user_data"] = replaceBareMetalServerInitializationOptions.UserData + if createLoadBalancerListenerOptions.CertificateInstance != nil { + body["certificate_instance"] = createLoadBalancerListenerOptions.CertificateInstance + } + if createLoadBalancerListenerOptions.ConnectionLimit != nil { + body["connection_limit"] = createLoadBalancerListenerOptions.ConnectionLimit + } + if createLoadBalancerListenerOptions.DefaultPool != nil { + body["default_pool"] = createLoadBalancerListenerOptions.DefaultPool + } + if createLoadBalancerListenerOptions.HTTPSRedirect != nil { + body["https_redirect"] = createLoadBalancerListenerOptions.HTTPSRedirect + } + if createLoadBalancerListenerOptions.IdleConnectionTimeout != nil { + body["idle_connection_timeout"] = createLoadBalancerListenerOptions.IdleConnectionTimeout + } + if createLoadBalancerListenerOptions.Policies != nil { + body["policies"] = createLoadBalancerListenerOptions.Policies + } + if createLoadBalancerListenerOptions.Port != nil { + body["port"] = createLoadBalancerListenerOptions.Port + } + if createLoadBalancerListenerOptions.PortMax != nil { + body["port_max"] = createLoadBalancerListenerOptions.PortMax + } + if createLoadBalancerListenerOptions.PortMin != nil { + body["port_min"] = createLoadBalancerListenerOptions.PortMin } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -15287,12 +16176,12 @@ func (vpc *VpcV1) ReplaceBareMetalServerInitializationWithContext(ctx context.Co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "replace_bare_metal_server_initialization", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_load_balancer_listener", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBareMetalServerInitialization) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListener) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -15303,47 +16192,48 @@ func (vpc *VpcV1) ReplaceBareMetalServerInitializationWithContext(ctx context.Co return } -// RestartBareMetalServer : Restart a bare metal server -// This request immediately restarts a bare metal server. For this request to succeed, the server must have a `status` -// of `running`. -func (vpc *VpcV1) RestartBareMetalServer(restartBareMetalServerOptions *RestartBareMetalServerOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RestartBareMetalServerWithContext(context.Background(), restartBareMetalServerOptions) +// DeleteLoadBalancerListener : Delete a load balancer listener +// This request deletes a load balancer listener. This operation cannot be reversed. For this operation to succeed, the +// listener must not be the target of another load balancer listener. +func (vpc *VpcV1) DeleteLoadBalancerListener(deleteLoadBalancerListenerOptions *DeleteLoadBalancerListenerOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteLoadBalancerListenerWithContext(context.Background(), deleteLoadBalancerListenerOptions) err = core.RepurposeSDKProblem(err, "") return } -// RestartBareMetalServerWithContext is an alternate form of the RestartBareMetalServer method which supports a Context parameter -func (vpc *VpcV1) RestartBareMetalServerWithContext(ctx context.Context, restartBareMetalServerOptions *RestartBareMetalServerOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(restartBareMetalServerOptions, "restartBareMetalServerOptions cannot be nil") +// DeleteLoadBalancerListenerWithContext is an alternate form of the DeleteLoadBalancerListener method which supports a Context parameter +func (vpc *VpcV1) DeleteLoadBalancerListenerWithContext(ctx context.Context, deleteLoadBalancerListenerOptions *DeleteLoadBalancerListenerOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteLoadBalancerListenerOptions, "deleteLoadBalancerListenerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(restartBareMetalServerOptions, "restartBareMetalServerOptions") + err = core.ValidateStruct(deleteLoadBalancerListenerOptions, "deleteLoadBalancerListenerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *restartBareMetalServerOptions.ID, + "load_balancer_id": *deleteLoadBalancerListenerOptions.LoadBalancerID, + "id": *deleteLoadBalancerListenerOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/restart`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range restartBareMetalServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerListener") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RestartBareMetalServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteLoadBalancerListenerOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -15358,7 +16248,7 @@ func (vpc *VpcV1) RestartBareMetalServerWithContext(ctx context.Context, restart response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "restart_bare_metal_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_load_balancer_listener", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -15366,48 +16256,50 @@ func (vpc *VpcV1) RestartBareMetalServerWithContext(ctx context.Context, restart return } -// StartBareMetalServer : Start a bare metal server -// This request starts a bare metal server. It will run immediately provided the server is stopped. -func (vpc *VpcV1) StartBareMetalServer(startBareMetalServerOptions *StartBareMetalServerOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.StartBareMetalServerWithContext(context.Background(), startBareMetalServerOptions) +// GetLoadBalancerListener : Retrieve a load balancer listener +// This request retrieves a single listener specified by the identifier in the URL path. +func (vpc *VpcV1) GetLoadBalancerListener(getLoadBalancerListenerOptions *GetLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetLoadBalancerListenerWithContext(context.Background(), getLoadBalancerListenerOptions) err = core.RepurposeSDKProblem(err, "") return } -// StartBareMetalServerWithContext is an alternate form of the StartBareMetalServer method which supports a Context parameter -func (vpc *VpcV1) StartBareMetalServerWithContext(ctx context.Context, startBareMetalServerOptions *StartBareMetalServerOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(startBareMetalServerOptions, "startBareMetalServerOptions cannot be nil") +// GetLoadBalancerListenerWithContext is an alternate form of the GetLoadBalancerListener method which supports a Context parameter +func (vpc *VpcV1) GetLoadBalancerListenerWithContext(ctx context.Context, getLoadBalancerListenerOptions *GetLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLoadBalancerListenerOptions, "getLoadBalancerListenerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(startBareMetalServerOptions, "startBareMetalServerOptions") + err = core.ValidateStruct(getLoadBalancerListenerOptions, "getLoadBalancerListenerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *startBareMetalServerOptions.ID, + "load_balancer_id": *getLoadBalancerListenerOptions.LoadBalancerID, + "id": *getLoadBalancerListenerOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/start`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range startBareMetalServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerListener") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "StartBareMetalServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLoadBalancerListenerOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -15418,69 +16310,75 @@ func (vpc *VpcV1) StartBareMetalServerWithContext(ctx context.Context, startBare return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "start_bare_metal_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_load_balancer_listener", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListener) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// StopBareMetalServer : Stop a bare metal server -// This request stops a bare metal server. It will run immediately provided the server is running. Note: A soft stop may -// not complete as it relies on the operating system to perform the operation. -func (vpc *VpcV1) StopBareMetalServer(stopBareMetalServerOptions *StopBareMetalServerOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.StopBareMetalServerWithContext(context.Background(), stopBareMetalServerOptions) +// UpdateLoadBalancerListener : Update a load balancer listener +// This request updates a load balancer listener from a listener patch. +func (vpc *VpcV1) UpdateLoadBalancerListener(updateLoadBalancerListenerOptions *UpdateLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateLoadBalancerListenerWithContext(context.Background(), updateLoadBalancerListenerOptions) err = core.RepurposeSDKProblem(err, "") return } -// StopBareMetalServerWithContext is an alternate form of the StopBareMetalServer method which supports a Context parameter -func (vpc *VpcV1) StopBareMetalServerWithContext(ctx context.Context, stopBareMetalServerOptions *StopBareMetalServerOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(stopBareMetalServerOptions, "stopBareMetalServerOptions cannot be nil") +// UpdateLoadBalancerListenerWithContext is an alternate form of the UpdateLoadBalancerListener method which supports a Context parameter +func (vpc *VpcV1) UpdateLoadBalancerListenerWithContext(ctx context.Context, updateLoadBalancerListenerOptions *UpdateLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateLoadBalancerListenerOptions, "updateLoadBalancerListenerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(stopBareMetalServerOptions, "stopBareMetalServerOptions") + err = core.ValidateStruct(updateLoadBalancerListenerOptions, "updateLoadBalancerListenerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *stopBareMetalServerOptions.ID, + "load_balancer_id": *updateLoadBalancerListenerOptions.LoadBalancerID, + "id": *updateLoadBalancerListenerOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/bare_metal_servers/{id}/stop`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range stopBareMetalServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerListener") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "StopBareMetalServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateLoadBalancerListenerOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if stopBareMetalServerOptions.Type != nil { - body["type"] = stopBareMetalServerOptions.Type - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(updateLoadBalancerListenerOptions.LoadBalancerListenerPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -15492,60 +16390,73 @@ func (vpc *VpcV1) StopBareMetalServerWithContext(ctx context.Context, stopBareMe return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "stop_bare_metal_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_load_balancer_listener", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListener) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListVolumeProfiles : List volume profiles -// This request lists [volume profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-block-storage-profiles) available in -// the region. A volume profile specifies the performance characteristics and pricing model for a volume. -func (vpc *VpcV1) ListVolumeProfiles(listVolumeProfilesOptions *ListVolumeProfilesOptions) (result *VolumeProfileCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVolumeProfilesWithContext(context.Background(), listVolumeProfilesOptions) +// ListLoadBalancerListenerPolicies : List policies for a load balancer listener +// This request lists policies for a load balancer listener. A policy consists of rules to match against each incoming +// request, and an action to apply to the request if a rule matches. +func (vpc *VpcV1) ListLoadBalancerListenerPolicies(listLoadBalancerListenerPoliciesOptions *ListLoadBalancerListenerPoliciesOptions) (result *LoadBalancerListenerPolicyCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListLoadBalancerListenerPoliciesWithContext(context.Background(), listLoadBalancerListenerPoliciesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVolumeProfilesWithContext is an alternate form of the ListVolumeProfiles method which supports a Context parameter -func (vpc *VpcV1) ListVolumeProfilesWithContext(ctx context.Context, listVolumeProfilesOptions *ListVolumeProfilesOptions) (result *VolumeProfileCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listVolumeProfilesOptions, "listVolumeProfilesOptions") +// ListLoadBalancerListenerPoliciesWithContext is an alternate form of the ListLoadBalancerListenerPolicies method which supports a Context parameter +func (vpc *VpcV1) ListLoadBalancerListenerPoliciesWithContext(ctx context.Context, listLoadBalancerListenerPoliciesOptions *ListLoadBalancerListenerPoliciesOptions) (result *LoadBalancerListenerPolicyCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listLoadBalancerListenerPoliciesOptions, "listLoadBalancerListenerPoliciesOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listLoadBalancerListenerPoliciesOptions, "listLoadBalancerListenerPoliciesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "load_balancer_id": *listLoadBalancerListenerPoliciesOptions.LoadBalancerID, + "listener_id": *listLoadBalancerListenerPoliciesOptions.ListenerID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volume/profiles`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVolumeProfilesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerListenerPolicies") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVolumeProfiles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listLoadBalancerListenerPoliciesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVolumeProfilesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVolumeProfilesOptions.Start)) - } - if listVolumeProfilesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVolumeProfilesOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -15556,12 +16467,12 @@ func (vpc *VpcV1) ListVolumeProfilesWithContext(ctx context.Context, listVolumeP var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_volume_profiles", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_load_balancer_listener_policies", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeProfileCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -15572,53 +16483,79 @@ func (vpc *VpcV1) ListVolumeProfilesWithContext(ctx context.Context, listVolumeP return } -// GetVolumeProfile : Retrieve a volume profile -// This request retrieves a single volume profile specified by the name in the URL. -func (vpc *VpcV1) GetVolumeProfile(getVolumeProfileOptions *GetVolumeProfileOptions) (result *VolumeProfile, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVolumeProfileWithContext(context.Background(), getVolumeProfileOptions) +// CreateLoadBalancerListenerPolicy : Create a policy for a load balancer listener +// This request creates a new policy from a load balancer listener policy object. The prototype object is structured in +// the same way as a retrieved policy, and contains the information necessary to create the new policy. For this request +// to succeed, the load balancer must be in the `application` family. +func (vpc *VpcV1) CreateLoadBalancerListenerPolicy(createLoadBalancerListenerPolicyOptions *CreateLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateLoadBalancerListenerPolicyWithContext(context.Background(), createLoadBalancerListenerPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVolumeProfileWithContext is an alternate form of the GetVolumeProfile method which supports a Context parameter -func (vpc *VpcV1) GetVolumeProfileWithContext(ctx context.Context, getVolumeProfileOptions *GetVolumeProfileOptions) (result *VolumeProfile, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVolumeProfileOptions, "getVolumeProfileOptions cannot be nil") +// CreateLoadBalancerListenerPolicyWithContext is an alternate form of the CreateLoadBalancerListenerPolicy method which supports a Context parameter +func (vpc *VpcV1) CreateLoadBalancerListenerPolicyWithContext(ctx context.Context, createLoadBalancerListenerPolicyOptions *CreateLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createLoadBalancerListenerPolicyOptions, "createLoadBalancerListenerPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVolumeProfileOptions, "getVolumeProfileOptions") + err = core.ValidateStruct(createLoadBalancerListenerPolicyOptions, "createLoadBalancerListenerPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "name": *getVolumeProfileOptions.Name, + "load_balancer_id": *createLoadBalancerListenerPolicyOptions.LoadBalancerID, + "listener_id": *createLoadBalancerListenerPolicyOptions.ListenerID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volume/profiles/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVolumeProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerListenerPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVolumeProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createLoadBalancerListenerPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createLoadBalancerListenerPolicyOptions.Action != nil { + body["action"] = createLoadBalancerListenerPolicyOptions.Action + } + if createLoadBalancerListenerPolicyOptions.Priority != nil { + body["priority"] = createLoadBalancerListenerPolicyOptions.Priority + } + if createLoadBalancerListenerPolicyOptions.Name != nil { + body["name"] = createLoadBalancerListenerPolicyOptions.Name + } + if createLoadBalancerListenerPolicyOptions.Rules != nil { + body["rules"] = createLoadBalancerListenerPolicyOptions.Rules + } + if createLoadBalancerListenerPolicyOptions.Target != nil { + body["target"] = createLoadBalancerListenerPolicyOptions.Target + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -15628,12 +16565,12 @@ func (vpc *VpcV1) GetVolumeProfileWithContext(ctx context.Context, getVolumeProf var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_volume_profile", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_load_balancer_listener_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeProfile) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -15644,71 +16581,53 @@ func (vpc *VpcV1) GetVolumeProfileWithContext(ctx context.Context, getVolumeProf return } -// ListVolumes : List volumes -// This request lists volumes in the region. Volumes are network-connected block storage devices that may be attached to -// one or more instances in the same region. -func (vpc *VpcV1) ListVolumes(listVolumesOptions *ListVolumesOptions) (result *VolumeCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVolumesWithContext(context.Background(), listVolumesOptions) +// DeleteLoadBalancerListenerPolicy : Delete a load balancer listener policy +// Deletes a policy of the load balancer listener. This operation cannot be reversed. +func (vpc *VpcV1) DeleteLoadBalancerListenerPolicy(deleteLoadBalancerListenerPolicyOptions *DeleteLoadBalancerListenerPolicyOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteLoadBalancerListenerPolicyWithContext(context.Background(), deleteLoadBalancerListenerPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVolumesWithContext is an alternate form of the ListVolumes method which supports a Context parameter -func (vpc *VpcV1) ListVolumesWithContext(ctx context.Context, listVolumesOptions *ListVolumesOptions) (result *VolumeCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listVolumesOptions, "listVolumesOptions") +// DeleteLoadBalancerListenerPolicyWithContext is an alternate form of the DeleteLoadBalancerListenerPolicy method which supports a Context parameter +func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyWithContext(ctx context.Context, deleteLoadBalancerListenerPolicyOptions *DeleteLoadBalancerListenerPolicyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteLoadBalancerListenerPolicyOptions, "deleteLoadBalancerListenerPolicyOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteLoadBalancerListenerPolicyOptions, "deleteLoadBalancerListenerPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "load_balancer_id": *deleteLoadBalancerListenerPolicyOptions.LoadBalancerID, + "listener_id": *deleteLoadBalancerListenerPolicyOptions.ListenerID, + "id": *deleteLoadBalancerListenerPolicyOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVolumesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerListenerPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVolumes") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteLoadBalancerListenerPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVolumesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVolumesOptions.Start)) - } - if listVolumesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVolumesOptions.Limit)) - } - if listVolumesOptions.AttachmentState != nil { - builder.AddQuery("attachment_state", fmt.Sprint(*listVolumesOptions.AttachmentState)) - } - if listVolumesOptions.Encryption != nil { - builder.AddQuery("encryption", fmt.Sprint(*listVolumesOptions.Encryption)) - } - if listVolumesOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listVolumesOptions.Name)) - } - if listVolumesOptions.OperatingSystemFamily != nil { - builder.AddQuery("operating_system.family", fmt.Sprint(*listVolumesOptions.OperatingSystemFamily)) - } - if listVolumesOptions.OperatingSystemArchitecture != nil { - builder.AddQuery("operating_system.architecture", fmt.Sprint(*listVolumesOptions.OperatingSystemArchitecture)) - } - if listVolumesOptions.Tag != nil { - builder.AddQuery("tag", fmt.Sprint(*listVolumesOptions.Tag)) - } - if listVolumesOptions.ZoneName != nil { - builder.AddQuery("zone.name", fmt.Sprint(*listVolumesOptions.ZoneName)) - } request, err := builder.Build() if err != nil { @@ -15716,76 +16635,65 @@ func (vpc *VpcV1) ListVolumesWithContext(ctx context.Context, listVolumesOptions return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_volumes", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_load_balancer_listener_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateVolume : Create a volume -// This request creates a new volume from a volume prototype object. The prototype object is structured in the same way -// as a retrieved volume, and contains the information necessary to create the new volume. -func (vpc *VpcV1) CreateVolume(createVolumeOptions *CreateVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVolumeWithContext(context.Background(), createVolumeOptions) +// GetLoadBalancerListenerPolicy : Retrieve a load balancer listener policy +// Retrieve a single policy specified by the identifier in the URL path. +func (vpc *VpcV1) GetLoadBalancerListenerPolicy(getLoadBalancerListenerPolicyOptions *GetLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetLoadBalancerListenerPolicyWithContext(context.Background(), getLoadBalancerListenerPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVolumeWithContext is an alternate form of the CreateVolume method which supports a Context parameter -func (vpc *VpcV1) CreateVolumeWithContext(ctx context.Context, createVolumeOptions *CreateVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVolumeOptions, "createVolumeOptions cannot be nil") +// GetLoadBalancerListenerPolicyWithContext is an alternate form of the GetLoadBalancerListenerPolicy method which supports a Context parameter +func (vpc *VpcV1) GetLoadBalancerListenerPolicyWithContext(ctx context.Context, getLoadBalancerListenerPolicyOptions *GetLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLoadBalancerListenerPolicyOptions, "getLoadBalancerListenerPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVolumeOptions, "createVolumeOptions") + err = core.ValidateStruct(getLoadBalancerListenerPolicyOptions, "getLoadBalancerListenerPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "load_balancer_id": *getLoadBalancerListenerPolicyOptions.LoadBalancerID, + "listener_id": *getLoadBalancerListenerPolicyOptions.ListenerID, + "id": *getLoadBalancerListenerPolicyOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVolumeOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerListenerPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVolume") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLoadBalancerListenerPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createVolumeOptions.VolumePrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -15795,12 +16703,12 @@ func (vpc *VpcV1) CreateVolumeWithContext(ctx context.Context, createVolumeOptio var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_volume", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_load_balancer_listener_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolume) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -15811,112 +16719,130 @@ func (vpc *VpcV1) CreateVolumeWithContext(ctx context.Context, createVolumeOptio return } -// DeleteVolume : Delete a volume -// This request deletes a volume. This operation cannot be reversed. For this request to succeed, the volume must not be -// attached to any instances. -func (vpc *VpcV1) DeleteVolume(deleteVolumeOptions *DeleteVolumeOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVolumeWithContext(context.Background(), deleteVolumeOptions) +// UpdateLoadBalancerListenerPolicy : Update a load balancer listener policy +// This request updates a load balancer listener policy with the information in a provided policy patch. The policy +// patch object is structured in the same way as a retrieved policy and contains only the information to be updated. +func (vpc *VpcV1) UpdateLoadBalancerListenerPolicy(updateLoadBalancerListenerPolicyOptions *UpdateLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateLoadBalancerListenerPolicyWithContext(context.Background(), updateLoadBalancerListenerPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVolumeWithContext is an alternate form of the DeleteVolume method which supports a Context parameter -func (vpc *VpcV1) DeleteVolumeWithContext(ctx context.Context, deleteVolumeOptions *DeleteVolumeOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVolumeOptions, "deleteVolumeOptions cannot be nil") +// UpdateLoadBalancerListenerPolicyWithContext is an alternate form of the UpdateLoadBalancerListenerPolicy method which supports a Context parameter +func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyWithContext(ctx context.Context, updateLoadBalancerListenerPolicyOptions *UpdateLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateLoadBalancerListenerPolicyOptions, "updateLoadBalancerListenerPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVolumeOptions, "deleteVolumeOptions") + err = core.ValidateStruct(updateLoadBalancerListenerPolicyOptions, "updateLoadBalancerListenerPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteVolumeOptions.ID, + "load_balancer_id": *updateLoadBalancerListenerPolicyOptions.LoadBalancerID, + "listener_id": *updateLoadBalancerListenerPolicyOptions.ListenerID, + "id": *updateLoadBalancerListenerPolicyOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVolumeOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerListenerPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVolume") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateLoadBalancerListenerPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } - if deleteVolumeOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteVolumeOptions.IfMatch)) - } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateLoadBalancerListenerPolicyOptions.LoadBalancerListenerPolicyPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_volume", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_load_balancer_listener_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicy) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetVolume : Retrieve a volume -// This request retrieves a single volume specified by the identifier in the URL. -func (vpc *VpcV1) GetVolume(getVolumeOptions *GetVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVolumeWithContext(context.Background(), getVolumeOptions) +// ListLoadBalancerListenerPolicyRules : List rules of a load balancer listener policy +// This request lists rules of a load balancer listener policy. +func (vpc *VpcV1) ListLoadBalancerListenerPolicyRules(listLoadBalancerListenerPolicyRulesOptions *ListLoadBalancerListenerPolicyRulesOptions) (result *LoadBalancerListenerPolicyRuleCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListLoadBalancerListenerPolicyRulesWithContext(context.Background(), listLoadBalancerListenerPolicyRulesOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVolumeWithContext is an alternate form of the GetVolume method which supports a Context parameter -func (vpc *VpcV1) GetVolumeWithContext(ctx context.Context, getVolumeOptions *GetVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVolumeOptions, "getVolumeOptions cannot be nil") +// ListLoadBalancerListenerPolicyRulesWithContext is an alternate form of the ListLoadBalancerListenerPolicyRules method which supports a Context parameter +func (vpc *VpcV1) ListLoadBalancerListenerPolicyRulesWithContext(ctx context.Context, listLoadBalancerListenerPolicyRulesOptions *ListLoadBalancerListenerPolicyRulesOptions) (result *LoadBalancerListenerPolicyRuleCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listLoadBalancerListenerPolicyRulesOptions, "listLoadBalancerListenerPolicyRulesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVolumeOptions, "getVolumeOptions") + err = core.ValidateStruct(listLoadBalancerListenerPolicyRulesOptions, "listLoadBalancerListenerPolicyRulesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getVolumeOptions.ID, + "load_balancer_id": *listLoadBalancerListenerPolicyRulesOptions.LoadBalancerID, + "listener_id": *listLoadBalancerListenerPolicyRulesOptions.ListenerID, + "policy_id": *listLoadBalancerListenerPolicyRulesOptions.PolicyID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVolumeOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerListenerPolicyRules") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVolume") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listLoadBalancerListenerPolicyRulesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -15933,12 +16859,12 @@ func (vpc *VpcV1) GetVolumeWithContext(ctx context.Context, getVolumeOptions *Ge var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_volume", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_load_balancer_listener_policy_rules", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolume) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyRuleCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -15949,59 +16875,70 @@ func (vpc *VpcV1) GetVolumeWithContext(ctx context.Context, getVolumeOptions *Ge return } -// UpdateVolume : Update a volume -// This request updates a volume with the information in a provided volume patch. The volume patch object is structured -// in the same way as a retrieved volume and contains only the information to be updated. -func (vpc *VpcV1) UpdateVolume(updateVolumeOptions *UpdateVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVolumeWithContext(context.Background(), updateVolumeOptions) +// CreateLoadBalancerListenerPolicyRule : Create a rule for a load balancer listener policy +// Creates a new rule for the load balancer listener policy. +func (vpc *VpcV1) CreateLoadBalancerListenerPolicyRule(createLoadBalancerListenerPolicyRuleOptions *CreateLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateLoadBalancerListenerPolicyRuleWithContext(context.Background(), createLoadBalancerListenerPolicyRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVolumeWithContext is an alternate form of the UpdateVolume method which supports a Context parameter -func (vpc *VpcV1) UpdateVolumeWithContext(ctx context.Context, updateVolumeOptions *UpdateVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVolumeOptions, "updateVolumeOptions cannot be nil") +// CreateLoadBalancerListenerPolicyRuleWithContext is an alternate form of the CreateLoadBalancerListenerPolicyRule method which supports a Context parameter +func (vpc *VpcV1) CreateLoadBalancerListenerPolicyRuleWithContext(ctx context.Context, createLoadBalancerListenerPolicyRuleOptions *CreateLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createLoadBalancerListenerPolicyRuleOptions, "createLoadBalancerListenerPolicyRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVolumeOptions, "updateVolumeOptions") + err = core.ValidateStruct(createLoadBalancerListenerPolicyRuleOptions, "createLoadBalancerListenerPolicyRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateVolumeOptions.ID, + "load_balancer_id": *createLoadBalancerListenerPolicyRuleOptions.LoadBalancerID, + "listener_id": *createLoadBalancerListenerPolicyRuleOptions.ListenerID, + "policy_id": *createLoadBalancerListenerPolicyRuleOptions.PolicyID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVolumeOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerListenerPolicyRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVolume") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createLoadBalancerListenerPolicyRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateVolumeOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateVolumeOptions.IfMatch)) - } + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVolumeOptions.VolumePatch) + body := make(map[string]interface{}) + if createLoadBalancerListenerPolicyRuleOptions.Condition != nil { + body["condition"] = createLoadBalancerListenerPolicyRuleOptions.Condition + } + if createLoadBalancerListenerPolicyRuleOptions.Type != nil { + body["type"] = createLoadBalancerListenerPolicyRuleOptions.Type + } + if createLoadBalancerListenerPolicyRuleOptions.Value != nil { + body["value"] = createLoadBalancerListenerPolicyRuleOptions.Value + } + if createLoadBalancerListenerPolicyRuleOptions.Field != nil { + body["field"] = createLoadBalancerListenerPolicyRuleOptions.Field + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -16016,12 +16953,12 @@ func (vpc *VpcV1) UpdateVolumeWithContext(ctx context.Context, updateVolumeOptio var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_volume", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_load_balancer_listener_policy_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolume) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyRule) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16032,62 +16969,54 @@ func (vpc *VpcV1) UpdateVolumeWithContext(ctx context.Context, updateVolumeOptio return } -// ListSnapshotConsistencyGroups : List snapshot consistency groups -// This request lists snapshot consistency groups in the region. A snapshot consistency group is a collection of -// individual snapshots taken at the same time. -func (vpc *VpcV1) ListSnapshotConsistencyGroups(listSnapshotConsistencyGroupsOptions *ListSnapshotConsistencyGroupsOptions) (result *SnapshotConsistencyGroupCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSnapshotConsistencyGroupsWithContext(context.Background(), listSnapshotConsistencyGroupsOptions) +// DeleteLoadBalancerListenerPolicyRule : Delete a load balancer listener policy rule +// Deletes a rule from the load balancer listener policy. This operation cannot be reversed. +func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyRule(deleteLoadBalancerListenerPolicyRuleOptions *DeleteLoadBalancerListenerPolicyRuleOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteLoadBalancerListenerPolicyRuleWithContext(context.Background(), deleteLoadBalancerListenerPolicyRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSnapshotConsistencyGroupsWithContext is an alternate form of the ListSnapshotConsistencyGroups method which supports a Context parameter -func (vpc *VpcV1) ListSnapshotConsistencyGroupsWithContext(ctx context.Context, listSnapshotConsistencyGroupsOptions *ListSnapshotConsistencyGroupsOptions) (result *SnapshotConsistencyGroupCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listSnapshotConsistencyGroupsOptions, "listSnapshotConsistencyGroupsOptions") +// DeleteLoadBalancerListenerPolicyRuleWithContext is an alternate form of the DeleteLoadBalancerListenerPolicyRule method which supports a Context parameter +func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyRuleWithContext(ctx context.Context, deleteLoadBalancerListenerPolicyRuleOptions *DeleteLoadBalancerListenerPolicyRuleOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteLoadBalancerListenerPolicyRuleOptions, "deleteLoadBalancerListenerPolicyRuleOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteLoadBalancerListenerPolicyRuleOptions, "deleteLoadBalancerListenerPolicyRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "load_balancer_id": *deleteLoadBalancerListenerPolicyRuleOptions.LoadBalancerID, + "listener_id": *deleteLoadBalancerListenerPolicyRuleOptions.ListenerID, + "policy_id": *deleteLoadBalancerListenerPolicyRuleOptions.PolicyID, + "id": *deleteLoadBalancerListenerPolicyRuleOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSnapshotConsistencyGroupsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerListenerPolicyRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSnapshotConsistencyGroups") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteLoadBalancerListenerPolicyRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listSnapshotConsistencyGroupsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.Start)) - } - if listSnapshotConsistencyGroupsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.Limit)) - } - if listSnapshotConsistencyGroupsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.ResourceGroupID)) - } - if listSnapshotConsistencyGroupsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.Name)) - } - if listSnapshotConsistencyGroupsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.Sort)) - } - if listSnapshotConsistencyGroupsOptions.BackupPolicyPlanID != nil { - builder.AddQuery("backup_policy_plan.id", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.BackupPolicyPlanID)) - } request, err := builder.Build() if err != nil { @@ -16095,77 +17024,66 @@ func (vpc *VpcV1) ListSnapshotConsistencyGroupsWithContext(ctx context.Context, return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_snapshot_consistency_groups", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_load_balancer_listener_policy_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroupCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateSnapshotConsistencyGroup : Create a snapshot consistency group -// This request creates a new snapshot consistency group from a snapshot consistency group object. The prototype object -// is structured in the same way as a retrieved consistency group, and contains the information necessary to provision -// the new snapshot consistency group. -func (vpc *VpcV1) CreateSnapshotConsistencyGroup(createSnapshotConsistencyGroupOptions *CreateSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateSnapshotConsistencyGroupWithContext(context.Background(), createSnapshotConsistencyGroupOptions) +// GetLoadBalancerListenerPolicyRule : Retrieve a load balancer listener policy rule +// Retrieves a single rule specified by the identifier in the URL path. +func (vpc *VpcV1) GetLoadBalancerListenerPolicyRule(getLoadBalancerListenerPolicyRuleOptions *GetLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetLoadBalancerListenerPolicyRuleWithContext(context.Background(), getLoadBalancerListenerPolicyRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateSnapshotConsistencyGroupWithContext is an alternate form of the CreateSnapshotConsistencyGroup method which supports a Context parameter -func (vpc *VpcV1) CreateSnapshotConsistencyGroupWithContext(ctx context.Context, createSnapshotConsistencyGroupOptions *CreateSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createSnapshotConsistencyGroupOptions, "createSnapshotConsistencyGroupOptions cannot be nil") +// GetLoadBalancerListenerPolicyRuleWithContext is an alternate form of the GetLoadBalancerListenerPolicyRule method which supports a Context parameter +func (vpc *VpcV1) GetLoadBalancerListenerPolicyRuleWithContext(ctx context.Context, getLoadBalancerListenerPolicyRuleOptions *GetLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLoadBalancerListenerPolicyRuleOptions, "getLoadBalancerListenerPolicyRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createSnapshotConsistencyGroupOptions, "createSnapshotConsistencyGroupOptions") + err = core.ValidateStruct(getLoadBalancerListenerPolicyRuleOptions, "getLoadBalancerListenerPolicyRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "load_balancer_id": *getLoadBalancerListenerPolicyRuleOptions.LoadBalancerID, + "listener_id": *getLoadBalancerListenerPolicyRuleOptions.ListenerID, + "policy_id": *getLoadBalancerListenerPolicyRuleOptions.PolicyID, + "id": *getLoadBalancerListenerPolicyRuleOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createSnapshotConsistencyGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerListenerPolicyRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSnapshotConsistencyGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLoadBalancerListenerPolicyRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createSnapshotConsistencyGroupOptions.SnapshotConsistencyGroupPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -16175,12 +17093,12 @@ func (vpc *VpcV1) CreateSnapshotConsistencyGroupWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_snapshot_consistency_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_load_balancer_listener_policy_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyRule) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16191,54 +17109,63 @@ func (vpc *VpcV1) CreateSnapshotConsistencyGroupWithContext(ctx context.Context, return } -// DeleteSnapshotConsistencyGroup : Delete a snapshot consistency group -// This request deletes snapshot consistency group. This operation cannot be reversed. If the -// `delete_snapshots_on_delete` property is `true`, all snapshots in the consistency group will also be deleted. -func (vpc *VpcV1) DeleteSnapshotConsistencyGroup(deleteSnapshotConsistencyGroupOptions *DeleteSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteSnapshotConsistencyGroupWithContext(context.Background(), deleteSnapshotConsistencyGroupOptions) +// UpdateLoadBalancerListenerPolicyRule : Update a load balancer listener policy rule +// Updates a rule of the load balancer listener policy. +func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyRule(updateLoadBalancerListenerPolicyRuleOptions *UpdateLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateLoadBalancerListenerPolicyRuleWithContext(context.Background(), updateLoadBalancerListenerPolicyRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSnapshotConsistencyGroupWithContext is an alternate form of the DeleteSnapshotConsistencyGroup method which supports a Context parameter -func (vpc *VpcV1) DeleteSnapshotConsistencyGroupWithContext(ctx context.Context, deleteSnapshotConsistencyGroupOptions *DeleteSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSnapshotConsistencyGroupOptions, "deleteSnapshotConsistencyGroupOptions cannot be nil") +// UpdateLoadBalancerListenerPolicyRuleWithContext is an alternate form of the UpdateLoadBalancerListenerPolicyRule method which supports a Context parameter +func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyRuleWithContext(ctx context.Context, updateLoadBalancerListenerPolicyRuleOptions *UpdateLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateLoadBalancerListenerPolicyRuleOptions, "updateLoadBalancerListenerPolicyRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSnapshotConsistencyGroupOptions, "deleteSnapshotConsistencyGroupOptions") + err = core.ValidateStruct(updateLoadBalancerListenerPolicyRuleOptions, "updateLoadBalancerListenerPolicyRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteSnapshotConsistencyGroupOptions.ID, + "load_balancer_id": *updateLoadBalancerListenerPolicyRuleOptions.LoadBalancerID, + "listener_id": *updateLoadBalancerListenerPolicyRuleOptions.ListenerID, + "policy_id": *updateLoadBalancerListenerPolicyRuleOptions.PolicyID, + "id": *updateLoadBalancerListenerPolicyRuleOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSnapshotConsistencyGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerListenerPolicyRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSnapshotConsistencyGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateLoadBalancerListenerPolicyRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateLoadBalancerListenerPolicyRuleOptions.LoadBalancerListenerPolicyRulePatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -16248,12 +17175,12 @@ func (vpc *VpcV1) DeleteSnapshotConsistencyGroupWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_snapshot_consistency_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_load_balancer_listener_policy_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyRule) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16264,46 +17191,46 @@ func (vpc *VpcV1) DeleteSnapshotConsistencyGroupWithContext(ctx context.Context, return } -// GetSnapshotConsistencyGroup : Retrieve a snapshot consistency group -// This request retrieves a single snapshot consistency group specified by the identifier in the URL. -func (vpc *VpcV1) GetSnapshotConsistencyGroup(getSnapshotConsistencyGroupOptions *GetSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSnapshotConsistencyGroupWithContext(context.Background(), getSnapshotConsistencyGroupOptions) +// ListLoadBalancerPools : List pools of a load balancer +// This request lists pools of a load balancer. +func (vpc *VpcV1) ListLoadBalancerPools(listLoadBalancerPoolsOptions *ListLoadBalancerPoolsOptions) (result *LoadBalancerPoolCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListLoadBalancerPoolsWithContext(context.Background(), listLoadBalancerPoolsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSnapshotConsistencyGroupWithContext is an alternate form of the GetSnapshotConsistencyGroup method which supports a Context parameter -func (vpc *VpcV1) GetSnapshotConsistencyGroupWithContext(ctx context.Context, getSnapshotConsistencyGroupOptions *GetSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSnapshotConsistencyGroupOptions, "getSnapshotConsistencyGroupOptions cannot be nil") +// ListLoadBalancerPoolsWithContext is an alternate form of the ListLoadBalancerPools method which supports a Context parameter +func (vpc *VpcV1) ListLoadBalancerPoolsWithContext(ctx context.Context, listLoadBalancerPoolsOptions *ListLoadBalancerPoolsOptions) (result *LoadBalancerPoolCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listLoadBalancerPoolsOptions, "listLoadBalancerPoolsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSnapshotConsistencyGroupOptions, "getSnapshotConsistencyGroupOptions") + err = core.ValidateStruct(listLoadBalancerPoolsOptions, "listLoadBalancerPoolsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getSnapshotConsistencyGroupOptions.ID, + "load_balancer_id": *listLoadBalancerPoolsOptions.LoadBalancerID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSnapshotConsistencyGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerPools") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSnapshotConsistencyGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listLoadBalancerPoolsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -16320,12 +17247,12 @@ func (vpc *VpcV1) GetSnapshotConsistencyGroupWithContext(ctx context.Context, ge var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_snapshot_consistency_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_load_balancer_pools", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16336,60 +17263,80 @@ func (vpc *VpcV1) GetSnapshotConsistencyGroupWithContext(ctx context.Context, ge return } -// UpdateSnapshotConsistencyGroup : Update a snapshot consistency group -// This request updates a snapshot consistency group with the information in a provided snapshot consistency group -// patch. The snapshot consistency group patch object is structured in the same way as a retrieved snapshot consistency -// group and contains only the information to be updated. -func (vpc *VpcV1) UpdateSnapshotConsistencyGroup(updateSnapshotConsistencyGroupOptions *UpdateSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateSnapshotConsistencyGroupWithContext(context.Background(), updateSnapshotConsistencyGroupOptions) +// CreateLoadBalancerPool : Create a load balancer pool +// This request creates a new pool from a pool prototype object. +func (vpc *VpcV1) CreateLoadBalancerPool(createLoadBalancerPoolOptions *CreateLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateLoadBalancerPoolWithContext(context.Background(), createLoadBalancerPoolOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateSnapshotConsistencyGroupWithContext is an alternate form of the UpdateSnapshotConsistencyGroup method which supports a Context parameter -func (vpc *VpcV1) UpdateSnapshotConsistencyGroupWithContext(ctx context.Context, updateSnapshotConsistencyGroupOptions *UpdateSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateSnapshotConsistencyGroupOptions, "updateSnapshotConsistencyGroupOptions cannot be nil") +// CreateLoadBalancerPoolWithContext is an alternate form of the CreateLoadBalancerPool method which supports a Context parameter +func (vpc *VpcV1) CreateLoadBalancerPoolWithContext(ctx context.Context, createLoadBalancerPoolOptions *CreateLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createLoadBalancerPoolOptions, "createLoadBalancerPoolOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateSnapshotConsistencyGroupOptions, "updateSnapshotConsistencyGroupOptions") + err = core.ValidateStruct(createLoadBalancerPoolOptions, "createLoadBalancerPoolOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateSnapshotConsistencyGroupOptions.ID, + "load_balancer_id": *createLoadBalancerPoolOptions.LoadBalancerID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateSnapshotConsistencyGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerPool") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSnapshotConsistencyGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createLoadBalancerPoolOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateSnapshotConsistencyGroupOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateSnapshotConsistencyGroupOptions.IfMatch)) - } + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateSnapshotConsistencyGroupOptions.SnapshotConsistencyGroupPatch) + body := make(map[string]interface{}) + if createLoadBalancerPoolOptions.Algorithm != nil { + body["algorithm"] = createLoadBalancerPoolOptions.Algorithm + } + if createLoadBalancerPoolOptions.HealthMonitor != nil { + body["health_monitor"] = createLoadBalancerPoolOptions.HealthMonitor + } + if createLoadBalancerPoolOptions.Protocol != nil { + body["protocol"] = createLoadBalancerPoolOptions.Protocol + } + if createLoadBalancerPoolOptions.FailsafePolicy != nil { + body["failsafe_policy"] = createLoadBalancerPoolOptions.FailsafePolicy + } + if createLoadBalancerPoolOptions.Members != nil { + body["members"] = createLoadBalancerPoolOptions.Members + } + if createLoadBalancerPoolOptions.Name != nil { + body["name"] = createLoadBalancerPoolOptions.Name + } + if createLoadBalancerPoolOptions.ProxyProtocol != nil { + body["proxy_protocol"] = createLoadBalancerPoolOptions.ProxyProtocol + } + if createLoadBalancerPoolOptions.SessionPersistence != nil { + body["session_persistence"] = createLoadBalancerPoolOptions.SessionPersistence + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -16404,12 +17351,12 @@ func (vpc *VpcV1) UpdateSnapshotConsistencyGroupWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_snapshot_consistency_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_load_balancer_pool", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPool) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16420,48 +17367,53 @@ func (vpc *VpcV1) UpdateSnapshotConsistencyGroupWithContext(ctx context.Context, return } -// DeleteSnapshots : Delete a filtered collection of snapshots -// This request deletes snapshots that match the specified filter. This operation cannot be reversed. -func (vpc *VpcV1) DeleteSnapshots(deleteSnapshotsOptions *DeleteSnapshotsOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteSnapshotsWithContext(context.Background(), deleteSnapshotsOptions) +// DeleteLoadBalancerPool : Delete a load balancer pool +// This request deletes a load balancer pool. This operation cannot be reversed. The pool must not currently be the +// default pool for any listener in the load balancer, nor be the target pool in the failsafe policy for any other pool. +func (vpc *VpcV1) DeleteLoadBalancerPool(deleteLoadBalancerPoolOptions *DeleteLoadBalancerPoolOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteLoadBalancerPoolWithContext(context.Background(), deleteLoadBalancerPoolOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSnapshotsWithContext is an alternate form of the DeleteSnapshots method which supports a Context parameter -func (vpc *VpcV1) DeleteSnapshotsWithContext(ctx context.Context, deleteSnapshotsOptions *DeleteSnapshotsOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSnapshotsOptions, "deleteSnapshotsOptions cannot be nil") +// DeleteLoadBalancerPoolWithContext is an alternate form of the DeleteLoadBalancerPool method which supports a Context parameter +func (vpc *VpcV1) DeleteLoadBalancerPoolWithContext(ctx context.Context, deleteLoadBalancerPoolOptions *DeleteLoadBalancerPoolOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteLoadBalancerPoolOptions, "deleteLoadBalancerPoolOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSnapshotsOptions, "deleteSnapshotsOptions") + err = core.ValidateStruct(deleteLoadBalancerPoolOptions, "deleteLoadBalancerPoolOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "load_balancer_id": *deleteLoadBalancerPoolOptions.LoadBalancerID, + "id": *deleteLoadBalancerPoolOptions.ID, + } + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSnapshotsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerPool") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSnapshots") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteLoadBalancerPoolOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - builder.AddQuery("source_volume.id", fmt.Sprint(*deleteSnapshotsOptions.SourceVolumeID)) request, err := builder.Build() if err != nil { @@ -16471,7 +17423,7 @@ func (vpc *VpcV1) DeleteSnapshotsWithContext(ctx context.Context, deleteSnapshot response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_snapshots", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_load_balancer_pool", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -16479,110 +17431,53 @@ func (vpc *VpcV1) DeleteSnapshotsWithContext(ctx context.Context, deleteSnapshot return } -// ListSnapshots : List snapshots -// This request lists snapshots in the region. A snapshot preserves the data of a volume at the time the snapshot is -// created. -func (vpc *VpcV1) ListSnapshots(listSnapshotsOptions *ListSnapshotsOptions) (result *SnapshotCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSnapshotsWithContext(context.Background(), listSnapshotsOptions) +// GetLoadBalancerPool : Retrieve a load balancer pool +// This request retrieves a single pool specified by the identifier in the URL path. +func (vpc *VpcV1) GetLoadBalancerPool(getLoadBalancerPoolOptions *GetLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetLoadBalancerPoolWithContext(context.Background(), getLoadBalancerPoolOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSnapshotsWithContext is an alternate form of the ListSnapshots method which supports a Context parameter -func (vpc *VpcV1) ListSnapshotsWithContext(ctx context.Context, listSnapshotsOptions *ListSnapshotsOptions) (result *SnapshotCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listSnapshotsOptions, "listSnapshotsOptions") +// GetLoadBalancerPoolWithContext is an alternate form of the GetLoadBalancerPool method which supports a Context parameter +func (vpc *VpcV1) GetLoadBalancerPoolWithContext(ctx context.Context, getLoadBalancerPoolOptions *GetLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLoadBalancerPoolOptions, "getLoadBalancerPoolOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getLoadBalancerPoolOptions, "getLoadBalancerPoolOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "load_balancer_id": *getLoadBalancerPoolOptions.LoadBalancerID, + "id": *getLoadBalancerPoolOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSnapshotsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerPool") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSnapshots") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLoadBalancerPoolOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listSnapshotsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listSnapshotsOptions.Start)) - } - if listSnapshotsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listSnapshotsOptions.Limit)) - } - if listSnapshotsOptions.Tag != nil { - builder.AddQuery("tag", fmt.Sprint(*listSnapshotsOptions.Tag)) - } - if listSnapshotsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listSnapshotsOptions.ResourceGroupID)) - } - if listSnapshotsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listSnapshotsOptions.Name)) - } - if listSnapshotsOptions.SourceVolumeID != nil { - builder.AddQuery("source_volume.id", fmt.Sprint(*listSnapshotsOptions.SourceVolumeID)) - } - if listSnapshotsOptions.SourceVolumeCRN != nil { - builder.AddQuery("source_volume.crn", fmt.Sprint(*listSnapshotsOptions.SourceVolumeCRN)) - } - if listSnapshotsOptions.SourceImageID != nil { - builder.AddQuery("source_image.id", fmt.Sprint(*listSnapshotsOptions.SourceImageID)) - } - if listSnapshotsOptions.SourceImageCRN != nil { - builder.AddQuery("source_image.crn", fmt.Sprint(*listSnapshotsOptions.SourceImageCRN)) - } - if listSnapshotsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listSnapshotsOptions.Sort)) - } - if listSnapshotsOptions.BackupPolicyPlanID != nil { - builder.AddQuery("backup_policy_plan.id", fmt.Sprint(*listSnapshotsOptions.BackupPolicyPlanID)) - } - if listSnapshotsOptions.CopiesID != nil { - builder.AddQuery("copies[].id", fmt.Sprint(*listSnapshotsOptions.CopiesID)) - } - if listSnapshotsOptions.CopiesName != nil { - builder.AddQuery("copies[].name", fmt.Sprint(*listSnapshotsOptions.CopiesName)) - } - if listSnapshotsOptions.CopiesCRN != nil { - builder.AddQuery("copies[].crn", fmt.Sprint(*listSnapshotsOptions.CopiesCRN)) - } - if listSnapshotsOptions.CopiesRemoteRegionName != nil { - builder.AddQuery("copies[].remote.region.name", fmt.Sprint(*listSnapshotsOptions.CopiesRemoteRegionName)) - } - if listSnapshotsOptions.SourceSnapshotID != nil { - builder.AddQuery("source_snapshot.id", fmt.Sprint(*listSnapshotsOptions.SourceSnapshotID)) - } - if listSnapshotsOptions.SourceSnapshotRemoteRegionName != nil { - builder.AddQuery("source_snapshot.remote.region.name", fmt.Sprint(*listSnapshotsOptions.SourceSnapshotRemoteRegionName)) - } - if listSnapshotsOptions.SourceVolumeRemoteRegionName != nil { - builder.AddQuery("source_volume.remote.region.name", fmt.Sprint(*listSnapshotsOptions.SourceVolumeRemoteRegionName)) - } - if listSnapshotsOptions.SourceImageRemoteRegionName != nil { - builder.AddQuery("source_image.remote.region.name", fmt.Sprint(*listSnapshotsOptions.SourceImageRemoteRegionName)) - } - if listSnapshotsOptions.ClonesZoneName != nil { - builder.AddQuery("clones[].zone.name", fmt.Sprint(*listSnapshotsOptions.ClonesZoneName)) - } - if listSnapshotsOptions.SnapshotConsistencyGroupID != nil { - builder.AddQuery("snapshot_consistency_group.id", fmt.Sprint(*listSnapshotsOptions.SnapshotConsistencyGroupID)) - } - if listSnapshotsOptions.SnapshotConsistencyGroupCRN != nil { - builder.AddQuery("snapshot_consistency_group.crn", fmt.Sprint(*listSnapshotsOptions.SnapshotConsistencyGroupCRN)) - } request, err := builder.Build() if err != nil { @@ -16593,12 +17488,12 @@ func (vpc *VpcV1) ListSnapshotsWithContext(ctx context.Context, listSnapshotsOpt var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_snapshots", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_load_balancer_pool", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPool) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16609,52 +17504,56 @@ func (vpc *VpcV1) ListSnapshotsWithContext(ctx context.Context, listSnapshotsOpt return } -// CreateSnapshot : Create a snapshot -// This request creates a new snapshot from a snapshot prototype object. The prototype object is structured in the same -// way as a retrieved snapshot, and contains the information necessary to provision the new snapshot. -func (vpc *VpcV1) CreateSnapshot(createSnapshotOptions *CreateSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateSnapshotWithContext(context.Background(), createSnapshotOptions) +// UpdateLoadBalancerPool : Update a load balancer pool +// This request updates a load balancer pool from a pool patch. +func (vpc *VpcV1) UpdateLoadBalancerPool(updateLoadBalancerPoolOptions *UpdateLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateLoadBalancerPoolWithContext(context.Background(), updateLoadBalancerPoolOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateSnapshotWithContext is an alternate form of the CreateSnapshot method which supports a Context parameter -func (vpc *VpcV1) CreateSnapshotWithContext(ctx context.Context, createSnapshotOptions *CreateSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createSnapshotOptions, "createSnapshotOptions cannot be nil") +// UpdateLoadBalancerPoolWithContext is an alternate form of the UpdateLoadBalancerPool method which supports a Context parameter +func (vpc *VpcV1) UpdateLoadBalancerPoolWithContext(ctx context.Context, updateLoadBalancerPoolOptions *UpdateLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateLoadBalancerPoolOptions, "updateLoadBalancerPoolOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createSnapshotOptions, "createSnapshotOptions") + err = core.ValidateStruct(updateLoadBalancerPoolOptions, "updateLoadBalancerPoolOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "load_balancer_id": *updateLoadBalancerPoolOptions.LoadBalancerID, + "id": *updateLoadBalancerPoolOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createSnapshotOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerPool") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSnapshot") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateLoadBalancerPoolOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createSnapshotOptions.SnapshotPrototype) + _, err = builder.SetBodyContentJSON(updateLoadBalancerPoolOptions.LoadBalancerPoolPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -16669,12 +17568,12 @@ func (vpc *VpcV1) CreateSnapshotWithContext(ctx context.Context, createSnapshotO var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_snapshot", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_load_balancer_pool", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshot) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPool) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16685,51 +17584,50 @@ func (vpc *VpcV1) CreateSnapshotWithContext(ctx context.Context, createSnapshotO return } -// DeleteSnapshot : Delete a snapshot -// This request deletes a snapshot. This operation cannot be reversed. -func (vpc *VpcV1) DeleteSnapshot(deleteSnapshotOptions *DeleteSnapshotOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteSnapshotWithContext(context.Background(), deleteSnapshotOptions) +// ListLoadBalancerPoolMembers : List members of a load balancer pool +// This request lists members of a load balancer pool. +func (vpc *VpcV1) ListLoadBalancerPoolMembers(listLoadBalancerPoolMembersOptions *ListLoadBalancerPoolMembersOptions) (result *LoadBalancerPoolMemberCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListLoadBalancerPoolMembersWithContext(context.Background(), listLoadBalancerPoolMembersOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSnapshotWithContext is an alternate form of the DeleteSnapshot method which supports a Context parameter -func (vpc *VpcV1) DeleteSnapshotWithContext(ctx context.Context, deleteSnapshotOptions *DeleteSnapshotOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSnapshotOptions, "deleteSnapshotOptions cannot be nil") +// ListLoadBalancerPoolMembersWithContext is an alternate form of the ListLoadBalancerPoolMembers method which supports a Context parameter +func (vpc *VpcV1) ListLoadBalancerPoolMembersWithContext(ctx context.Context, listLoadBalancerPoolMembersOptions *ListLoadBalancerPoolMembersOptions) (result *LoadBalancerPoolMemberCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listLoadBalancerPoolMembersOptions, "listLoadBalancerPoolMembersOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSnapshotOptions, "deleteSnapshotOptions") + err = core.ValidateStruct(listLoadBalancerPoolMembersOptions, "listLoadBalancerPoolMembersOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteSnapshotOptions.ID, + "load_balancer_id": *listLoadBalancerPoolMembersOptions.LoadBalancerID, + "pool_id": *listLoadBalancerPoolMembersOptions.PoolID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSnapshotOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerPoolMembers") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSnapshot") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listLoadBalancerPoolMembersOptions.Headers { builder.AddHeader(headerName, headerValue) } - if deleteSnapshotOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteSnapshotOptions.IfMatch)) - } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -16740,63 +17638,92 @@ func (vpc *VpcV1) DeleteSnapshotWithContext(ctx context.Context, deleteSnapshotO return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_snapshot", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_load_balancer_pool_members", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMemberCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetSnapshot : Retrieve a snapshot -// This request retrieves a single snapshot specified by the identifier in the URL. -func (vpc *VpcV1) GetSnapshot(getSnapshotOptions *GetSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSnapshotWithContext(context.Background(), getSnapshotOptions) +// CreateLoadBalancerPoolMember : Create a member in a load balancer pool +// This request creates a new member and adds the member to the pool. +// +// The pool must not already have a member targeting a load balancer. +func (vpc *VpcV1) CreateLoadBalancerPoolMember(createLoadBalancerPoolMemberOptions *CreateLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateLoadBalancerPoolMemberWithContext(context.Background(), createLoadBalancerPoolMemberOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSnapshotWithContext is an alternate form of the GetSnapshot method which supports a Context parameter -func (vpc *VpcV1) GetSnapshotWithContext(ctx context.Context, getSnapshotOptions *GetSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSnapshotOptions, "getSnapshotOptions cannot be nil") +// CreateLoadBalancerPoolMemberWithContext is an alternate form of the CreateLoadBalancerPoolMember method which supports a Context parameter +func (vpc *VpcV1) CreateLoadBalancerPoolMemberWithContext(ctx context.Context, createLoadBalancerPoolMemberOptions *CreateLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createLoadBalancerPoolMemberOptions, "createLoadBalancerPoolMemberOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSnapshotOptions, "getSnapshotOptions") + err = core.ValidateStruct(createLoadBalancerPoolMemberOptions, "createLoadBalancerPoolMemberOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getSnapshotOptions.ID, + "load_balancer_id": *createLoadBalancerPoolMemberOptions.LoadBalancerID, + "pool_id": *createLoadBalancerPoolMemberOptions.PoolID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSnapshotOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerPoolMember") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSnapshot") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createLoadBalancerPoolMemberOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createLoadBalancerPoolMemberOptions.Port != nil { + body["port"] = createLoadBalancerPoolMemberOptions.Port + } + if createLoadBalancerPoolMemberOptions.Target != nil { + body["target"] = createLoadBalancerPoolMemberOptions.Target + } + if createLoadBalancerPoolMemberOptions.Weight != nil { + body["weight"] = createLoadBalancerPoolMemberOptions.Weight + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -16806,12 +17733,12 @@ func (vpc *VpcV1) GetSnapshotWithContext(ctx context.Context, getSnapshotOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_snapshot", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_load_balancer_pool_member", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshot) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMember) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16822,59 +17749,61 @@ func (vpc *VpcV1) GetSnapshotWithContext(ctx context.Context, getSnapshotOptions return } -// UpdateSnapshot : Update a snapshot -// This request updates a snapshot with the information in a provided snapshot patch. The snapshot consistency group -// patch object is structured in the same way as a retrieved snapshot and contains only the information to be updated. -func (vpc *VpcV1) UpdateSnapshot(updateSnapshotOptions *UpdateSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateSnapshotWithContext(context.Background(), updateSnapshotOptions) +// ReplaceLoadBalancerPoolMembers : Replace load balancer pool members +// This request replaces the existing members of the load balancer pool with new members created from the collection of +// member prototype objects. +func (vpc *VpcV1) ReplaceLoadBalancerPoolMembers(replaceLoadBalancerPoolMembersOptions *ReplaceLoadBalancerPoolMembersOptions) (result *LoadBalancerPoolMemberCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ReplaceLoadBalancerPoolMembersWithContext(context.Background(), replaceLoadBalancerPoolMembersOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateSnapshotWithContext is an alternate form of the UpdateSnapshot method which supports a Context parameter -func (vpc *VpcV1) UpdateSnapshotWithContext(ctx context.Context, updateSnapshotOptions *UpdateSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateSnapshotOptions, "updateSnapshotOptions cannot be nil") +// ReplaceLoadBalancerPoolMembersWithContext is an alternate form of the ReplaceLoadBalancerPoolMembers method which supports a Context parameter +func (vpc *VpcV1) ReplaceLoadBalancerPoolMembersWithContext(ctx context.Context, replaceLoadBalancerPoolMembersOptions *ReplaceLoadBalancerPoolMembersOptions) (result *LoadBalancerPoolMemberCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(replaceLoadBalancerPoolMembersOptions, "replaceLoadBalancerPoolMembersOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateSnapshotOptions, "updateSnapshotOptions") + err = core.ValidateStruct(replaceLoadBalancerPoolMembersOptions, "replaceLoadBalancerPoolMembersOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateSnapshotOptions.ID, + "load_balancer_id": *replaceLoadBalancerPoolMembersOptions.LoadBalancerID, + "pool_id": *replaceLoadBalancerPoolMembersOptions.PoolID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateSnapshotOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ReplaceLoadBalancerPoolMembers") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSnapshot") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range replaceLoadBalancerPoolMembersOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateSnapshotOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateSnapshotOptions.IfMatch)) - } + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateSnapshotOptions.SnapshotPatch) + body := make(map[string]interface{}) + if replaceLoadBalancerPoolMembersOptions.Members != nil { + body["members"] = replaceLoadBalancerPoolMembersOptions.Members + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -16889,12 +17818,12 @@ func (vpc *VpcV1) UpdateSnapshotWithContext(ctx context.Context, updateSnapshotO var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_snapshot", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "replace_load_balancer_pool_members", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshot) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMemberCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -16905,49 +17834,50 @@ func (vpc *VpcV1) UpdateSnapshotWithContext(ctx context.Context, updateSnapshotO return } -// ListSnapshotClones : List clones for a snapshot -// This request lists clones for a snapshot. Use a clone to quickly restore a snapshot within the clone's zone. -func (vpc *VpcV1) ListSnapshotClones(listSnapshotClonesOptions *ListSnapshotClonesOptions) (result *SnapshotCloneCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSnapshotClonesWithContext(context.Background(), listSnapshotClonesOptions) +// DeleteLoadBalancerPoolMember : Delete a load balancer pool member +// This request deletes a member from the pool. This operation cannot be reversed. +func (vpc *VpcV1) DeleteLoadBalancerPoolMember(deleteLoadBalancerPoolMemberOptions *DeleteLoadBalancerPoolMemberOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteLoadBalancerPoolMemberWithContext(context.Background(), deleteLoadBalancerPoolMemberOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSnapshotClonesWithContext is an alternate form of the ListSnapshotClones method which supports a Context parameter -func (vpc *VpcV1) ListSnapshotClonesWithContext(ctx context.Context, listSnapshotClonesOptions *ListSnapshotClonesOptions) (result *SnapshotCloneCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listSnapshotClonesOptions, "listSnapshotClonesOptions cannot be nil") +// DeleteLoadBalancerPoolMemberWithContext is an alternate form of the DeleteLoadBalancerPoolMember method which supports a Context parameter +func (vpc *VpcV1) DeleteLoadBalancerPoolMemberWithContext(ctx context.Context, deleteLoadBalancerPoolMemberOptions *DeleteLoadBalancerPoolMemberOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteLoadBalancerPoolMemberOptions, "deleteLoadBalancerPoolMemberOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listSnapshotClonesOptions, "listSnapshotClonesOptions") + err = core.ValidateStruct(deleteLoadBalancerPoolMemberOptions, "deleteLoadBalancerPoolMemberOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *listSnapshotClonesOptions.ID, + "load_balancer_id": *deleteLoadBalancerPoolMemberOptions.LoadBalancerID, + "pool_id": *deleteLoadBalancerPoolMemberOptions.PoolID, + "id": *deleteLoadBalancerPoolMemberOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/clones`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSnapshotClonesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerPoolMember") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSnapshotClones") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteLoadBalancerPoolMemberOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -16958,69 +17888,61 @@ func (vpc *VpcV1) ListSnapshotClonesWithContext(ctx context.Context, listSnapsho return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_snapshot_clones", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_load_balancer_pool_member", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotCloneCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// DeleteSnapshotClone : Delete a snapshot clone -// This request deletes a snapshot clone. This operation cannot be reversed, but an equivalent clone may be recreated -// from the snapshot. -func (vpc *VpcV1) DeleteSnapshotClone(deleteSnapshotCloneOptions *DeleteSnapshotCloneOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteSnapshotCloneWithContext(context.Background(), deleteSnapshotCloneOptions) +// GetLoadBalancerPoolMember : Retrieve a load balancer pool member +// This request retrieves a single member specified by the identifier in the URL path. +func (vpc *VpcV1) GetLoadBalancerPoolMember(getLoadBalancerPoolMemberOptions *GetLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetLoadBalancerPoolMemberWithContext(context.Background(), getLoadBalancerPoolMemberOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSnapshotCloneWithContext is an alternate form of the DeleteSnapshotClone method which supports a Context parameter -func (vpc *VpcV1) DeleteSnapshotCloneWithContext(ctx context.Context, deleteSnapshotCloneOptions *DeleteSnapshotCloneOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSnapshotCloneOptions, "deleteSnapshotCloneOptions cannot be nil") +// GetLoadBalancerPoolMemberWithContext is an alternate form of the GetLoadBalancerPoolMember method which supports a Context parameter +func (vpc *VpcV1) GetLoadBalancerPoolMemberWithContext(ctx context.Context, getLoadBalancerPoolMemberOptions *GetLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLoadBalancerPoolMemberOptions, "getLoadBalancerPoolMemberOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSnapshotCloneOptions, "deleteSnapshotCloneOptions") + err = core.ValidateStruct(getLoadBalancerPoolMemberOptions, "getLoadBalancerPoolMemberOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteSnapshotCloneOptions.ID, - "zone_name": *deleteSnapshotCloneOptions.ZoneName, + "load_balancer_id": *getLoadBalancerPoolMemberOptions.LoadBalancerID, + "pool_id": *getLoadBalancerPoolMemberOptions.PoolID, + "id": *getLoadBalancerPoolMemberOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/clones/{zone_name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSnapshotCloneOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerPoolMember") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSnapshotClone") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getLoadBalancerPoolMemberOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -17031,64 +17953,81 @@ func (vpc *VpcV1) DeleteSnapshotCloneWithContext(ctx context.Context, deleteSnap return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_snapshot_clone", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_load_balancer_pool_member", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMember) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetSnapshotClone : Retrieve a snapshot clone -// This request retrieves a single clone specified by the snapshot identifier and zone name in the URL. -func (vpc *VpcV1) GetSnapshotClone(getSnapshotCloneOptions *GetSnapshotCloneOptions) (result *SnapshotClone, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSnapshotCloneWithContext(context.Background(), getSnapshotCloneOptions) +// UpdateLoadBalancerPoolMember : Update a load balancer pool member +// This request updates an existing member from a member patch. +func (vpc *VpcV1) UpdateLoadBalancerPoolMember(updateLoadBalancerPoolMemberOptions *UpdateLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateLoadBalancerPoolMemberWithContext(context.Background(), updateLoadBalancerPoolMemberOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSnapshotCloneWithContext is an alternate form of the GetSnapshotClone method which supports a Context parameter -func (vpc *VpcV1) GetSnapshotCloneWithContext(ctx context.Context, getSnapshotCloneOptions *GetSnapshotCloneOptions) (result *SnapshotClone, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSnapshotCloneOptions, "getSnapshotCloneOptions cannot be nil") +// UpdateLoadBalancerPoolMemberWithContext is an alternate form of the UpdateLoadBalancerPoolMember method which supports a Context parameter +func (vpc *VpcV1) UpdateLoadBalancerPoolMemberWithContext(ctx context.Context, updateLoadBalancerPoolMemberOptions *UpdateLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateLoadBalancerPoolMemberOptions, "updateLoadBalancerPoolMemberOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSnapshotCloneOptions, "getSnapshotCloneOptions") + err = core.ValidateStruct(updateLoadBalancerPoolMemberOptions, "updateLoadBalancerPoolMemberOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getSnapshotCloneOptions.ID, - "zone_name": *getSnapshotCloneOptions.ZoneName, + "load_balancer_id": *updateLoadBalancerPoolMemberOptions.LoadBalancerID, + "pool_id": *updateLoadBalancerPoolMemberOptions.PoolID, + "id": *updateLoadBalancerPoolMemberOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/clones/{zone_name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSnapshotCloneOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerPoolMember") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSnapshotClone") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateLoadBalancerPoolMemberOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateLoadBalancerPoolMemberOptions.LoadBalancerPoolMemberPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -17098,12 +18037,12 @@ func (vpc *VpcV1) GetSnapshotCloneWithContext(ctx context.Context, getSnapshotCl var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_snapshot_clone", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_load_balancer_pool_member", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotClone) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMember) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17114,54 +18053,55 @@ func (vpc *VpcV1) GetSnapshotCloneWithContext(ctx context.Context, getSnapshotCl return } -// CreateSnapshotClone : Create a clone for a snapshot -// This request creates a new clone for a snapshot in the specified zone. A request body is not required, and if -// provided, is ignored. If the snapshot already has a clone in the zone, it is returned. -func (vpc *VpcV1) CreateSnapshotClone(createSnapshotCloneOptions *CreateSnapshotCloneOptions) (result *SnapshotClone, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateSnapshotCloneWithContext(context.Background(), createSnapshotCloneOptions) +// ListNetworkAcls : List network ACLs +// This request lists network ACLs in the region. A network ACL defines a set of packet filtering rules for traffic in +// and out of the subnets the network ACL is attached to. No traffic is allowed by default. Both allow and deny rules +// can be defined, and rules are stateless so that reverse traffic in response to allowed traffic is not automatically +// allowed. +func (vpc *VpcV1) ListNetworkAcls(listNetworkAclsOptions *ListNetworkAclsOptions) (result *NetworkACLCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListNetworkAclsWithContext(context.Background(), listNetworkAclsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateSnapshotCloneWithContext is an alternate form of the CreateSnapshotClone method which supports a Context parameter -func (vpc *VpcV1) CreateSnapshotCloneWithContext(ctx context.Context, createSnapshotCloneOptions *CreateSnapshotCloneOptions) (result *SnapshotClone, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createSnapshotCloneOptions, "createSnapshotCloneOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(createSnapshotCloneOptions, "createSnapshotCloneOptions") +// ListNetworkAclsWithContext is an alternate form of the ListNetworkAcls method which supports a Context parameter +func (vpc *VpcV1) ListNetworkAclsWithContext(ctx context.Context, listNetworkAclsOptions *ListNetworkAclsOptions) (result *NetworkACLCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listNetworkAclsOptions, "listNetworkAclsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *createSnapshotCloneOptions.ID, - "zone_name": *createSnapshotCloneOptions.ZoneName, - } - - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/clones/{zone_name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createSnapshotCloneOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListNetworkAcls") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSnapshotClone") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listNetworkAclsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listNetworkAclsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listNetworkAclsOptions.Start)) + } + if listNetworkAclsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listNetworkAclsOptions.Limit)) + } + if listNetworkAclsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listNetworkAclsOptions.ResourceGroupID)) + } request, err := builder.Build() if err != nil { @@ -17172,12 +18112,12 @@ func (vpc *VpcV1) CreateSnapshotCloneWithContext(ctx context.Context, createSnap var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_snapshot_clone", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_network_acls", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotClone) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17188,52 +18128,56 @@ func (vpc *VpcV1) CreateSnapshotCloneWithContext(ctx context.Context, createSnap return } -// ListShareProfiles : List file share profiles -// This request lists [file share profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-file-storage-profiles) available in -// the region. A file share profile specifies the performance characteristics and pricing model for a file share. -func (vpc *VpcV1) ListShareProfiles(listShareProfilesOptions *ListShareProfilesOptions) (result *ShareProfileCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListShareProfilesWithContext(context.Background(), listShareProfilesOptions) +// CreateNetworkACL : Create a network ACL +// This request creates a new stateless network ACL from a network ACL prototype object. The prototype object is +// structured in the same way as a retrieved network ACL, and contains the information necessary to create the new +// network ACL. +func (vpc *VpcV1) CreateNetworkACL(createNetworkACLOptions *CreateNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateNetworkACLWithContext(context.Background(), createNetworkACLOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListShareProfilesWithContext is an alternate form of the ListShareProfiles method which supports a Context parameter -func (vpc *VpcV1) ListShareProfilesWithContext(ctx context.Context, listShareProfilesOptions *ListShareProfilesOptions) (result *ShareProfileCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listShareProfilesOptions, "listShareProfilesOptions") +// CreateNetworkACLWithContext is an alternate form of the CreateNetworkACL method which supports a Context parameter +func (vpc *VpcV1) CreateNetworkACLWithContext(ctx context.Context, createNetworkACLOptions *CreateNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createNetworkACLOptions, "createNetworkACLOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(createNetworkACLOptions, "createNetworkACLOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/share/profiles`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listShareProfilesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateNetworkACL") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShareProfiles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createNetworkACLOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listShareProfilesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listShareProfilesOptions.Start)) - } - if listShareProfilesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listShareProfilesOptions.Limit)) - } - if listShareProfilesOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listShareProfilesOptions.Sort)) + + _, err = builder.SetBodyContentJSON(createNetworkACLOptions.NetworkACLPrototype) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -17245,12 +18189,12 @@ func (vpc *VpcV1) ListShareProfilesWithContext(ctx context.Context, listSharePro var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_share_profiles", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_network_acl", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareProfileCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17261,49 +18205,49 @@ func (vpc *VpcV1) ListShareProfilesWithContext(ctx context.Context, listSharePro return } -// GetShareProfile : Retrieve a file share profile -// This request retrieves a single file share profile specified by the name in the URL. -func (vpc *VpcV1) GetShareProfile(getShareProfileOptions *GetShareProfileOptions) (result *ShareProfile, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetShareProfileWithContext(context.Background(), getShareProfileOptions) +// DeleteNetworkACL : Delete a network ACL +// This request deletes a network ACL. This operation cannot be reversed. For this request to succeed, the network ACL +// must not be the default network ACL for any VPCs, and the network ACL must not be attached to any subnets. +func (vpc *VpcV1) DeleteNetworkACL(deleteNetworkACLOptions *DeleteNetworkACLOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteNetworkACLWithContext(context.Background(), deleteNetworkACLOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetShareProfileWithContext is an alternate form of the GetShareProfile method which supports a Context parameter -func (vpc *VpcV1) GetShareProfileWithContext(ctx context.Context, getShareProfileOptions *GetShareProfileOptions) (result *ShareProfile, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getShareProfileOptions, "getShareProfileOptions cannot be nil") +// DeleteNetworkACLWithContext is an alternate form of the DeleteNetworkACL method which supports a Context parameter +func (vpc *VpcV1) DeleteNetworkACLWithContext(ctx context.Context, deleteNetworkACLOptions *DeleteNetworkACLOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteNetworkACLOptions, "deleteNetworkACLOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getShareProfileOptions, "getShareProfileOptions") + err = core.ValidateStruct(deleteNetworkACLOptions, "deleteNetworkACLOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "name": *getShareProfileOptions.Name, + "id": *deleteNetworkACLOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/share/profiles/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getShareProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteNetworkACL") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteNetworkACLOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -17314,80 +18258,62 @@ func (vpc *VpcV1) GetShareProfileWithContext(ctx context.Context, getShareProfil return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_share_profile", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_network_acl", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareProfile) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListShares : List file shares -// This request lists file shares in the region. -func (vpc *VpcV1) ListShares(listSharesOptions *ListSharesOptions) (result *ShareCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSharesWithContext(context.Background(), listSharesOptions) +// GetNetworkACL : Retrieve a network ACL +// This request retrieves a single network ACL specified by the identifier in the URL. +func (vpc *VpcV1) GetNetworkACL(getNetworkACLOptions *GetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetNetworkACLWithContext(context.Background(), getNetworkACLOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSharesWithContext is an alternate form of the ListShares method which supports a Context parameter -func (vpc *VpcV1) ListSharesWithContext(ctx context.Context, listSharesOptions *ListSharesOptions) (result *ShareCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listSharesOptions, "listSharesOptions") +// GetNetworkACLWithContext is an alternate form of the GetNetworkACL method which supports a Context parameter +func (vpc *VpcV1) GetNetworkACLWithContext(ctx context.Context, getNetworkACLOptions *GetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getNetworkACLOptions, "getNetworkACLOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getNetworkACLOptions, "getNetworkACLOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "id": *getNetworkACLOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSharesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetNetworkACL") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShares") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getNetworkACLOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listSharesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listSharesOptions.Start)) - } - if listSharesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listSharesOptions.Limit)) - } - if listSharesOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listSharesOptions.ResourceGroupID)) - } - if listSharesOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listSharesOptions.Name)) - } - if listSharesOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listSharesOptions.Sort)) - } - if listSharesOptions.ReplicationRole != nil { - builder.AddQuery("replication_role", fmt.Sprint(*listSharesOptions.ReplicationRole)) - } request, err := builder.Build() if err != nil { @@ -17398,12 +18324,12 @@ func (vpc *VpcV1) ListSharesWithContext(ctx context.Context, listSharesOptions * var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_shares", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_network_acl", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17414,55 +18340,55 @@ func (vpc *VpcV1) ListSharesWithContext(ctx context.Context, listSharesOptions * return } -// CreateShare : Create a file share -// This request provisions new file shares from a share prototype object. The new file shares can be a standalone share, -// a replica share, or both a source and replica share. -// -// The prototype object is structured in the same way as a retrieved share, and contains the information necessary to -// provision the new file shares. -func (vpc *VpcV1) CreateShare(createShareOptions *CreateShareOptions) (result *Share, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateShareWithContext(context.Background(), createShareOptions) +// UpdateNetworkACL : Update a network ACL +// This request updates a network ACL's name. +func (vpc *VpcV1) UpdateNetworkACL(updateNetworkACLOptions *UpdateNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateNetworkACLWithContext(context.Background(), updateNetworkACLOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateShareWithContext is an alternate form of the CreateShare method which supports a Context parameter -func (vpc *VpcV1) CreateShareWithContext(ctx context.Context, createShareOptions *CreateShareOptions) (result *Share, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createShareOptions, "createShareOptions cannot be nil") +// UpdateNetworkACLWithContext is an alternate form of the UpdateNetworkACL method which supports a Context parameter +func (vpc *VpcV1) UpdateNetworkACLWithContext(ctx context.Context, updateNetworkACLOptions *UpdateNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateNetworkACLOptions, "updateNetworkACLOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createShareOptions, "createShareOptions") + err = core.ValidateStruct(updateNetworkACLOptions, "updateNetworkACLOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "id": *updateNetworkACLOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createShareOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateNetworkACL") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateShare") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateNetworkACLOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createShareOptions.SharePrototype) + _, err = builder.SetBodyContentJSON(updateNetworkACLOptions.NetworkACLPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -17477,12 +18403,12 @@ func (vpc *VpcV1) CreateShareWithContext(ctx context.Context, createShareOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_share", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_network_acl", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShare) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17493,61 +18419,62 @@ func (vpc *VpcV1) CreateShareWithContext(ctx context.Context, createShareOptions return } -// DeleteShare : Delete a file share -// This request deletes a share. This operation cannot be reversed. A share cannot be deleted if it: -// - has share mount targets -// - has a `lifecycle_state` of `updating` -// - has a replication operation in progress -// -// If the request is accepted, the share `lifecycle_state` will be set to `deleting`. Once deletion processing -// completes, it will no longer be retrievable. -func (vpc *VpcV1) DeleteShare(deleteShareOptions *DeleteShareOptions) (result *Share, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteShareWithContext(context.Background(), deleteShareOptions) +// ListNetworkACLRules : List rules for a network ACL +// This request lists rules for a network ACL. These rules can allow or deny traffic between a source CIDR block and a +// destination CIDR block over a particular protocol and port range. +func (vpc *VpcV1) ListNetworkACLRules(listNetworkACLRulesOptions *ListNetworkACLRulesOptions) (result *NetworkACLRuleCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListNetworkACLRulesWithContext(context.Background(), listNetworkACLRulesOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteShareWithContext is an alternate form of the DeleteShare method which supports a Context parameter -func (vpc *VpcV1) DeleteShareWithContext(ctx context.Context, deleteShareOptions *DeleteShareOptions) (result *Share, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteShareOptions, "deleteShareOptions cannot be nil") +// ListNetworkACLRulesWithContext is an alternate form of the ListNetworkACLRules method which supports a Context parameter +func (vpc *VpcV1) ListNetworkACLRulesWithContext(ctx context.Context, listNetworkACLRulesOptions *ListNetworkACLRulesOptions) (result *NetworkACLRuleCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listNetworkACLRulesOptions, "listNetworkACLRulesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteShareOptions, "deleteShareOptions") + err = core.ValidateStruct(listNetworkACLRulesOptions, "listNetworkACLRulesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteShareOptions.ID, + "network_acl_id": *listNetworkACLRulesOptions.NetworkACLID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteShareOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListNetworkACLRules") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShare") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listNetworkACLRulesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if deleteShareOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteShareOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listNetworkACLRulesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listNetworkACLRulesOptions.Start)) + } + if listNetworkACLRulesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listNetworkACLRulesOptions.Limit)) + } + if listNetworkACLRulesOptions.Direction != nil { + builder.AddQuery("direction", fmt.Sprint(*listNetworkACLRulesOptions.Direction)) + } request, err := builder.Build() if err != nil { @@ -17558,12 +18485,12 @@ func (vpc *VpcV1) DeleteShareWithContext(ctx context.Context, deleteShareOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_share", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_network_acl_rules", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShare) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLRuleCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17574,53 +18501,61 @@ func (vpc *VpcV1) DeleteShareWithContext(ctx context.Context, deleteShareOptions return } -// GetShare : Retrieve a file share -// This request retrieves a single file share specified by the identifier in the URL. -func (vpc *VpcV1) GetShare(getShareOptions *GetShareOptions) (result *Share, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetShareWithContext(context.Background(), getShareOptions) +// CreateNetworkACLRule : Create a rule for a network ACL +// This request creates a new rule from a network ACL rule prototype object. The prototype object is structured in the +// same way as a retrieved rule, and contains the information necessary to create the new rule. +func (vpc *VpcV1) CreateNetworkACLRule(createNetworkACLRuleOptions *CreateNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateNetworkACLRuleWithContext(context.Background(), createNetworkACLRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetShareWithContext is an alternate form of the GetShare method which supports a Context parameter -func (vpc *VpcV1) GetShareWithContext(ctx context.Context, getShareOptions *GetShareOptions) (result *Share, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getShareOptions, "getShareOptions cannot be nil") +// CreateNetworkACLRuleWithContext is an alternate form of the CreateNetworkACLRule method which supports a Context parameter +func (vpc *VpcV1) CreateNetworkACLRuleWithContext(ctx context.Context, createNetworkACLRuleOptions *CreateNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createNetworkACLRuleOptions, "createNetworkACLRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getShareOptions, "getShareOptions") + err = core.ValidateStruct(createNetworkACLRuleOptions, "createNetworkACLRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getShareOptions.ID, + "network_acl_id": *createNetworkACLRuleOptions.NetworkACLID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getShareOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateNetworkACLRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShare") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createNetworkACLRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(createNetworkACLRuleOptions.NetworkACLRulePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -17630,12 +18565,12 @@ func (vpc *VpcV1) GetShareWithContext(ctx context.Context, getShareOptions *GetS var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_share", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_network_acl_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShare) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLRule) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17646,144 +18581,116 @@ func (vpc *VpcV1) GetShareWithContext(ctx context.Context, getShareOptions *GetS return } -// UpdateShare : Update a file share -// This request updates a share with the information in a provided share patch. The share patch object is structured in -// the same way as a retrieved share and contains only the information to be updated. -func (vpc *VpcV1) UpdateShare(updateShareOptions *UpdateShareOptions) (result *Share, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateShareWithContext(context.Background(), updateShareOptions) +// DeleteNetworkACLRule : Delete a network ACL rule +// This request deletes a rule. This operation cannot be reversed. +func (vpc *VpcV1) DeleteNetworkACLRule(deleteNetworkACLRuleOptions *DeleteNetworkACLRuleOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteNetworkACLRuleWithContext(context.Background(), deleteNetworkACLRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateShareWithContext is an alternate form of the UpdateShare method which supports a Context parameter -func (vpc *VpcV1) UpdateShareWithContext(ctx context.Context, updateShareOptions *UpdateShareOptions) (result *Share, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateShareOptions, "updateShareOptions cannot be nil") +// DeleteNetworkACLRuleWithContext is an alternate form of the DeleteNetworkACLRule method which supports a Context parameter +func (vpc *VpcV1) DeleteNetworkACLRuleWithContext(ctx context.Context, deleteNetworkACLRuleOptions *DeleteNetworkACLRuleOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteNetworkACLRuleOptions, "deleteNetworkACLRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateShareOptions, "updateShareOptions") + err = core.ValidateStruct(deleteNetworkACLRuleOptions, "deleteNetworkACLRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateShareOptions.ID, + "network_acl_id": *deleteNetworkACLRuleOptions.NetworkACLID, + "id": *deleteNetworkACLRuleOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateShareOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteNetworkACLRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateShare") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteNetworkACLRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateShareOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateShareOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateShareOptions.SharePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "update_share", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_network_acl_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShare) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListShareAccessorBindings : List accessor bindings for a file share -// This request lists accessor bindings for a share. Each accessor binding identifies a resource (possibly in another -// account) with access to this file share including its snapshots. -// -// The share accessor bindings will be sorted by their `created_at` property values, with newest bindings first. -func (vpc *VpcV1) ListShareAccessorBindings(listShareAccessorBindingsOptions *ListShareAccessorBindingsOptions) (result *ShareAccessorBindingCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListShareAccessorBindingsWithContext(context.Background(), listShareAccessorBindingsOptions) +// GetNetworkACLRule : Retrieve a network ACL rule +// This request retrieves a single rule specified by the identifier in the URL. +func (vpc *VpcV1) GetNetworkACLRule(getNetworkACLRuleOptions *GetNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetNetworkACLRuleWithContext(context.Background(), getNetworkACLRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListShareAccessorBindingsWithContext is an alternate form of the ListShareAccessorBindings method which supports a Context parameter -func (vpc *VpcV1) ListShareAccessorBindingsWithContext(ctx context.Context, listShareAccessorBindingsOptions *ListShareAccessorBindingsOptions) (result *ShareAccessorBindingCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listShareAccessorBindingsOptions, "listShareAccessorBindingsOptions cannot be nil") +// GetNetworkACLRuleWithContext is an alternate form of the GetNetworkACLRule method which supports a Context parameter +func (vpc *VpcV1) GetNetworkACLRuleWithContext(ctx context.Context, getNetworkACLRuleOptions *GetNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getNetworkACLRuleOptions, "getNetworkACLRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listShareAccessorBindingsOptions, "listShareAccessorBindingsOptions") + err = core.ValidateStruct(getNetworkACLRuleOptions, "getNetworkACLRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *listShareAccessorBindingsOptions.ID, + "network_acl_id": *getNetworkACLRuleOptions.NetworkACLID, + "id": *getNetworkACLRuleOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{id}/accessor_bindings`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listShareAccessorBindingsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetNetworkACLRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShareAccessorBindings") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getNetworkACLRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listShareAccessorBindingsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listShareAccessorBindingsOptions.Start)) - } - if listShareAccessorBindingsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listShareAccessorBindingsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -17794,12 +18701,12 @@ func (vpc *VpcV1) ListShareAccessorBindingsWithContext(ctx context.Context, list var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_share_accessor_bindings", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_network_acl_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareAccessorBindingCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLRule) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17810,116 +18717,131 @@ func (vpc *VpcV1) ListShareAccessorBindingsWithContext(ctx context.Context, list return } -// DeleteShareAccessorBinding : Delete a file share accessor binding -// This request deletes a share accessor binding. This operation cannot be reversed. -func (vpc *VpcV1) DeleteShareAccessorBinding(deleteShareAccessorBindingOptions *DeleteShareAccessorBindingOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteShareAccessorBindingWithContext(context.Background(), deleteShareAccessorBindingOptions) +// UpdateNetworkACLRule : Update a network ACL rule +// This request updates a rule with the information in a provided rule patch. The rule patch object contains only the +// information to be updated. The request will fail if the provided patch includes properties that are not used by the +// rule's protocol. +func (vpc *VpcV1) UpdateNetworkACLRule(updateNetworkACLRuleOptions *UpdateNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateNetworkACLRuleWithContext(context.Background(), updateNetworkACLRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteShareAccessorBindingWithContext is an alternate form of the DeleteShareAccessorBinding method which supports a Context parameter -func (vpc *VpcV1) DeleteShareAccessorBindingWithContext(ctx context.Context, deleteShareAccessorBindingOptions *DeleteShareAccessorBindingOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteShareAccessorBindingOptions, "deleteShareAccessorBindingOptions cannot be nil") +// UpdateNetworkACLRuleWithContext is an alternate form of the UpdateNetworkACLRule method which supports a Context parameter +func (vpc *VpcV1) UpdateNetworkACLRuleWithContext(ctx context.Context, updateNetworkACLRuleOptions *UpdateNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateNetworkACLRuleOptions, "updateNetworkACLRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteShareAccessorBindingOptions, "deleteShareAccessorBindingOptions") + err = core.ValidateStruct(updateNetworkACLRuleOptions, "updateNetworkACLRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *deleteShareAccessorBindingOptions.ShareID, - "id": *deleteShareAccessorBindingOptions.ID, + "network_acl_id": *updateNetworkACLRuleOptions.NetworkACLID, + "id": *updateNetworkACLRuleOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/accessor_bindings/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteShareAccessorBindingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateNetworkACLRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShareAccessorBinding") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateNetworkACLRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateNetworkACLRuleOptions.NetworkACLRulePatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_share_accessor_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_network_acl_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLRule) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetShareAccessorBinding : Retrieve a file share accessor binding -// This request retrieves a single accessor binding specified by the identifier in the URL. -func (vpc *VpcV1) GetShareAccessorBinding(getShareAccessorBindingOptions *GetShareAccessorBindingOptions) (result *ShareAccessorBinding, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetShareAccessorBindingWithContext(context.Background(), getShareAccessorBindingOptions) +// ListPlacementGroups : List placement groups +// This request lists placement groups in the region. +func (vpc *VpcV1) ListPlacementGroups(listPlacementGroupsOptions *ListPlacementGroupsOptions) (result *PlacementGroupCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListPlacementGroupsWithContext(context.Background(), listPlacementGroupsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetShareAccessorBindingWithContext is an alternate form of the GetShareAccessorBinding method which supports a Context parameter -func (vpc *VpcV1) GetShareAccessorBindingWithContext(ctx context.Context, getShareAccessorBindingOptions *GetShareAccessorBindingOptions) (result *ShareAccessorBinding, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getShareAccessorBindingOptions, "getShareAccessorBindingOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getShareAccessorBindingOptions, "getShareAccessorBindingOptions") +// ListPlacementGroupsWithContext is an alternate form of the ListPlacementGroups method which supports a Context parameter +func (vpc *VpcV1) ListPlacementGroupsWithContext(ctx context.Context, listPlacementGroupsOptions *ListPlacementGroupsOptions) (result *PlacementGroupCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listPlacementGroupsOptions, "listPlacementGroupsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "share_id": *getShareAccessorBindingOptions.ShareID, - "id": *getShareAccessorBindingOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/accessor_bindings/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getShareAccessorBindingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPlacementGroups") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareAccessorBinding") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPlacementGroupsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listPlacementGroupsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listPlacementGroupsOptions.Start)) + } + if listPlacementGroupsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listPlacementGroupsOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -17930,12 +18852,12 @@ func (vpc *VpcV1) GetShareAccessorBindingWithContext(ctx context.Context, getSha var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_share_accessor_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_placement_groups", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareAccessorBinding) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPlacementGroupCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -17946,64 +18868,59 @@ func (vpc *VpcV1) GetShareAccessorBindingWithContext(ctx context.Context, getSha return } -// FailoverShare : Failover to replica file share -// This request triggers a failover to the replica file share specified by the identifier in the URL. The failover -// cannot be started if a source share or the replica share has a `lifecycle_state` of `updating`, or has a replication -// operation in progress. -// -// If `fallback_policy` is specified as `split`, and the request is accepted but the failover operation cannot be -// performed, a split will be triggered. -func (vpc *VpcV1) FailoverShare(failoverShareOptions *FailoverShareOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.FailoverShareWithContext(context.Background(), failoverShareOptions) +// CreatePlacementGroup : Create a placement group +// This request creates a new placement group. +func (vpc *VpcV1) CreatePlacementGroup(createPlacementGroupOptions *CreatePlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreatePlacementGroupWithContext(context.Background(), createPlacementGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// FailoverShareWithContext is an alternate form of the FailoverShare method which supports a Context parameter -func (vpc *VpcV1) FailoverShareWithContext(ctx context.Context, failoverShareOptions *FailoverShareOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(failoverShareOptions, "failoverShareOptions cannot be nil") +// CreatePlacementGroupWithContext is an alternate form of the CreatePlacementGroup method which supports a Context parameter +func (vpc *VpcV1) CreatePlacementGroupWithContext(ctx context.Context, createPlacementGroupOptions *CreatePlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createPlacementGroupOptions, "createPlacementGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(failoverShareOptions, "failoverShareOptions") + err = core.ValidateStruct(createPlacementGroupOptions, "createPlacementGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "share_id": *failoverShareOptions.ShareID, - } - builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/failover`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range failoverShareOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePlacementGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "FailoverShare") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPlacementGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if failoverShareOptions.FallbackPolicy != nil { - body["fallback_policy"] = failoverShareOptions.FallbackPolicy + if createPlacementGroupOptions.Strategy != nil { + body["strategy"] = createPlacementGroupOptions.Strategy } - if failoverShareOptions.Timeout != nil { - body["timeout"] = failoverShareOptions.Timeout + if createPlacementGroupOptions.Name != nil { + body["name"] = createPlacementGroupOptions.Name + } + if createPlacementGroupOptions.ResourceGroup != nil { + body["resource_group"] = createPlacementGroupOptions.ResourceGroup } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -18017,74 +18934,71 @@ func (vpc *VpcV1) FailoverShareWithContext(ctx context.Context, failoverShareOpt return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "failover_share", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_placement_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPlacementGroup) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListShareMountTargets : List mount targets for a file share -// This request lists mount targets for a file share. A mount target is a network endpoint at which a file share may be -// mounted. The file share can be mounted by clients in the same VPC and zone after creating share mount targets. -// -// The share mount targets will be sorted by their `created_at` property values, with newest targets first. -func (vpc *VpcV1) ListShareMountTargets(listShareMountTargetsOptions *ListShareMountTargetsOptions) (result *ShareMountTargetCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListShareMountTargetsWithContext(context.Background(), listShareMountTargetsOptions) +// DeletePlacementGroup : Delete a placement group +// This request deletes a placement group. This operation cannot be reversed. For this request to succeed, the placement +// group must not be associated with an instance. +func (vpc *VpcV1) DeletePlacementGroup(deletePlacementGroupOptions *DeletePlacementGroupOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeletePlacementGroupWithContext(context.Background(), deletePlacementGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListShareMountTargetsWithContext is an alternate form of the ListShareMountTargets method which supports a Context parameter -func (vpc *VpcV1) ListShareMountTargetsWithContext(ctx context.Context, listShareMountTargetsOptions *ListShareMountTargetsOptions) (result *ShareMountTargetCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listShareMountTargetsOptions, "listShareMountTargetsOptions cannot be nil") +// DeletePlacementGroupWithContext is an alternate form of the DeletePlacementGroup method which supports a Context parameter +func (vpc *VpcV1) DeletePlacementGroupWithContext(ctx context.Context, deletePlacementGroupOptions *DeletePlacementGroupOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deletePlacementGroupOptions, "deletePlacementGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listShareMountTargetsOptions, "listShareMountTargetsOptions") + err = core.ValidateStruct(deletePlacementGroupOptions, "deletePlacementGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *listShareMountTargetsOptions.ShareID, + "id": *deletePlacementGroupOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listShareMountTargetsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePlacementGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShareMountTargets") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePlacementGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listShareMountTargetsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listShareMountTargetsOptions.Name)) - } - if listShareMountTargetsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listShareMountTargetsOptions.Start)) - } - if listShareMountTargetsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listShareMountTargetsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -18092,82 +19006,63 @@ func (vpc *VpcV1) ListShareMountTargetsWithContext(ctx context.Context, listShar return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_share_mount_targets", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_placement_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTargetCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateShareMountTarget : Create a mount target for a file share -// This request creates a new share mount target from a share mount target prototype object. -// -// The prototype object is structured in the same way as a retrieved share mount target, and contains the information -// necessary to provision the new file share mount target. -func (vpc *VpcV1) CreateShareMountTarget(createShareMountTargetOptions *CreateShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateShareMountTargetWithContext(context.Background(), createShareMountTargetOptions) +// GetPlacementGroup : Retrieve a placement group +// This request retrieves a single placement group specified by identifier in the URL. +func (vpc *VpcV1) GetPlacementGroup(getPlacementGroupOptions *GetPlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetPlacementGroupWithContext(context.Background(), getPlacementGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateShareMountTargetWithContext is an alternate form of the CreateShareMountTarget method which supports a Context parameter -func (vpc *VpcV1) CreateShareMountTargetWithContext(ctx context.Context, createShareMountTargetOptions *CreateShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createShareMountTargetOptions, "createShareMountTargetOptions cannot be nil") +// GetPlacementGroupWithContext is an alternate form of the GetPlacementGroup method which supports a Context parameter +func (vpc *VpcV1) GetPlacementGroupWithContext(ctx context.Context, getPlacementGroupOptions *GetPlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getPlacementGroupOptions, "getPlacementGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createShareMountTargetOptions, "createShareMountTargetOptions") + err = core.ValidateStruct(getPlacementGroupOptions, "getPlacementGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *createShareMountTargetOptions.ShareID, + "id": *getPlacementGroupOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createShareMountTargetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPlacementGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateShareMountTarget") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPlacementGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createShareMountTargetOptions.ShareMountTargetPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -18177,12 +19072,12 @@ func (vpc *VpcV1) CreateShareMountTargetWithContext(ctx context.Context, createS var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_share_mount_target", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_placement_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTarget) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPlacementGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18193,57 +19088,61 @@ func (vpc *VpcV1) CreateShareMountTargetWithContext(ctx context.Context, createS return } -// DeleteShareMountTarget : Delete a file share mount target -// This request deletes a share mount target. This operation cannot be reversed. -// -// If the request is accepted, the share mount target `lifecycle_state` will be set to -// `deleting`. Once deletion processing completes, it will no longer be retrievable. -func (vpc *VpcV1) DeleteShareMountTarget(deleteShareMountTargetOptions *DeleteShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteShareMountTargetWithContext(context.Background(), deleteShareMountTargetOptions) +// UpdatePlacementGroup : Update a placement group +// This request updates a placement group with the information provided placement group patch. The placement group patch +// object is structured in the same way as a retrieved placement group and contains only the information to be updated. +func (vpc *VpcV1) UpdatePlacementGroup(updatePlacementGroupOptions *UpdatePlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdatePlacementGroupWithContext(context.Background(), updatePlacementGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteShareMountTargetWithContext is an alternate form of the DeleteShareMountTarget method which supports a Context parameter -func (vpc *VpcV1) DeleteShareMountTargetWithContext(ctx context.Context, deleteShareMountTargetOptions *DeleteShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteShareMountTargetOptions, "deleteShareMountTargetOptions cannot be nil") +// UpdatePlacementGroupWithContext is an alternate form of the UpdatePlacementGroup method which supports a Context parameter +func (vpc *VpcV1) UpdatePlacementGroupWithContext(ctx context.Context, updatePlacementGroupOptions *UpdatePlacementGroupOptions) (result *PlacementGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updatePlacementGroupOptions, "updatePlacementGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteShareMountTargetOptions, "deleteShareMountTargetOptions") + err = core.ValidateStruct(updatePlacementGroupOptions, "updatePlacementGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *deleteShareMountTargetOptions.ShareID, - "id": *deleteShareMountTargetOptions.ID, + "id": *updatePlacementGroupOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/placement_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteShareMountTargetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePlacementGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShareMountTarget") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updatePlacementGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updatePlacementGroupOptions.PlacementGroupPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -18253,12 +19152,12 @@ func (vpc *VpcV1) DeleteShareMountTargetWithContext(ctx context.Context, deleteS var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_share_mount_target", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_placement_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTarget) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPlacementGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18269,53 +19168,59 @@ func (vpc *VpcV1) DeleteShareMountTargetWithContext(ctx context.Context, deleteS return } -// GetShareMountTarget : Retrieve a file share mount target -// This request retrieves a single share mount target specified by the identifier in the URL. -func (vpc *VpcV1) GetShareMountTarget(getShareMountTargetOptions *GetShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetShareMountTargetWithContext(context.Background(), getShareMountTargetOptions) +// ListPrivatePathServiceGateways : List private path service gateways +// This request lists private path service gateways in the region. Private path service gateways allow +// [service +// providers](https://cloud.ibm.com/docs/private-path?topic=private-path-private-path-service-architecture#private-path-service-components) +// to make their services available using +// [private path +// connectivity](https://cloud.ibm.com/docs/private-path?topic=private-path-private-path-service-architecture#private-path-service-components). +// Private path service gateways are used to facilitate and manage the private path connectivity between private path +// network load balancers and their associated endpoint gateways. +func (vpc *VpcV1) ListPrivatePathServiceGateways(listPrivatePathServiceGatewaysOptions *ListPrivatePathServiceGatewaysOptions) (result *PrivatePathServiceGatewayCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListPrivatePathServiceGatewaysWithContext(context.Background(), listPrivatePathServiceGatewaysOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetShareMountTargetWithContext is an alternate form of the GetShareMountTarget method which supports a Context parameter -func (vpc *VpcV1) GetShareMountTargetWithContext(ctx context.Context, getShareMountTargetOptions *GetShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getShareMountTargetOptions, "getShareMountTargetOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getShareMountTargetOptions, "getShareMountTargetOptions") +// ListPrivatePathServiceGatewaysWithContext is an alternate form of the ListPrivatePathServiceGateways method which supports a Context parameter +func (vpc *VpcV1) ListPrivatePathServiceGatewaysWithContext(ctx context.Context, listPrivatePathServiceGatewaysOptions *ListPrivatePathServiceGatewaysOptions) (result *PrivatePathServiceGatewayCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listPrivatePathServiceGatewaysOptions, "listPrivatePathServiceGatewaysOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "share_id": *getShareMountTargetOptions.ShareID, - "id": *getShareMountTargetOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getShareMountTargetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPrivatePathServiceGateways") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareMountTarget") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPrivatePathServiceGatewaysOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listPrivatePathServiceGatewaysOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listPrivatePathServiceGatewaysOptions.Start)) + } + if listPrivatePathServiceGatewaysOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listPrivatePathServiceGatewaysOptions.Limit)) + } + if listPrivatePathServiceGatewaysOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listPrivatePathServiceGatewaysOptions.ResourceGroupID)) + } request, err := builder.Build() if err != nil { @@ -18326,12 +19231,12 @@ func (vpc *VpcV1) GetShareMountTargetWithContext(ctx context.Context, getShareMo var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_share_mount_target", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_private_path_service_gateways", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTarget) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18342,58 +19247,72 @@ func (vpc *VpcV1) GetShareMountTargetWithContext(ctx context.Context, getShareMo return } -// UpdateShareMountTarget : Update a file share mount target -// This request updates a share mount target with the information provided in a share mount target patch object. The -// share mount target patch object is structured in the same way as a retrieved share mount target and needs to contain -// only the information to be updated. -func (vpc *VpcV1) UpdateShareMountTarget(updateShareMountTargetOptions *UpdateShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateShareMountTargetWithContext(context.Background(), updateShareMountTargetOptions) +// CreatePrivatePathServiceGateway : Create a private path service gateway +// This request creates a private path service gateway from a private path service gateway prototype object. The +// prototype object is structured in the same way as a retrieved private path service gateway, and contains the +// information necessary to create the new private path service gateway. +func (vpc *VpcV1) CreatePrivatePathServiceGateway(createPrivatePathServiceGatewayOptions *CreatePrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreatePrivatePathServiceGatewayWithContext(context.Background(), createPrivatePathServiceGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateShareMountTargetWithContext is an alternate form of the UpdateShareMountTarget method which supports a Context parameter -func (vpc *VpcV1) UpdateShareMountTargetWithContext(ctx context.Context, updateShareMountTargetOptions *UpdateShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateShareMountTargetOptions, "updateShareMountTargetOptions cannot be nil") +// CreatePrivatePathServiceGatewayWithContext is an alternate form of the CreatePrivatePathServiceGateway method which supports a Context parameter +func (vpc *VpcV1) CreatePrivatePathServiceGatewayWithContext(ctx context.Context, createPrivatePathServiceGatewayOptions *CreatePrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createPrivatePathServiceGatewayOptions, "createPrivatePathServiceGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateShareMountTargetOptions, "updateShareMountTargetOptions") + err = core.ValidateStruct(createPrivatePathServiceGatewayOptions, "createPrivatePathServiceGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "share_id": *updateShareMountTargetOptions.ShareID, - "id": *updateShareMountTargetOptions.ID, - } - - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateShareMountTargetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePrivatePathServiceGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateShareMountTarget") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPrivatePathServiceGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateShareMountTargetOptions.ShareMountTargetPatch) + body := make(map[string]interface{}) + if createPrivatePathServiceGatewayOptions.LoadBalancer != nil { + body["load_balancer"] = createPrivatePathServiceGatewayOptions.LoadBalancer + } + if createPrivatePathServiceGatewayOptions.ServiceEndpoints != nil { + body["service_endpoints"] = createPrivatePathServiceGatewayOptions.ServiceEndpoints + } + if createPrivatePathServiceGatewayOptions.DefaultAccessPolicy != nil { + body["default_access_policy"] = createPrivatePathServiceGatewayOptions.DefaultAccessPolicy + } + if createPrivatePathServiceGatewayOptions.Name != nil { + body["name"] = createPrivatePathServiceGatewayOptions.Name + } + if createPrivatePathServiceGatewayOptions.ResourceGroup != nil { + body["resource_group"] = createPrivatePathServiceGatewayOptions.ResourceGroup + } + if createPrivatePathServiceGatewayOptions.ZonalAffinity != nil { + body["zonal_affinity"] = createPrivatePathServiceGatewayOptions.ZonalAffinity + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -18408,12 +19327,12 @@ func (vpc *VpcV1) UpdateShareMountTargetWithContext(ctx context.Context, updateS var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_share_mount_target", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_private_path_service_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTarget) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18424,70 +19343,52 @@ func (vpc *VpcV1) UpdateShareMountTargetWithContext(ctx context.Context, updateS return } -// ListShareSnapshots : List file share snapshots -// This request lists snapshots for the specified file share, or across all accessible file shares. A snapshot preserves -// the data of a share at the time the snapshot was captured. -// -// If the file share is a replica, the list will contain snapshots corresponding to snapshots on the source. -func (vpc *VpcV1) ListShareSnapshots(listShareSnapshotsOptions *ListShareSnapshotsOptions) (result *ShareSnapshotCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListShareSnapshotsWithContext(context.Background(), listShareSnapshotsOptions) +// DeletePrivatePathServiceGateway : Delete a private path service gateway +// This request deletes a private path service gateway. For this request to succeed, the value of +// `endpoint_gateway_count` must be `0`. This operation cannot be reversed. +func (vpc *VpcV1) DeletePrivatePathServiceGateway(deletePrivatePathServiceGatewayOptions *DeletePrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeletePrivatePathServiceGatewayWithContext(context.Background(), deletePrivatePathServiceGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListShareSnapshotsWithContext is an alternate form of the ListShareSnapshots method which supports a Context parameter -func (vpc *VpcV1) ListShareSnapshotsWithContext(ctx context.Context, listShareSnapshotsOptions *ListShareSnapshotsOptions) (result *ShareSnapshotCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listShareSnapshotsOptions, "listShareSnapshotsOptions cannot be nil") +// DeletePrivatePathServiceGatewayWithContext is an alternate form of the DeletePrivatePathServiceGateway method which supports a Context parameter +func (vpc *VpcV1) DeletePrivatePathServiceGatewayWithContext(ctx context.Context, deletePrivatePathServiceGatewayOptions *DeletePrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deletePrivatePathServiceGatewayOptions, "deletePrivatePathServiceGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listShareSnapshotsOptions, "listShareSnapshotsOptions") + err = core.ValidateStruct(deletePrivatePathServiceGatewayOptions, "deletePrivatePathServiceGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *listShareSnapshotsOptions.ShareID, + "id": *deletePrivatePathServiceGatewayOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listShareSnapshotsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePrivatePathServiceGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShareSnapshots") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePrivatePathServiceGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listShareSnapshotsOptions.BackupPolicyPlanID != nil { - builder.AddQuery("backup_policy_plan.id", fmt.Sprint(*listShareSnapshotsOptions.BackupPolicyPlanID)) - } - if listShareSnapshotsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listShareSnapshotsOptions.Name)) - } - if listShareSnapshotsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listShareSnapshotsOptions.Start)) - } - if listShareSnapshotsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listShareSnapshotsOptions.Limit)) - } - if listShareSnapshotsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listShareSnapshotsOptions.Sort)) - } request, err := builder.Build() if err != nil { @@ -18495,97 +19396,63 @@ func (vpc *VpcV1) ListShareSnapshotsWithContext(ctx context.Context, listShareSn return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_share_snapshots", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_private_path_service_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshotCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateShareSnapshot : Create a snapshot for a file share -// This request creates a new share snapshot from a share snapshot prototype object. The prototype object is structured -// in the same way as a retrieved share snapshot, and contains the information necessary to create the new share -// snapshot. -// -// The share must have an `access_control_mode` of `security_group` and a `replication_role` of `source` or `none`. -// -// The snapshot will inherit its `resource_group` and encryption settings from the share. -// -// If the share has a `replication_role` of `source`, a corresponding snapshot on the replica share will be created with -// a `status` of `pending`. It will remain in -// `pending` until the data is synchronized per the replication schedule determined by the replica share's -// `replication_cron_spec`. -func (vpc *VpcV1) CreateShareSnapshot(createShareSnapshotOptions *CreateShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateShareSnapshotWithContext(context.Background(), createShareSnapshotOptions) +// GetPrivatePathServiceGateway : Retrieve a private path service gateway +// This request retrieves the private path service gateway specified by the identifier in the URL. +func (vpc *VpcV1) GetPrivatePathServiceGateway(getPrivatePathServiceGatewayOptions *GetPrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetPrivatePathServiceGatewayWithContext(context.Background(), getPrivatePathServiceGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateShareSnapshotWithContext is an alternate form of the CreateShareSnapshot method which supports a Context parameter -func (vpc *VpcV1) CreateShareSnapshotWithContext(ctx context.Context, createShareSnapshotOptions *CreateShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createShareSnapshotOptions, "createShareSnapshotOptions cannot be nil") +// GetPrivatePathServiceGatewayWithContext is an alternate form of the GetPrivatePathServiceGateway method which supports a Context parameter +func (vpc *VpcV1) GetPrivatePathServiceGatewayWithContext(ctx context.Context, getPrivatePathServiceGatewayOptions *GetPrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getPrivatePathServiceGatewayOptions, "getPrivatePathServiceGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createShareSnapshotOptions, "createShareSnapshotOptions") + err = core.ValidateStruct(getPrivatePathServiceGatewayOptions, "getPrivatePathServiceGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *createShareSnapshotOptions.ShareID, + "id": *getPrivatePathServiceGatewayOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createShareSnapshotOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPrivatePathServiceGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateShareSnapshot") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPrivatePathServiceGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createShareSnapshotOptions.Name != nil { - body["name"] = createShareSnapshotOptions.Name - } - if createShareSnapshotOptions.UserTags != nil { - body["user_tags"] = createShareSnapshotOptions.UserTags - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -18595,12 +19462,12 @@ func (vpc *VpcV1) CreateShareSnapshotWithContext(ctx context.Context, createShar var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_share_snapshot", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_private_path_service_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshot) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18611,65 +19478,62 @@ func (vpc *VpcV1) CreateShareSnapshotWithContext(ctx context.Context, createShar return } -// DeleteShareSnapshot : Delete a share snapshot -// This request deletes a share snapshot. This operation cannot be reversed. For this request to succeed, the share must -// have a `replication_role` of `source` or `none`. -// -// If the request is accepted, the share snapshot `lifecycle_state` will be set to -// `deleting`. Once deletion processing completes, the share snapshot will no longer be retrievable. -// -// Deleting a share snapshot will not affect any previously-accepted requests to create a share from it. -// -// If the share has a `replication_role` of `source`, the corresponding snapshot on the replica share will be -// subsequently moved to a `lifecycle_state` of `deleting`. If the data for the corresponding snapshot has already been -// synchronized via the replication schedule determined by `replication_cron_spec`, the snapshot will remain available -// in the replica share's `.snapshot` directory until the next replication sync. -func (vpc *VpcV1) DeleteShareSnapshot(deleteShareSnapshotOptions *DeleteShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteShareSnapshotWithContext(context.Background(), deleteShareSnapshotOptions) +// UpdatePrivatePathServiceGateway : Update a private path service gateway +// This request updates a private path service gateway with the information provided in a private path service gateway +// patch object. The private path service gateway patch object is structured in the same way as a retrieved private path +// service gateway and contains only the information to be updated. +func (vpc *VpcV1) UpdatePrivatePathServiceGateway(updatePrivatePathServiceGatewayOptions *UpdatePrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdatePrivatePathServiceGatewayWithContext(context.Background(), updatePrivatePathServiceGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteShareSnapshotWithContext is an alternate form of the DeleteShareSnapshot method which supports a Context parameter -func (vpc *VpcV1) DeleteShareSnapshotWithContext(ctx context.Context, deleteShareSnapshotOptions *DeleteShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteShareSnapshotOptions, "deleteShareSnapshotOptions cannot be nil") +// UpdatePrivatePathServiceGatewayWithContext is an alternate form of the UpdatePrivatePathServiceGateway method which supports a Context parameter +func (vpc *VpcV1) UpdatePrivatePathServiceGatewayWithContext(ctx context.Context, updatePrivatePathServiceGatewayOptions *UpdatePrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updatePrivatePathServiceGatewayOptions, "updatePrivatePathServiceGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteShareSnapshotOptions, "deleteShareSnapshotOptions") + err = core.ValidateStruct(updatePrivatePathServiceGatewayOptions, "updatePrivatePathServiceGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *deleteShareSnapshotOptions.ShareID, - "id": *deleteShareSnapshotOptions.ID, + "id": *updatePrivatePathServiceGatewayOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteShareSnapshotOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePrivatePathServiceGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShareSnapshot") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updatePrivatePathServiceGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updatePrivatePathServiceGatewayOptions.PrivatePathServiceGatewayPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -18679,12 +19543,12 @@ func (vpc *VpcV1) DeleteShareSnapshotWithContext(ctx context.Context, deleteShar var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_share_snapshot", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_private_path_service_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshot) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18695,53 +19559,66 @@ func (vpc *VpcV1) DeleteShareSnapshotWithContext(ctx context.Context, deleteShar return } -// GetShareSnapshot : Retrieve a share snapshot -// This request retrieves a single share snapshot specified by the identifier in the URL. -func (vpc *VpcV1) GetShareSnapshot(getShareSnapshotOptions *GetShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetShareSnapshotWithContext(context.Background(), getShareSnapshotOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// GetShareSnapshotWithContext is an alternate form of the GetShareSnapshot method which supports a Context parameter -func (vpc *VpcV1) GetShareSnapshotWithContext(ctx context.Context, getShareSnapshotOptions *GetShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getShareSnapshotOptions, "getShareSnapshotOptions cannot be nil") +// ListPrivatePathServiceGatewayAccountPolicies : List account policies for a private path service gateway +// This request lists account policies for a private path service gateway. Each policy defines how requests to use the +// private path service gateway from that account will be handled. +// +// The account policies will be sorted by their `created_at` property values, with newest account policies first. +// Account policies with identical `created_at` property values will in turn be sorted by ascending `id` property +// values. +func (vpc *VpcV1) ListPrivatePathServiceGatewayAccountPolicies(listPrivatePathServiceGatewayAccountPoliciesOptions *ListPrivatePathServiceGatewayAccountPoliciesOptions) (result *PrivatePathServiceGatewayAccountPolicyCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListPrivatePathServiceGatewayAccountPoliciesWithContext(context.Background(), listPrivatePathServiceGatewayAccountPoliciesOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListPrivatePathServiceGatewayAccountPoliciesWithContext is an alternate form of the ListPrivatePathServiceGatewayAccountPolicies method which supports a Context parameter +func (vpc *VpcV1) ListPrivatePathServiceGatewayAccountPoliciesWithContext(ctx context.Context, listPrivatePathServiceGatewayAccountPoliciesOptions *ListPrivatePathServiceGatewayAccountPoliciesOptions) (result *PrivatePathServiceGatewayAccountPolicyCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listPrivatePathServiceGatewayAccountPoliciesOptions, "listPrivatePathServiceGatewayAccountPoliciesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getShareSnapshotOptions, "getShareSnapshotOptions") + err = core.ValidateStruct(listPrivatePathServiceGatewayAccountPoliciesOptions, "listPrivatePathServiceGatewayAccountPoliciesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *getShareSnapshotOptions.ShareID, - "id": *getShareSnapshotOptions.ID, + "private_path_service_gateway_id": *listPrivatePathServiceGatewayAccountPoliciesOptions.PrivatePathServiceGatewayID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getShareSnapshotOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPrivatePathServiceGatewayAccountPolicies") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareSnapshot") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPrivatePathServiceGatewayAccountPoliciesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listPrivatePathServiceGatewayAccountPoliciesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listPrivatePathServiceGatewayAccountPoliciesOptions.Start)) + } + if listPrivatePathServiceGatewayAccountPoliciesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listPrivatePathServiceGatewayAccountPoliciesOptions.Limit)) + } + if listPrivatePathServiceGatewayAccountPoliciesOptions.AccountID != nil { + builder.AddQuery("account.id", fmt.Sprint(*listPrivatePathServiceGatewayAccountPoliciesOptions.AccountID)) + } request, err := builder.Build() if err != nil { @@ -18752,12 +19629,12 @@ func (vpc *VpcV1) GetShareSnapshotWithContext(ctx context.Context, getShareSnaps var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_share_snapshot", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_private_path_service_gateway_account_policies", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshot) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayAccountPolicyCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18768,61 +19645,63 @@ func (vpc *VpcV1) GetShareSnapshotWithContext(ctx context.Context, getShareSnaps return } -// UpdateShareSnapshot : Update a share snapshot -// This request updates a share snapshot with the information provided in a share snapshot patch object. The share -// snapshot patch object is structured in the same way as a retrieved share snapshot and needs to contain only the -// information to be updated. -func (vpc *VpcV1) UpdateShareSnapshot(updateShareSnapshotOptions *UpdateShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateShareSnapshotWithContext(context.Background(), updateShareSnapshotOptions) +// CreatePrivatePathServiceGatewayAccountPolicy : Create an account policy for a private path service gateway +// This request creates an account policy from an account policy prototype object. The prototype object is structured in +// the same way as a retrieved account policy, and contains the information necessary to create the new account policy. +func (vpc *VpcV1) CreatePrivatePathServiceGatewayAccountPolicy(createPrivatePathServiceGatewayAccountPolicyOptions *CreatePrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreatePrivatePathServiceGatewayAccountPolicyWithContext(context.Background(), createPrivatePathServiceGatewayAccountPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateShareSnapshotWithContext is an alternate form of the UpdateShareSnapshot method which supports a Context parameter -func (vpc *VpcV1) UpdateShareSnapshotWithContext(ctx context.Context, updateShareSnapshotOptions *UpdateShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateShareSnapshotOptions, "updateShareSnapshotOptions cannot be nil") +// CreatePrivatePathServiceGatewayAccountPolicyWithContext is an alternate form of the CreatePrivatePathServiceGatewayAccountPolicy method which supports a Context parameter +func (vpc *VpcV1) CreatePrivatePathServiceGatewayAccountPolicyWithContext(ctx context.Context, createPrivatePathServiceGatewayAccountPolicyOptions *CreatePrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createPrivatePathServiceGatewayAccountPolicyOptions, "createPrivatePathServiceGatewayAccountPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateShareSnapshotOptions, "updateShareSnapshotOptions") + err = core.ValidateStruct(createPrivatePathServiceGatewayAccountPolicyOptions, "createPrivatePathServiceGatewayAccountPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *updateShareSnapshotOptions.ShareID, - "id": *updateShareSnapshotOptions.ID, + "private_path_service_gateway_id": *createPrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateShareSnapshotOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePrivatePathServiceGatewayAccountPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateShareSnapshot") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPrivatePathServiceGatewayAccountPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateShareSnapshotOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateShareSnapshotOptions.IfMatch)) - } + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateShareSnapshotOptions.ShareSnapshotPatch) + body := make(map[string]interface{}) + if createPrivatePathServiceGatewayAccountPolicyOptions.AccessPolicy != nil { + body["access_policy"] = createPrivatePathServiceGatewayAccountPolicyOptions.AccessPolicy + } + if createPrivatePathServiceGatewayAccountPolicyOptions.Account != nil { + body["account"] = createPrivatePathServiceGatewayAccountPolicyOptions.Account + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -18837,12 +19716,12 @@ func (vpc *VpcV1) UpdateShareSnapshotWithContext(ctx context.Context, updateShar var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_share_snapshot", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_private_path_service_gateway_account_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshot) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayAccountPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18853,50 +19732,48 @@ func (vpc *VpcV1) UpdateShareSnapshotWithContext(ctx context.Context, updateShar return } -// DeleteShareSource : Split the source file share from a replica file share -// This request removes the replication relationship between a source share and the replica share specified by the -// identifier in the URL. The replication relationship cannot be removed if a source share or the replica share has a -// `lifecycle_state` of `updating`, or has a replication operation in progress. -// -// This operation cannot be reversed. -func (vpc *VpcV1) DeleteShareSource(deleteShareSourceOptions *DeleteShareSourceOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteShareSourceWithContext(context.Background(), deleteShareSourceOptions) +// DeletePrivatePathServiceGatewayAccountPolicy : Delete an account policy for a private path service gateway +// This request deletes an account policy. This operation cannot be reversed and it does not affect the `status` of any +// existing endpoint gateway bindings. +func (vpc *VpcV1) DeletePrivatePathServiceGatewayAccountPolicy(deletePrivatePathServiceGatewayAccountPolicyOptions *DeletePrivatePathServiceGatewayAccountPolicyOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeletePrivatePathServiceGatewayAccountPolicyWithContext(context.Background(), deletePrivatePathServiceGatewayAccountPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteShareSourceWithContext is an alternate form of the DeleteShareSource method which supports a Context parameter -func (vpc *VpcV1) DeleteShareSourceWithContext(ctx context.Context, deleteShareSourceOptions *DeleteShareSourceOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteShareSourceOptions, "deleteShareSourceOptions cannot be nil") +// DeletePrivatePathServiceGatewayAccountPolicyWithContext is an alternate form of the DeletePrivatePathServiceGatewayAccountPolicy method which supports a Context parameter +func (vpc *VpcV1) DeletePrivatePathServiceGatewayAccountPolicyWithContext(ctx context.Context, deletePrivatePathServiceGatewayAccountPolicyOptions *DeletePrivatePathServiceGatewayAccountPolicyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deletePrivatePathServiceGatewayAccountPolicyOptions, "deletePrivatePathServiceGatewayAccountPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteShareSourceOptions, "deleteShareSourceOptions") + err = core.ValidateStruct(deletePrivatePathServiceGatewayAccountPolicyOptions, "deletePrivatePathServiceGatewayAccountPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *deleteShareSourceOptions.ShareID, + "private_path_service_gateway_id": *deletePrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayID, + "id": *deletePrivatePathServiceGatewayAccountPolicyOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/source`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteShareSourceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePrivatePathServiceGatewayAccountPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShareSource") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePrivatePathServiceGatewayAccountPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -18911,7 +19788,7 @@ func (vpc *VpcV1) DeleteShareSourceWithContext(ctx context.Context, deleteShareS response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_share_source", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_private_path_service_gateway_account_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -18919,47 +19796,47 @@ func (vpc *VpcV1) DeleteShareSourceWithContext(ctx context.Context, deleteShareS return } -// GetShareSource : Retrieve the source file share for a replica file share -// This request retrieves the source file share associated with the replica file share specified by the identifier in -// the URL. -func (vpc *VpcV1) GetShareSource(getShareSourceOptions *GetShareSourceOptions) (result *ShareReference, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetShareSourceWithContext(context.Background(), getShareSourceOptions) +// GetPrivatePathServiceGatewayAccountPolicy : Retrieve an account policy for a private path service gateway +// This request retrieves a single account policy specified by the identifier in the URL. +func (vpc *VpcV1) GetPrivatePathServiceGatewayAccountPolicy(getPrivatePathServiceGatewayAccountPolicyOptions *GetPrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetPrivatePathServiceGatewayAccountPolicyWithContext(context.Background(), getPrivatePathServiceGatewayAccountPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetShareSourceWithContext is an alternate form of the GetShareSource method which supports a Context parameter -func (vpc *VpcV1) GetShareSourceWithContext(ctx context.Context, getShareSourceOptions *GetShareSourceOptions) (result *ShareReference, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getShareSourceOptions, "getShareSourceOptions cannot be nil") +// GetPrivatePathServiceGatewayAccountPolicyWithContext is an alternate form of the GetPrivatePathServiceGatewayAccountPolicy method which supports a Context parameter +func (vpc *VpcV1) GetPrivatePathServiceGatewayAccountPolicyWithContext(ctx context.Context, getPrivatePathServiceGatewayAccountPolicyOptions *GetPrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getPrivatePathServiceGatewayAccountPolicyOptions, "getPrivatePathServiceGatewayAccountPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getShareSourceOptions, "getShareSourceOptions") + err = core.ValidateStruct(getPrivatePathServiceGatewayAccountPolicyOptions, "getPrivatePathServiceGatewayAccountPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "share_id": *getShareSourceOptions.ShareID, + "private_path_service_gateway_id": *getPrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayID, + "id": *getPrivatePathServiceGatewayAccountPolicyOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/source`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getShareSourceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPrivatePathServiceGatewayAccountPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareSource") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPrivatePathServiceGatewayAccountPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -18976,12 +19853,12 @@ func (vpc *VpcV1) GetShareSourceWithContext(ctx context.Context, getShareSourceO var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_share_source", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_private_path_service_gateway_account_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayAccountPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -18992,58 +19869,61 @@ func (vpc *VpcV1) GetShareSourceWithContext(ctx context.Context, getShareSourceO return } -// ListBackupPolicies : List backup policies -// This request lists backup policies in the region. Backup policies control which sources are selected for backup and -// include a set of backup policy plans that provide the backup schedules and deletion triggers. -func (vpc *VpcV1) ListBackupPolicies(listBackupPoliciesOptions *ListBackupPoliciesOptions) (result *BackupPolicyCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBackupPoliciesWithContext(context.Background(), listBackupPoliciesOptions) +// UpdatePrivatePathServiceGatewayAccountPolicy : Update an account policy for a private path service gateway +// This request updates an account policy with the information in a provided account policy patch. The account policy +// patch object is structured in the same way as a retrieved account policy and contains only the information to be +// updated. +func (vpc *VpcV1) UpdatePrivatePathServiceGatewayAccountPolicy(updatePrivatePathServiceGatewayAccountPolicyOptions *UpdatePrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdatePrivatePathServiceGatewayAccountPolicyWithContext(context.Background(), updatePrivatePathServiceGatewayAccountPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBackupPoliciesWithContext is an alternate form of the ListBackupPolicies method which supports a Context parameter -func (vpc *VpcV1) ListBackupPoliciesWithContext(ctx context.Context, listBackupPoliciesOptions *ListBackupPoliciesOptions) (result *BackupPolicyCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listBackupPoliciesOptions, "listBackupPoliciesOptions") +// UpdatePrivatePathServiceGatewayAccountPolicyWithContext is an alternate form of the UpdatePrivatePathServiceGatewayAccountPolicy method which supports a Context parameter +func (vpc *VpcV1) UpdatePrivatePathServiceGatewayAccountPolicyWithContext(ctx context.Context, updatePrivatePathServiceGatewayAccountPolicyOptions *UpdatePrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updatePrivatePathServiceGatewayAccountPolicyOptions, "updatePrivatePathServiceGatewayAccountPolicyOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(updatePrivatePathServiceGatewayAccountPolicyOptions, "updatePrivatePathServiceGatewayAccountPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "private_path_service_gateway_id": *updatePrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayID, + "id": *updatePrivatePathServiceGatewayAccountPolicyOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBackupPoliciesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePrivatePathServiceGatewayAccountPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBackupPolicies") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updatePrivatePathServiceGatewayAccountPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listBackupPoliciesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listBackupPoliciesOptions.Start)) - } - if listBackupPoliciesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listBackupPoliciesOptions.Limit)) - } - if listBackupPoliciesOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listBackupPoliciesOptions.ResourceGroupID)) - } - if listBackupPoliciesOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listBackupPoliciesOptions.Name)) - } - if listBackupPoliciesOptions.Tag != nil { - builder.AddQuery("tag", fmt.Sprint(*listBackupPoliciesOptions.Tag)) + + _, err = builder.SetBodyContentJSON(updatePrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayAccountPolicyPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -19055,12 +19935,12 @@ func (vpc *VpcV1) ListBackupPoliciesWithContext(ctx context.Context, listBackupP var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_backup_policies", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_private_path_service_gateway_account_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayAccountPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -19071,55 +19951,70 @@ func (vpc *VpcV1) ListBackupPoliciesWithContext(ctx context.Context, listBackupP return } -// CreateBackupPolicy : Create a backup policy -// This request creates a new backup policy from a backup policy prototype object. The prototype object is structured in -// the same way as a retrieved backup policy, and contains the information necessary to create the new backup policy. -func (vpc *VpcV1) CreateBackupPolicy(createBackupPolicyOptions *CreateBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateBackupPolicyWithContext(context.Background(), createBackupPolicyOptions) +// ListPrivatePathServiceGatewayEndpointGatewayBindings : List endpoint gateway bindings for a private path service gateway +// This request lists endpoint gateway bindings for a private path service gateway. Each endpoint gateway binding is +// implicitly created when an endpoint gateway is created targeting the private path service gateway. The associated +// account policy is applied to all new endpoint gateway bindings. If an associated account policy doesn't exist, the +// private path service gateway's `default_access_policy` is used. +// +// The endpoint gateway bindings will be sorted by their `created_at` property values, with newest endpoint gateway +// bindings first. Endpoint gateway bindings with identical +// `created_at` property values will in turn be sorted by ascending `name` property values. +func (vpc *VpcV1) ListPrivatePathServiceGatewayEndpointGatewayBindings(listPrivatePathServiceGatewayEndpointGatewayBindingsOptions *ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions) (result *PrivatePathServiceGatewayEndpointGatewayBindingCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListPrivatePathServiceGatewayEndpointGatewayBindingsWithContext(context.Background(), listPrivatePathServiceGatewayEndpointGatewayBindingsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateBackupPolicyWithContext is an alternate form of the CreateBackupPolicy method which supports a Context parameter -func (vpc *VpcV1) CreateBackupPolicyWithContext(ctx context.Context, createBackupPolicyOptions *CreateBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createBackupPolicyOptions, "createBackupPolicyOptions cannot be nil") +// ListPrivatePathServiceGatewayEndpointGatewayBindingsWithContext is an alternate form of the ListPrivatePathServiceGatewayEndpointGatewayBindings method which supports a Context parameter +func (vpc *VpcV1) ListPrivatePathServiceGatewayEndpointGatewayBindingsWithContext(ctx context.Context, listPrivatePathServiceGatewayEndpointGatewayBindingsOptions *ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions) (result *PrivatePathServiceGatewayEndpointGatewayBindingCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listPrivatePathServiceGatewayEndpointGatewayBindingsOptions, "listPrivatePathServiceGatewayEndpointGatewayBindingsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createBackupPolicyOptions, "createBackupPolicyOptions") + err = core.ValidateStruct(listPrivatePathServiceGatewayEndpointGatewayBindingsOptions, "listPrivatePathServiceGatewayEndpointGatewayBindingsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "private_path_service_gateway_id": *listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.PrivatePathServiceGatewayID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/endpoint_gateway_bindings`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createBackupPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPrivatePathServiceGatewayEndpointGatewayBindings") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBackupPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - _, err = builder.SetBodyContentJSON(createBackupPolicyOptions.BackupPolicyPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Start)) + } + if listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Limit)) + } + if listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Status != nil { + builder.AddQuery("status", fmt.Sprint(*listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Status)) + } + if listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.AccountID != nil { + builder.AddQuery("account.id", fmt.Sprint(*listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.AccountID)) } request, err := builder.Build() @@ -19131,12 +20026,12 @@ func (vpc *VpcV1) CreateBackupPolicyWithContext(ctx context.Context, createBacku var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_backup_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_private_path_service_gateway_endpoint_gateway_bindings", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayEndpointGatewayBindingCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -19147,77 +20042,53 @@ func (vpc *VpcV1) CreateBackupPolicyWithContext(ctx context.Context, createBacku return } -// ListBackupPolicyJobs : List jobs for a backup policy -// This request retrieves jobs for a backup policy. A backup job represents the execution of a backup policy plan for a -// resource matching the policy's criteria. -func (vpc *VpcV1) ListBackupPolicyJobs(listBackupPolicyJobsOptions *ListBackupPolicyJobsOptions) (result *BackupPolicyJobCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBackupPolicyJobsWithContext(context.Background(), listBackupPolicyJobsOptions) +// GetPrivatePathServiceGatewayEndpointGatewayBinding : Retrieve an endpoint gateway binding for a private path service gateway +// This request retrieves a single endpoint gateway binding specified by the identifier in the URL. +func (vpc *VpcV1) GetPrivatePathServiceGatewayEndpointGatewayBinding(getPrivatePathServiceGatewayEndpointGatewayBindingOptions *GetPrivatePathServiceGatewayEndpointGatewayBindingOptions) (result *PrivatePathServiceGatewayEndpointGatewayBinding, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetPrivatePathServiceGatewayEndpointGatewayBindingWithContext(context.Background(), getPrivatePathServiceGatewayEndpointGatewayBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBackupPolicyJobsWithContext is an alternate form of the ListBackupPolicyJobs method which supports a Context parameter -func (vpc *VpcV1) ListBackupPolicyJobsWithContext(ctx context.Context, listBackupPolicyJobsOptions *ListBackupPolicyJobsOptions) (result *BackupPolicyJobCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listBackupPolicyJobsOptions, "listBackupPolicyJobsOptions cannot be nil") +// GetPrivatePathServiceGatewayEndpointGatewayBindingWithContext is an alternate form of the GetPrivatePathServiceGatewayEndpointGatewayBinding method which supports a Context parameter +func (vpc *VpcV1) GetPrivatePathServiceGatewayEndpointGatewayBindingWithContext(ctx context.Context, getPrivatePathServiceGatewayEndpointGatewayBindingOptions *GetPrivatePathServiceGatewayEndpointGatewayBindingOptions) (result *PrivatePathServiceGatewayEndpointGatewayBinding, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getPrivatePathServiceGatewayEndpointGatewayBindingOptions, "getPrivatePathServiceGatewayEndpointGatewayBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listBackupPolicyJobsOptions, "listBackupPolicyJobsOptions") + err = core.ValidateStruct(getPrivatePathServiceGatewayEndpointGatewayBindingOptions, "getPrivatePathServiceGatewayEndpointGatewayBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "backup_policy_id": *listBackupPolicyJobsOptions.BackupPolicyID, + "private_path_service_gateway_id": *getPrivatePathServiceGatewayEndpointGatewayBindingOptions.PrivatePathServiceGatewayID, + "id": *getPrivatePathServiceGatewayEndpointGatewayBindingOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/jobs`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/endpoint_gateway_bindings/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBackupPolicyJobsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPrivatePathServiceGatewayEndpointGatewayBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBackupPolicyJobs") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPrivatePathServiceGatewayEndpointGatewayBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listBackupPolicyJobsOptions.Status != nil { - builder.AddQuery("status", fmt.Sprint(*listBackupPolicyJobsOptions.Status)) - } - if listBackupPolicyJobsOptions.BackupPolicyPlanID != nil { - builder.AddQuery("backup_policy_plan.id", fmt.Sprint(*listBackupPolicyJobsOptions.BackupPolicyPlanID)) - } - if listBackupPolicyJobsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listBackupPolicyJobsOptions.Start)) - } - if listBackupPolicyJobsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listBackupPolicyJobsOptions.Limit)) - } - if listBackupPolicyJobsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listBackupPolicyJobsOptions.Sort)) - } - if listBackupPolicyJobsOptions.SourceID != nil { - builder.AddQuery("source.id", fmt.Sprint(*listBackupPolicyJobsOptions.SourceID)) - } - if listBackupPolicyJobsOptions.TargetSnapshotsID != nil { - builder.AddQuery("target_snapshots[].id", fmt.Sprint(*listBackupPolicyJobsOptions.TargetSnapshotsID)) - } - if listBackupPolicyJobsOptions.TargetSnapshotsCRN != nil { - builder.AddQuery("target_snapshots[].crn", fmt.Sprint(*listBackupPolicyJobsOptions.TargetSnapshotsCRN)) - } request, err := builder.Build() if err != nil { @@ -19228,12 +20099,12 @@ func (vpc *VpcV1) ListBackupPolicyJobsWithContext(ctx context.Context, listBacku var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_backup_policy_jobs", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_private_path_service_gateway_endpoint_gateway_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyJobCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayEndpointGatewayBinding) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -19244,127 +20115,138 @@ func (vpc *VpcV1) ListBackupPolicyJobsWithContext(ctx context.Context, listBacku return } -// GetBackupPolicyJob : Retrieve a backup policy job -// This request retrieves a single backup policy job specified by the identifier in the URL. -func (vpc *VpcV1) GetBackupPolicyJob(getBackupPolicyJobOptions *GetBackupPolicyJobOptions) (result *BackupPolicyJob, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBackupPolicyJobWithContext(context.Background(), getBackupPolicyJobOptions) +// DenyPrivatePathServiceGatewayEndpointGatewayBinding : Deny an endpoint gateway binding for a private path service gateway +// This request denies a `pending` endpoint gateway request, and optionally sets the policy to deny future requests from +// the same account. +func (vpc *VpcV1) DenyPrivatePathServiceGatewayEndpointGatewayBinding(denyPrivatePathServiceGatewayEndpointGatewayBindingOptions *DenyPrivatePathServiceGatewayEndpointGatewayBindingOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DenyPrivatePathServiceGatewayEndpointGatewayBindingWithContext(context.Background(), denyPrivatePathServiceGatewayEndpointGatewayBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBackupPolicyJobWithContext is an alternate form of the GetBackupPolicyJob method which supports a Context parameter -func (vpc *VpcV1) GetBackupPolicyJobWithContext(ctx context.Context, getBackupPolicyJobOptions *GetBackupPolicyJobOptions) (result *BackupPolicyJob, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBackupPolicyJobOptions, "getBackupPolicyJobOptions cannot be nil") +// DenyPrivatePathServiceGatewayEndpointGatewayBindingWithContext is an alternate form of the DenyPrivatePathServiceGatewayEndpointGatewayBinding method which supports a Context parameter +func (vpc *VpcV1) DenyPrivatePathServiceGatewayEndpointGatewayBindingWithContext(ctx context.Context, denyPrivatePathServiceGatewayEndpointGatewayBindingOptions *DenyPrivatePathServiceGatewayEndpointGatewayBindingOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(denyPrivatePathServiceGatewayEndpointGatewayBindingOptions, "denyPrivatePathServiceGatewayEndpointGatewayBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getBackupPolicyJobOptions, "getBackupPolicyJobOptions") + err = core.ValidateStruct(denyPrivatePathServiceGatewayEndpointGatewayBindingOptions, "denyPrivatePathServiceGatewayEndpointGatewayBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "backup_policy_id": *getBackupPolicyJobOptions.BackupPolicyID, - "id": *getBackupPolicyJobOptions.ID, + "private_path_service_gateway_id": *denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.PrivatePathServiceGatewayID, + "id": *denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/jobs/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/endpoint_gateway_bindings/{id}/deny`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBackupPolicyJobOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DenyPrivatePathServiceGatewayEndpointGatewayBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBackupPolicyJob") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.SetAccountPolicy != nil { + body["set_account_policy"] = denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.SetAccountPolicy + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_backup_policy_job", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "deny_private_path_service_gateway_endpoint_gateway_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyJob) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListBackupPolicyPlans : List plans for a backup policy -// This request retrieves plans for a backup policy. Backup plans provide the backup schedule and deletion triggers. -func (vpc *VpcV1) ListBackupPolicyPlans(listBackupPolicyPlansOptions *ListBackupPolicyPlansOptions) (result *BackupPolicyPlanCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListBackupPolicyPlansWithContext(context.Background(), listBackupPolicyPlansOptions) +// PermitPrivatePathServiceGatewayEndpointGatewayBinding : Permit an endpoint gateway binding for a private path service gateway +// This request permits a `pending` endpoint gateway request, and optionally sets the policy to permit future requests +// from the same account. +func (vpc *VpcV1) PermitPrivatePathServiceGatewayEndpointGatewayBinding(permitPrivatePathServiceGatewayEndpointGatewayBindingOptions *PermitPrivatePathServiceGatewayEndpointGatewayBindingOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.PermitPrivatePathServiceGatewayEndpointGatewayBindingWithContext(context.Background(), permitPrivatePathServiceGatewayEndpointGatewayBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListBackupPolicyPlansWithContext is an alternate form of the ListBackupPolicyPlans method which supports a Context parameter -func (vpc *VpcV1) ListBackupPolicyPlansWithContext(ctx context.Context, listBackupPolicyPlansOptions *ListBackupPolicyPlansOptions) (result *BackupPolicyPlanCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listBackupPolicyPlansOptions, "listBackupPolicyPlansOptions cannot be nil") +// PermitPrivatePathServiceGatewayEndpointGatewayBindingWithContext is an alternate form of the PermitPrivatePathServiceGatewayEndpointGatewayBinding method which supports a Context parameter +func (vpc *VpcV1) PermitPrivatePathServiceGatewayEndpointGatewayBindingWithContext(ctx context.Context, permitPrivatePathServiceGatewayEndpointGatewayBindingOptions *PermitPrivatePathServiceGatewayEndpointGatewayBindingOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(permitPrivatePathServiceGatewayEndpointGatewayBindingOptions, "permitPrivatePathServiceGatewayEndpointGatewayBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listBackupPolicyPlansOptions, "listBackupPolicyPlansOptions") + err = core.ValidateStruct(permitPrivatePathServiceGatewayEndpointGatewayBindingOptions, "permitPrivatePathServiceGatewayEndpointGatewayBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "backup_policy_id": *listBackupPolicyPlansOptions.BackupPolicyID, + "private_path_service_gateway_id": *permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.PrivatePathServiceGatewayID, + "id": *permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/endpoint_gateway_bindings/{id}/permit`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listBackupPolicyPlansOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "PermitPrivatePathServiceGatewayEndpointGatewayBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListBackupPolicyPlans") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listBackupPolicyPlansOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listBackupPolicyPlansOptions.Name)) + + body := make(map[string]interface{}) + if permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.SetAccountPolicy != nil { + body["set_account_policy"] = permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.SetAccountPolicy + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -19373,104 +20255,131 @@ func (vpc *VpcV1) ListBackupPolicyPlansWithContext(ctx context.Context, listBack return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_backup_policy_plans", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "permit_private_path_service_gateway_endpoint_gateway_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlanCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateBackupPolicyPlan : Create a plan for a backup policy -// This request creates a new backup policy plan from a backup policy plan prototype object. The prototype object is -// structured in the same way as a retrieved backup policy plan, and contains the information necessary to create the -// new backup policy plan. -// -// Backups created by this plan will use the resource group of the source being backed up. -// -// Backups created by this plan will use the plan's name truncated to 46 characters, followed by a unique 16-character -// suffix. -func (vpc *VpcV1) CreateBackupPolicyPlan(createBackupPolicyPlanOptions *CreateBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateBackupPolicyPlanWithContext(context.Background(), createBackupPolicyPlanOptions) +// PublishPrivatePathServiceGateway : Publish a private path service gateway +// This request publishes a private path service gateway, allowing any account to request access to it. +func (vpc *VpcV1) PublishPrivatePathServiceGateway(publishPrivatePathServiceGatewayOptions *PublishPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.PublishPrivatePathServiceGatewayWithContext(context.Background(), publishPrivatePathServiceGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateBackupPolicyPlanWithContext is an alternate form of the CreateBackupPolicyPlan method which supports a Context parameter -func (vpc *VpcV1) CreateBackupPolicyPlanWithContext(ctx context.Context, createBackupPolicyPlanOptions *CreateBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createBackupPolicyPlanOptions, "createBackupPolicyPlanOptions cannot be nil") +// PublishPrivatePathServiceGatewayWithContext is an alternate form of the PublishPrivatePathServiceGateway method which supports a Context parameter +func (vpc *VpcV1) PublishPrivatePathServiceGatewayWithContext(ctx context.Context, publishPrivatePathServiceGatewayOptions *PublishPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(publishPrivatePathServiceGatewayOptions, "publishPrivatePathServiceGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createBackupPolicyPlanOptions, "createBackupPolicyPlanOptions") + err = core.ValidateStruct(publishPrivatePathServiceGatewayOptions, "publishPrivatePathServiceGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "backup_policy_id": *createBackupPolicyPlanOptions.BackupPolicyID, + "private_path_service_gateway_id": *publishPrivatePathServiceGatewayOptions.PrivatePathServiceGatewayID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/publish`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createBackupPolicyPlanOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "PublishPrivatePathServiceGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateBackupPolicyPlan") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range publishPrivatePathServiceGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createBackupPolicyPlanOptions.CronSpec != nil { - body["cron_spec"] = createBackupPolicyPlanOptions.CronSpec + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return } - if createBackupPolicyPlanOptions.Active != nil { - body["active"] = createBackupPolicyPlanOptions.Active + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "publish_private_path_service_gateway", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return } - if createBackupPolicyPlanOptions.AttachUserTags != nil { - body["attach_user_tags"] = createBackupPolicyPlanOptions.AttachUserTags + + return +} + +// RevokeAccountForPrivatePathServiceGateway : Revoke access to a private path service gateway for an account +// This request revokes a consumer account. This operation cannot be reversed. The `status` of all endpoint gateway +// bindings associated with the specified private path service gateway become `denied`. If the specified account has an +// existing access policy, that policy will be updated to `denied`. Otherwise, a new `deny` access policy will be +// created for the account. +func (vpc *VpcV1) RevokeAccountForPrivatePathServiceGateway(revokeAccountForPrivatePathServiceGatewayOptions *RevokeAccountForPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RevokeAccountForPrivatePathServiceGatewayWithContext(context.Background(), revokeAccountForPrivatePathServiceGatewayOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// RevokeAccountForPrivatePathServiceGatewayWithContext is an alternate form of the RevokeAccountForPrivatePathServiceGateway method which supports a Context parameter +func (vpc *VpcV1) RevokeAccountForPrivatePathServiceGatewayWithContext(ctx context.Context, revokeAccountForPrivatePathServiceGatewayOptions *RevokeAccountForPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(revokeAccountForPrivatePathServiceGatewayOptions, "revokeAccountForPrivatePathServiceGatewayOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return } - if createBackupPolicyPlanOptions.ClonePolicy != nil { - body["clone_policy"] = createBackupPolicyPlanOptions.ClonePolicy + err = core.ValidateStruct(revokeAccountForPrivatePathServiceGatewayOptions, "revokeAccountForPrivatePathServiceGatewayOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return } - if createBackupPolicyPlanOptions.CopyUserTags != nil { - body["copy_user_tags"] = createBackupPolicyPlanOptions.CopyUserTags + + pathParamsMap := map[string]string{ + "private_path_service_gateway_id": *revokeAccountForPrivatePathServiceGatewayOptions.PrivatePathServiceGatewayID, } - if createBackupPolicyPlanOptions.DeletionTrigger != nil { - body["deletion_trigger"] = createBackupPolicyPlanOptions.DeletionTrigger + + builder := core.NewRequestBuilder(core.POST) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/revoke_account`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return } - if createBackupPolicyPlanOptions.Name != nil { - body["name"] = createBackupPolicyPlanOptions.Name + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RevokeAccountForPrivatePathServiceGateway") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) } - if createBackupPolicyPlanOptions.RemoteRegionPolicies != nil { - body["remote_region_policies"] = createBackupPolicyPlanOptions.RemoteRegionPolicies + + for headerName, headerValue := range revokeAccountForPrivatePathServiceGatewayOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Content-Type", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + body := make(map[string]interface{}) + if revokeAccountForPrivatePathServiceGatewayOptions.Account != nil { + body["account"] = revokeAccountForPrivatePathServiceGatewayOptions.Account } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -19484,77 +20393,60 @@ func (vpc *VpcV1) CreateBackupPolicyPlanWithContext(ctx context.Context, createB return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "create_backup_policy_plan", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "revoke_account_for_private_path_service_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlan) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// DeleteBackupPolicyPlan : Delete a backup policy plan -// This request deletes a backup policy plan. This operation cannot be reversed. Any backups that have been created by -// the plan will remain but will no longer be subject to the plan's deletion trigger. Any running jobs associated with -// the plan will run to completion before the plan is deleted. -// -// If the request is accepted, the backup policy plan `status` will be set to `deleting`. Once deletion processing -// completes, the backup policy plan will no longer be retrievable. -func (vpc *VpcV1) DeleteBackupPolicyPlan(deleteBackupPolicyPlanOptions *DeleteBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteBackupPolicyPlanWithContext(context.Background(), deleteBackupPolicyPlanOptions) +// UnpublishPrivatePathServiceGateway : Unpublish a private path service gateway +// This request unpublishes a private path service gateway. For this request to succeed, any existing access from other +// accounts must first be revoked. Once unpublished, access will again be restricted to the account that created this +// private path service gateway. +func (vpc *VpcV1) UnpublishPrivatePathServiceGateway(unpublishPrivatePathServiceGatewayOptions *UnpublishPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.UnpublishPrivatePathServiceGatewayWithContext(context.Background(), unpublishPrivatePathServiceGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteBackupPolicyPlanWithContext is an alternate form of the DeleteBackupPolicyPlan method which supports a Context parameter -func (vpc *VpcV1) DeleteBackupPolicyPlanWithContext(ctx context.Context, deleteBackupPolicyPlanOptions *DeleteBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteBackupPolicyPlanOptions, "deleteBackupPolicyPlanOptions cannot be nil") +// UnpublishPrivatePathServiceGatewayWithContext is an alternate form of the UnpublishPrivatePathServiceGateway method which supports a Context parameter +func (vpc *VpcV1) UnpublishPrivatePathServiceGatewayWithContext(ctx context.Context, unpublishPrivatePathServiceGatewayOptions *UnpublishPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(unpublishPrivatePathServiceGatewayOptions, "unpublishPrivatePathServiceGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteBackupPolicyPlanOptions, "deleteBackupPolicyPlanOptions") + err = core.ValidateStruct(unpublishPrivatePathServiceGatewayOptions, "unpublishPrivatePathServiceGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "backup_policy_id": *deleteBackupPolicyPlanOptions.BackupPolicyID, - "id": *deleteBackupPolicyPlanOptions.ID, + "private_path_service_gateway_id": *unpublishPrivatePathServiceGatewayOptions.PrivatePathServiceGatewayID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/unpublish`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteBackupPolicyPlanOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UnpublishPrivatePathServiceGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBackupPolicyPlan") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range unpublishPrivatePathServiceGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - if deleteBackupPolicyPlanOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteBackupPolicyPlanOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -19565,72 +20457,65 @@ func (vpc *VpcV1) DeleteBackupPolicyPlanWithContext(ctx context.Context, deleteB return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_backup_policy_plan", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "unpublish_private_path_service_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlan) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetBackupPolicyPlan : Retrieve a backup policy plan -// This request retrieves a single backup policy plan specified by the identifier in the URL. -func (vpc *VpcV1) GetBackupPolicyPlan(getBackupPolicyPlanOptions *GetBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBackupPolicyPlanWithContext(context.Background(), getBackupPolicyPlanOptions) +// ListPublicAddressRanges : List public address ranges +// This request lists [public address ranges](https://cloud.ibm.com/docs/vpc?topic=vpc-about-par) in the region. A +// public address range is a contiguous block of public IP addresses that can be bound to a `target` that specifies a +// `vpc` and a `zone`. Incoming traffic for these IP addresses will be routed according to the VPC's ingress routing +// table. +func (vpc *VpcV1) ListPublicAddressRanges(listPublicAddressRangesOptions *ListPublicAddressRangesOptions) (result *PublicAddressRangeCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListPublicAddressRangesWithContext(context.Background(), listPublicAddressRangesOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBackupPolicyPlanWithContext is an alternate form of the GetBackupPolicyPlan method which supports a Context parameter -func (vpc *VpcV1) GetBackupPolicyPlanWithContext(ctx context.Context, getBackupPolicyPlanOptions *GetBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBackupPolicyPlanOptions, "getBackupPolicyPlanOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getBackupPolicyPlanOptions, "getBackupPolicyPlanOptions") +// ListPublicAddressRangesWithContext is an alternate form of the ListPublicAddressRanges method which supports a Context parameter +func (vpc *VpcV1) ListPublicAddressRangesWithContext(ctx context.Context, listPublicAddressRangesOptions *ListPublicAddressRangesOptions) (result *PublicAddressRangeCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listPublicAddressRangesOptions, "listPublicAddressRangesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "backup_policy_id": *getBackupPolicyPlanOptions.BackupPolicyID, - "id": *getBackupPolicyPlanOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_address_ranges`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBackupPolicyPlanOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPublicAddressRanges") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBackupPolicyPlan") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPublicAddressRangesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listPublicAddressRangesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listPublicAddressRangesOptions.Start)) + } + if listPublicAddressRangesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listPublicAddressRangesOptions.Limit)) + } + if listPublicAddressRangesOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listPublicAddressRangesOptions.ResourceGroupID)) + } request, err := builder.Build() if err != nil { @@ -19641,12 +20526,12 @@ func (vpc *VpcV1) GetBackupPolicyPlanWithContext(ctx context.Context, getBackupP var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_backup_policy_plan", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_public_address_ranges", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlan) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicAddressRangeCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -19657,60 +20542,66 @@ func (vpc *VpcV1) GetBackupPolicyPlanWithContext(ctx context.Context, getBackupP return } -// UpdateBackupPolicyPlan : Update a backup policy plan -// This request updates a backup policy plan with the information in a provided plan patch. The plan patch object is -// structured in the same way as a retrieved backup policy plan and can contains only the information to be updated. -func (vpc *VpcV1) UpdateBackupPolicyPlan(updateBackupPolicyPlanOptions *UpdateBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateBackupPolicyPlanWithContext(context.Background(), updateBackupPolicyPlanOptions) +// CreatePublicAddressRange : Create a public address range +// This request creates a new public address range from a public address range prototype object. The prototype object is +// structured in the same way as a retrieved public address range, and contains the information necessary to create the +// new public address range. +func (vpc *VpcV1) CreatePublicAddressRange(createPublicAddressRangeOptions *CreatePublicAddressRangeOptions) (result *PublicAddressRange, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreatePublicAddressRangeWithContext(context.Background(), createPublicAddressRangeOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateBackupPolicyPlanWithContext is an alternate form of the UpdateBackupPolicyPlan method which supports a Context parameter -func (vpc *VpcV1) UpdateBackupPolicyPlanWithContext(ctx context.Context, updateBackupPolicyPlanOptions *UpdateBackupPolicyPlanOptions) (result *BackupPolicyPlan, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateBackupPolicyPlanOptions, "updateBackupPolicyPlanOptions cannot be nil") +// CreatePublicAddressRangeWithContext is an alternate form of the CreatePublicAddressRange method which supports a Context parameter +func (vpc *VpcV1) CreatePublicAddressRangeWithContext(ctx context.Context, createPublicAddressRangeOptions *CreatePublicAddressRangeOptions) (result *PublicAddressRange, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createPublicAddressRangeOptions, "createPublicAddressRangeOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateBackupPolicyPlanOptions, "updateBackupPolicyPlanOptions") + err = core.ValidateStruct(createPublicAddressRangeOptions, "createPublicAddressRangeOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "backup_policy_id": *updateBackupPolicyPlanOptions.BackupPolicyID, - "id": *updateBackupPolicyPlanOptions.ID, - } - - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{backup_policy_id}/plans/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_address_ranges`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateBackupPolicyPlanOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePublicAddressRange") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBackupPolicyPlan") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPublicAddressRangeOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateBackupPolicyPlanOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateBackupPolicyPlanOptions.IfMatch)) - } + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateBackupPolicyPlanOptions.BackupPolicyPlanPatch) + body := make(map[string]interface{}) + if createPublicAddressRangeOptions.Ipv4AddressCount != nil { + body["ipv4_address_count"] = createPublicAddressRangeOptions.Ipv4AddressCount + } + if createPublicAddressRangeOptions.Name != nil { + body["name"] = createPublicAddressRangeOptions.Name + } + if createPublicAddressRangeOptions.ResourceGroup != nil { + body["resource_group"] = createPublicAddressRangeOptions.ResourceGroup + } + if createPublicAddressRangeOptions.Target != nil { + body["target"] = createPublicAddressRangeOptions.Target + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -19725,12 +20616,12 @@ func (vpc *VpcV1) UpdateBackupPolicyPlanWithContext(ctx context.Context, updateB var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_backup_policy_plan", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_public_address_range", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicyPlan) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicAddressRange) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -19741,55 +20632,50 @@ func (vpc *VpcV1) UpdateBackupPolicyPlanWithContext(ctx context.Context, updateB return } -// DeleteBackupPolicy : Delete a backup policy -// This request deletes a backup policy. This operation cannot be reversed. -// -// If the request is accepted, the backup policy `status` will be set to `deleting`. Once deletion processing completes, -// the backup policy will no longer be retrievable. -func (vpc *VpcV1) DeleteBackupPolicy(deleteBackupPolicyOptions *DeleteBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteBackupPolicyWithContext(context.Background(), deleteBackupPolicyOptions) +// DeletePublicAddressRange : Delete a public address range +// This request deletes a public address range. If the public address range is bound to a +// `target`, it will be unbound. This operation cannot be reversed. +func (vpc *VpcV1) DeletePublicAddressRange(deletePublicAddressRangeOptions *DeletePublicAddressRangeOptions) (result *PublicAddressRange, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeletePublicAddressRangeWithContext(context.Background(), deletePublicAddressRangeOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteBackupPolicyWithContext is an alternate form of the DeleteBackupPolicy method which supports a Context parameter -func (vpc *VpcV1) DeleteBackupPolicyWithContext(ctx context.Context, deleteBackupPolicyOptions *DeleteBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteBackupPolicyOptions, "deleteBackupPolicyOptions cannot be nil") +// DeletePublicAddressRangeWithContext is an alternate form of the DeletePublicAddressRange method which supports a Context parameter +func (vpc *VpcV1) DeletePublicAddressRangeWithContext(ctx context.Context, deletePublicAddressRangeOptions *DeletePublicAddressRangeOptions) (result *PublicAddressRange, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deletePublicAddressRangeOptions, "deletePublicAddressRangeOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteBackupPolicyOptions, "deleteBackupPolicyOptions") + err = core.ValidateStruct(deletePublicAddressRangeOptions, "deletePublicAddressRangeOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteBackupPolicyOptions.ID, + "id": *deletePublicAddressRangeOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_address_ranges/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteBackupPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePublicAddressRange") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteBackupPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePublicAddressRangeOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if deleteBackupPolicyOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteBackupPolicyOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -19803,12 +20689,12 @@ func (vpc *VpcV1) DeleteBackupPolicyWithContext(ctx context.Context, deleteBacku var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_backup_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_public_address_range", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicAddressRange) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -19819,46 +20705,46 @@ func (vpc *VpcV1) DeleteBackupPolicyWithContext(ctx context.Context, deleteBacku return } -// GetBackupPolicy : Retrieve a backup policy -// This request retrieves a single backup policy specified by the identifier in the URL. -func (vpc *VpcV1) GetBackupPolicy(getBackupPolicyOptions *GetBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetBackupPolicyWithContext(context.Background(), getBackupPolicyOptions) +// GetPublicAddressRange : Retrieve a public address range +// This request retrieves a single public address range specified by the identifier in the URL. +func (vpc *VpcV1) GetPublicAddressRange(getPublicAddressRangeOptions *GetPublicAddressRangeOptions) (result *PublicAddressRange, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetPublicAddressRangeWithContext(context.Background(), getPublicAddressRangeOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetBackupPolicyWithContext is an alternate form of the GetBackupPolicy method which supports a Context parameter -func (vpc *VpcV1) GetBackupPolicyWithContext(ctx context.Context, getBackupPolicyOptions *GetBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getBackupPolicyOptions, "getBackupPolicyOptions cannot be nil") +// GetPublicAddressRangeWithContext is an alternate form of the GetPublicAddressRange method which supports a Context parameter +func (vpc *VpcV1) GetPublicAddressRangeWithContext(ctx context.Context, getPublicAddressRangeOptions *GetPublicAddressRangeOptions) (result *PublicAddressRange, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getPublicAddressRangeOptions, "getPublicAddressRangeOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getBackupPolicyOptions, "getBackupPolicyOptions") + err = core.ValidateStruct(getPublicAddressRangeOptions, "getPublicAddressRangeOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getBackupPolicyOptions.ID, + "id": *getPublicAddressRangeOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_address_ranges/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getBackupPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPublicAddressRange") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetBackupPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPublicAddressRangeOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -19875,12 +20761,12 @@ func (vpc *VpcV1) GetBackupPolicyWithContext(ctx context.Context, getBackupPolic var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_backup_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_public_address_range", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicAddressRange) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -19891,59 +20777,57 @@ func (vpc *VpcV1) GetBackupPolicyWithContext(ctx context.Context, getBackupPolic return } -// UpdateBackupPolicy : Update a backup policy -// This request updates a backup policy with the information in a provided backup policy patch. The backup policy patch -// object is structured in the same way as a retrieved backup policy and contains only the information to be updated. -func (vpc *VpcV1) UpdateBackupPolicy(updateBackupPolicyOptions *UpdateBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateBackupPolicyWithContext(context.Background(), updateBackupPolicyOptions) +// UpdatePublicAddressRange : Update a public address range +// This request updates a public address range with the information in a provided public address range patch. The public +// address range patch object is structured in the same way as a retrieved public address range and contains only the +// information to be updated. +func (vpc *VpcV1) UpdatePublicAddressRange(updatePublicAddressRangeOptions *UpdatePublicAddressRangeOptions) (result *PublicAddressRange, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdatePublicAddressRangeWithContext(context.Background(), updatePublicAddressRangeOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateBackupPolicyWithContext is an alternate form of the UpdateBackupPolicy method which supports a Context parameter -func (vpc *VpcV1) UpdateBackupPolicyWithContext(ctx context.Context, updateBackupPolicyOptions *UpdateBackupPolicyOptions) (result BackupPolicyIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateBackupPolicyOptions, "updateBackupPolicyOptions cannot be nil") +// UpdatePublicAddressRangeWithContext is an alternate form of the UpdatePublicAddressRange method which supports a Context parameter +func (vpc *VpcV1) UpdatePublicAddressRangeWithContext(ctx context.Context, updatePublicAddressRangeOptions *UpdatePublicAddressRangeOptions) (result *PublicAddressRange, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updatePublicAddressRangeOptions, "updatePublicAddressRangeOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateBackupPolicyOptions, "updateBackupPolicyOptions") + err = core.ValidateStruct(updatePublicAddressRangeOptions, "updatePublicAddressRangeOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateBackupPolicyOptions.ID, + "id": *updatePublicAddressRangeOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/backup_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_address_ranges/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateBackupPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePublicAddressRange") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateBackupPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updatePublicAddressRangeOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateBackupPolicyOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateBackupPolicyOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateBackupPolicyOptions.BackupPolicyPatch) + _, err = builder.SetBodyContentJSON(updatePublicAddressRangeOptions.PublicAddressRangePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -19958,12 +20842,12 @@ func (vpc *VpcV1) UpdateBackupPolicyWithContext(ctx context.Context, updateBacku var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_backup_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_public_address_range", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackupPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicAddressRange) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -19974,21 +20858,19 @@ func (vpc *VpcV1) UpdateBackupPolicyWithContext(ctx context.Context, updateBacku return } -// ListRegions : List regions -// This request lists regions. Each region is a separate geographic area that contains multiple isolated zones. -// Resources can be provisioned into one or more zones in a region. Each zone is isolated, but connected to other zones -// in the same region with low-latency and high-bandwidth links. Regions represent the top-level of fault isolation -// available. Resources deployed within a single region also benefit from the low latency afforded by geographic -// proximity. -func (vpc *VpcV1) ListRegions(listRegionsOptions *ListRegionsOptions) (result *RegionCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListRegionsWithContext(context.Background(), listRegionsOptions) +// ListPublicGateways : List public gateways +// This request lists public gateways in the region. A public gateway is a virtual network device associated with a VPC, +// which allows access to the Internet. A public gateway resides in a zone and can be connected to subnets in the same +// zone only. +func (vpc *VpcV1) ListPublicGateways(listPublicGatewaysOptions *ListPublicGatewaysOptions) (result *PublicGatewayCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListPublicGatewaysWithContext(context.Background(), listPublicGatewaysOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListRegionsWithContext is an alternate form of the ListRegions method which supports a Context parameter -func (vpc *VpcV1) ListRegionsWithContext(ctx context.Context, listRegionsOptions *ListRegionsOptions) (result *RegionCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listRegionsOptions, "listRegionsOptions") +// ListPublicGatewaysWithContext is an alternate form of the ListPublicGateways method which supports a Context parameter +func (vpc *VpcV1) ListPublicGatewaysWithContext(ctx context.Context, listPublicGatewaysOptions *ListPublicGatewaysOptions) (result *PublicGatewayCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listPublicGatewaysOptions, "listPublicGatewaysOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -19997,24 +20879,33 @@ func (vpc *VpcV1) ListRegionsWithContext(ctx context.Context, listRegionsOptions builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/regions`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listRegionsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPublicGateways") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListRegions") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listPublicGatewaysOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listPublicGatewaysOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listPublicGatewaysOptions.Start)) + } + if listPublicGatewaysOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listPublicGatewaysOptions.Limit)) + } + if listPublicGatewaysOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listPublicGatewaysOptions.ResourceGroupID)) + } request, err := builder.Build() if err != nil { @@ -20025,12 +20916,12 @@ func (vpc *VpcV1) ListRegionsWithContext(ctx context.Context, listRegionsOptions var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_regions", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_public_gateways", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRegionCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGatewayCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20041,53 +20932,77 @@ func (vpc *VpcV1) ListRegionsWithContext(ctx context.Context, listRegionsOptions return } -// GetRegion : Retrieve a region -// This request retrieves a single region specified by the name in the URL. -func (vpc *VpcV1) GetRegion(getRegionOptions *GetRegionOptions) (result *Region, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetRegionWithContext(context.Background(), getRegionOptions) +// CreatePublicGateway : Create a public gateway +// This request creates a new public gateway from a public gateway prototype object. For this to succeed, the VPC must +// not already have a public gateway in the specified zone. +// +// If a floating IP is provided, it must be unbound. If a floating IP is not provided, one will be created and bound to +// the public gateway. Once a public gateway has been created, its floating IP cannot be unbound. A public gateway must +// be explicitly attached to each subnet it will provide connectivity for. +func (vpc *VpcV1) CreatePublicGateway(createPublicGatewayOptions *CreatePublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreatePublicGatewayWithContext(context.Background(), createPublicGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetRegionWithContext is an alternate form of the GetRegion method which supports a Context parameter -func (vpc *VpcV1) GetRegionWithContext(ctx context.Context, getRegionOptions *GetRegionOptions) (result *Region, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getRegionOptions, "getRegionOptions cannot be nil") +// CreatePublicGatewayWithContext is an alternate form of the CreatePublicGateway method which supports a Context parameter +func (vpc *VpcV1) CreatePublicGatewayWithContext(ctx context.Context, createPublicGatewayOptions *CreatePublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createPublicGatewayOptions, "createPublicGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getRegionOptions, "getRegionOptions") + err = core.ValidateStruct(createPublicGatewayOptions, "createPublicGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "name": *getRegionOptions.Name, - } - - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/regions/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getRegionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePublicGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetRegion") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createPublicGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createPublicGatewayOptions.VPC != nil { + body["vpc"] = createPublicGatewayOptions.VPC + } + if createPublicGatewayOptions.Zone != nil { + body["zone"] = createPublicGatewayOptions.Zone + } + if createPublicGatewayOptions.FloatingIP != nil { + body["floating_ip"] = createPublicGatewayOptions.FloatingIP + } + if createPublicGatewayOptions.Name != nil { + body["name"] = createPublicGatewayOptions.Name + } + if createPublicGatewayOptions.ResourceGroup != nil { + body["resource_group"] = createPublicGatewayOptions.ResourceGroup + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -20097,12 +21012,12 @@ func (vpc *VpcV1) GetRegionWithContext(ctx context.Context, getRegionOptions *Ge var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_region", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_public_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRegion) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20113,50 +21028,50 @@ func (vpc *VpcV1) GetRegionWithContext(ctx context.Context, getRegionOptions *Ge return } -// ListRegionZones : List zones in a region -// This request lists zones in a region. Zones represent logically-isolated data centers with high-bandwidth and -// low-latency interconnects to other zones in the same region. Faults in a zone do not affect other zones. -func (vpc *VpcV1) ListRegionZones(listRegionZonesOptions *ListRegionZonesOptions) (result *ZoneCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListRegionZonesWithContext(context.Background(), listRegionZonesOptions) +// DeletePublicGateway : Delete a public gateway +// This request deletes a public gateway. This operation cannot be reversed. For this request to succeed, the public +// gateway must not be attached to any subnets. The public gateway's floating IP will be automatically unbound. If the +// floating IP was created when the public gateway was created, it will be deleted. +func (vpc *VpcV1) DeletePublicGateway(deletePublicGatewayOptions *DeletePublicGatewayOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeletePublicGatewayWithContext(context.Background(), deletePublicGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListRegionZonesWithContext is an alternate form of the ListRegionZones method which supports a Context parameter -func (vpc *VpcV1) ListRegionZonesWithContext(ctx context.Context, listRegionZonesOptions *ListRegionZonesOptions) (result *ZoneCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listRegionZonesOptions, "listRegionZonesOptions cannot be nil") +// DeletePublicGatewayWithContext is an alternate form of the DeletePublicGateway method which supports a Context parameter +func (vpc *VpcV1) DeletePublicGatewayWithContext(ctx context.Context, deletePublicGatewayOptions *DeletePublicGatewayOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deletePublicGatewayOptions, "deletePublicGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listRegionZonesOptions, "listRegionZonesOptions") + err = core.ValidateStruct(deletePublicGatewayOptions, "deletePublicGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "region_name": *listRegionZonesOptions.RegionName, + "id": *deletePublicGatewayOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/regions/{region_name}/zones`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listRegionZonesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePublicGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListRegionZones") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deletePublicGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -20167,66 +21082,56 @@ func (vpc *VpcV1) ListRegionZonesWithContext(ctx context.Context, listRegionZone return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_region_zones", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_public_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalZoneCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetRegionZone : Retrieve a zone -// This request retrieves a single zone specified by the region and zone names in the URL. -func (vpc *VpcV1) GetRegionZone(getRegionZoneOptions *GetRegionZoneOptions) (result *Zone, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetRegionZoneWithContext(context.Background(), getRegionZoneOptions) +// GetPublicGateway : Retrieve a public gateway +// This request retrieves a single public gateway specified by the identifier in the URL. +func (vpc *VpcV1) GetPublicGateway(getPublicGatewayOptions *GetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetPublicGatewayWithContext(context.Background(), getPublicGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetRegionZoneWithContext is an alternate form of the GetRegionZone method which supports a Context parameter -func (vpc *VpcV1) GetRegionZoneWithContext(ctx context.Context, getRegionZoneOptions *GetRegionZoneOptions) (result *Zone, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getRegionZoneOptions, "getRegionZoneOptions cannot be nil") +// GetPublicGatewayWithContext is an alternate form of the GetPublicGateway method which supports a Context parameter +func (vpc *VpcV1) GetPublicGatewayWithContext(ctx context.Context, getPublicGatewayOptions *GetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getPublicGatewayOptions, "getPublicGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getRegionZoneOptions, "getRegionZoneOptions") + err = core.ValidateStruct(getPublicGatewayOptions, "getPublicGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "region_name": *getRegionZoneOptions.RegionName, - "name": *getRegionZoneOptions.Name, + "id": *getPublicGatewayOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/regions/{region_name}/zones/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getRegionZoneOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPublicGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetRegionZone") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getPublicGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -20243,12 +21148,12 @@ func (vpc *VpcV1) GetRegionZoneWithContext(ctx context.Context, getRegionZoneOpt var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_region_zone", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_public_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalZone) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20259,56 +21164,58 @@ func (vpc *VpcV1) GetRegionZoneWithContext(ctx context.Context, getRegionZoneOpt return } -// ListVirtualNetworkInterfaces : List virtual network interfaces -// This request lists virtual network interfaces in the region. A virtual network interface is a logical abstraction of -// a virtual network interface in a subnet, and may be attached to a target resource. -// -// The virtual network interfaces will be sorted by their `created_at` property values, with newest virtual network -// interfaces first. Virtual network interfaces with identical -// `created_at` property values will in turn be sorted by ascending `name` property values. -func (vpc *VpcV1) ListVirtualNetworkInterfaces(listVirtualNetworkInterfacesOptions *ListVirtualNetworkInterfacesOptions) (result *VirtualNetworkInterfaceCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVirtualNetworkInterfacesWithContext(context.Background(), listVirtualNetworkInterfacesOptions) +// UpdatePublicGateway : Update a public gateway +// This request updates a public gateway's name. +func (vpc *VpcV1) UpdatePublicGateway(updatePublicGatewayOptions *UpdatePublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdatePublicGatewayWithContext(context.Background(), updatePublicGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVirtualNetworkInterfacesWithContext is an alternate form of the ListVirtualNetworkInterfaces method which supports a Context parameter -func (vpc *VpcV1) ListVirtualNetworkInterfacesWithContext(ctx context.Context, listVirtualNetworkInterfacesOptions *ListVirtualNetworkInterfacesOptions) (result *VirtualNetworkInterfaceCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listVirtualNetworkInterfacesOptions, "listVirtualNetworkInterfacesOptions") +// UpdatePublicGatewayWithContext is an alternate form of the UpdatePublicGateway method which supports a Context parameter +func (vpc *VpcV1) UpdatePublicGatewayWithContext(ctx context.Context, updatePublicGatewayOptions *UpdatePublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updatePublicGatewayOptions, "updatePublicGatewayOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(updatePublicGatewayOptions, "updatePublicGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "id": *updatePublicGatewayOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVirtualNetworkInterfacesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePublicGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVirtualNetworkInterfaces") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updatePublicGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVirtualNetworkInterfacesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVirtualNetworkInterfacesOptions.Start)) - } - if listVirtualNetworkInterfacesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVirtualNetworkInterfacesOptions.Limit)) - } - if listVirtualNetworkInterfacesOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listVirtualNetworkInterfacesOptions.ResourceGroupID)) + + _, err = builder.SetBodyContentJSON(updatePublicGatewayOptions.PublicGatewayPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -20320,12 +21227,12 @@ func (vpc *VpcV1) ListVirtualNetworkInterfacesWithContext(ctx context.Context, l var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_virtual_network_interfaces", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_public_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterfaceCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20336,87 +21243,67 @@ func (vpc *VpcV1) ListVirtualNetworkInterfacesWithContext(ctx context.Context, l return } -// CreateVirtualNetworkInterface : Create a virtual network interface -// This request creates a new virtual network interface from a virtual network interface prototype object. The prototype -// object is structured in the same way as a retrieved virtual network interface, and contains the information necessary -// to create the new virtual network interface. -func (vpc *VpcV1) CreateVirtualNetworkInterface(createVirtualNetworkInterfaceOptions *CreateVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVirtualNetworkInterfaceWithContext(context.Background(), createVirtualNetworkInterfaceOptions) +// ListReservations : List reservations +// This request lists reservations in the region. A reservation provides reserved capacity for a specified profile in a +// specified zone. A reservation can also include a long-term committed use discount. +// +// The reservations will be sorted by their `created_at` property values, with newest reservations first. Reservations +// with identical `created_at` property values will in turn be sorted by ascending `name` property values. +func (vpc *VpcV1) ListReservations(listReservationsOptions *ListReservationsOptions) (result *ReservationCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListReservationsWithContext(context.Background(), listReservationsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVirtualNetworkInterfaceWithContext is an alternate form of the CreateVirtualNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) CreateVirtualNetworkInterfaceWithContext(ctx context.Context, createVirtualNetworkInterfaceOptions *CreateVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVirtualNetworkInterfaceOptions, "createVirtualNetworkInterfaceOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(createVirtualNetworkInterfaceOptions, "createVirtualNetworkInterfaceOptions") +// ListReservationsWithContext is an alternate form of the ListReservations method which supports a Context parameter +func (vpc *VpcV1) ListReservationsWithContext(ctx context.Context, listReservationsOptions *ListReservationsOptions) (result *ReservationCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listReservationsOptions, "listReservationsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVirtualNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListReservations") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVirtualNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listReservationsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if createVirtualNetworkInterfaceOptions.AllowIPSpoofing != nil { - body["allow_ip_spoofing"] = createVirtualNetworkInterfaceOptions.AllowIPSpoofing - } - if createVirtualNetworkInterfaceOptions.AutoDelete != nil { - body["auto_delete"] = createVirtualNetworkInterfaceOptions.AutoDelete - } - if createVirtualNetworkInterfaceOptions.EnableInfrastructureNat != nil { - body["enable_infrastructure_nat"] = createVirtualNetworkInterfaceOptions.EnableInfrastructureNat - } - if createVirtualNetworkInterfaceOptions.Ips != nil { - body["ips"] = createVirtualNetworkInterfaceOptions.Ips - } - if createVirtualNetworkInterfaceOptions.Name != nil { - body["name"] = createVirtualNetworkInterfaceOptions.Name + if listReservationsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listReservationsOptions.Start)) } - if createVirtualNetworkInterfaceOptions.PrimaryIP != nil { - body["primary_ip"] = createVirtualNetworkInterfaceOptions.PrimaryIP + if listReservationsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listReservationsOptions.Limit)) } - if createVirtualNetworkInterfaceOptions.ProtocolStateFilteringMode != nil { - body["protocol_state_filtering_mode"] = createVirtualNetworkInterfaceOptions.ProtocolStateFilteringMode + if listReservationsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listReservationsOptions.Name)) } - if createVirtualNetworkInterfaceOptions.ResourceGroup != nil { - body["resource_group"] = createVirtualNetworkInterfaceOptions.ResourceGroup + if listReservationsOptions.ProfileResourceType != nil { + builder.AddQuery("profile.resource_type", fmt.Sprint(*listReservationsOptions.ProfileResourceType)) } - if createVirtualNetworkInterfaceOptions.SecurityGroups != nil { - body["security_groups"] = createVirtualNetworkInterfaceOptions.SecurityGroups + if listReservationsOptions.AffinityPolicy != nil { + builder.AddQuery("affinity_policy", fmt.Sprint(*listReservationsOptions.AffinityPolicy)) } - if createVirtualNetworkInterfaceOptions.Subnet != nil { - body["subnet"] = createVirtualNetworkInterfaceOptions.Subnet + if listReservationsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listReservationsOptions.ResourceGroupID)) } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listReservationsOptions.ZoneName != nil { + builder.AddQuery("zone.name", fmt.Sprint(*listReservationsOptions.ZoneName)) } request, err := builder.Build() @@ -20428,12 +21315,12 @@ func (vpc *VpcV1) CreateVirtualNetworkInterfaceWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_virtual_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_reservations", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservationCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20444,55 +21331,79 @@ func (vpc *VpcV1) CreateVirtualNetworkInterfaceWithContext(ctx context.Context, return } -// DeleteVirtualNetworkInterfaces : Delete a virtual network interface -// This request deletes a virtual network interface. This operation cannot be reversed. For this request to succeed, the -// virtual network interface must not be required by another resource, such as the primary network attachment for an -// instance. -func (vpc *VpcV1) DeleteVirtualNetworkInterfaces(deleteVirtualNetworkInterfacesOptions *DeleteVirtualNetworkInterfacesOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteVirtualNetworkInterfacesWithContext(context.Background(), deleteVirtualNetworkInterfacesOptions) +// CreateReservation : Create a reservation +// This request creates a new reservation from a reservation prototype object. The prototype object is structured in the +// same way as a retrieved reservation, and contains the information necessary to create the new reservation. +func (vpc *VpcV1) CreateReservation(createReservationOptions *CreateReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateReservationWithContext(context.Background(), createReservationOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVirtualNetworkInterfacesWithContext is an alternate form of the DeleteVirtualNetworkInterfaces method which supports a Context parameter -func (vpc *VpcV1) DeleteVirtualNetworkInterfacesWithContext(ctx context.Context, deleteVirtualNetworkInterfacesOptions *DeleteVirtualNetworkInterfacesOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVirtualNetworkInterfacesOptions, "deleteVirtualNetworkInterfacesOptions cannot be nil") +// CreateReservationWithContext is an alternate form of the CreateReservation method which supports a Context parameter +func (vpc *VpcV1) CreateReservationWithContext(ctx context.Context, createReservationOptions *CreateReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createReservationOptions, "createReservationOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVirtualNetworkInterfacesOptions, "deleteVirtualNetworkInterfacesOptions") + err = core.ValidateStruct(createReservationOptions, "createReservationOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *deleteVirtualNetworkInterfacesOptions.ID, - } - - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVirtualNetworkInterfacesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateReservation") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVirtualNetworkInterfaces") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createReservationOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createReservationOptions.Capacity != nil { + body["capacity"] = createReservationOptions.Capacity + } + if createReservationOptions.CommittedUse != nil { + body["committed_use"] = createReservationOptions.CommittedUse + } + if createReservationOptions.Profile != nil { + body["profile"] = createReservationOptions.Profile + } + if createReservationOptions.Zone != nil { + body["zone"] = createReservationOptions.Zone + } + if createReservationOptions.AffinityPolicy != nil { + body["affinity_policy"] = createReservationOptions.AffinityPolicy + } + if createReservationOptions.Name != nil { + body["name"] = createReservationOptions.Name + } + if createReservationOptions.ResourceGroup != nil { + body["resource_group"] = createReservationOptions.ResourceGroup + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -20502,12 +21413,12 @@ func (vpc *VpcV1) DeleteVirtualNetworkInterfacesWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_virtual_network_interfaces", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_reservation", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservation) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20518,46 +21429,47 @@ func (vpc *VpcV1) DeleteVirtualNetworkInterfacesWithContext(ctx context.Context, return } -// GetVirtualNetworkInterface : Retrieve a virtual network interface -// This request retrieves a single virtual network interface specified by the identifier in the URL. -func (vpc *VpcV1) GetVirtualNetworkInterface(getVirtualNetworkInterfaceOptions *GetVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVirtualNetworkInterfaceWithContext(context.Background(), getVirtualNetworkInterfaceOptions) +// DeleteReservation : Delete a reservation +// This request deletes a reservation. This operation cannot be reversed. Reservations with a `status` of `active` are +// not allowed to be deleted. +func (vpc *VpcV1) DeleteReservation(deleteReservationOptions *DeleteReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteReservationWithContext(context.Background(), deleteReservationOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVirtualNetworkInterfaceWithContext is an alternate form of the GetVirtualNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) GetVirtualNetworkInterfaceWithContext(ctx context.Context, getVirtualNetworkInterfaceOptions *GetVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVirtualNetworkInterfaceOptions, "getVirtualNetworkInterfaceOptions cannot be nil") +// DeleteReservationWithContext is an alternate form of the DeleteReservation method which supports a Context parameter +func (vpc *VpcV1) DeleteReservationWithContext(ctx context.Context, deleteReservationOptions *DeleteReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteReservationOptions, "deleteReservationOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVirtualNetworkInterfaceOptions, "getVirtualNetworkInterfaceOptions") + err = core.ValidateStruct(deleteReservationOptions, "deleteReservationOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getVirtualNetworkInterfaceOptions.ID, + "id": *deleteReservationOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVirtualNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteReservation") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVirtualNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteReservationOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -20574,12 +21486,12 @@ func (vpc *VpcV1) GetVirtualNetworkInterfaceWithContext(ctx context.Context, get var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_virtual_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_reservation", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservation) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20590,62 +21502,53 @@ func (vpc *VpcV1) GetVirtualNetworkInterfaceWithContext(ctx context.Context, get return } -// UpdateVirtualNetworkInterface : Update a virtual network interface -// This request updates a virtual network interface with the information in a provided virtual network interface patch. -// The virtual network interface patch object is structured in the same way as a retrieved virtual network interface and -// contains only the information to be updated. -func (vpc *VpcV1) UpdateVirtualNetworkInterface(updateVirtualNetworkInterfaceOptions *UpdateVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVirtualNetworkInterfaceWithContext(context.Background(), updateVirtualNetworkInterfaceOptions) +// GetReservation : Retrieve a reservation +// This request retrieves a single reservation specified by identifier in the URL. +func (vpc *VpcV1) GetReservation(getReservationOptions *GetReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetReservationWithContext(context.Background(), getReservationOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVirtualNetworkInterfaceWithContext is an alternate form of the UpdateVirtualNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) UpdateVirtualNetworkInterfaceWithContext(ctx context.Context, updateVirtualNetworkInterfaceOptions *UpdateVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVirtualNetworkInterfaceOptions, "updateVirtualNetworkInterfaceOptions cannot be nil") +// GetReservationWithContext is an alternate form of the GetReservation method which supports a Context parameter +func (vpc *VpcV1) GetReservationWithContext(ctx context.Context, getReservationOptions *GetReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getReservationOptions, "getReservationOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVirtualNetworkInterfaceOptions, "updateVirtualNetworkInterfaceOptions") + err = core.ValidateStruct(getReservationOptions, "getReservationOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateVirtualNetworkInterfaceOptions.ID, + "id": *getReservationOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVirtualNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetReservation") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVirtualNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getReservationOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVirtualNetworkInterfaceOptions.VirtualNetworkInterfacePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -20655,12 +21558,12 @@ func (vpc *VpcV1) UpdateVirtualNetworkInterfaceWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_virtual_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_reservation", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservation) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20671,60 +21574,59 @@ func (vpc *VpcV1) UpdateVirtualNetworkInterfaceWithContext(ctx context.Context, return } -// ListNetworkInterfaceFloatingIps : List floating IPs associated with a virtual network interface -// This request lists floating IPs associated with a virtual network interface. -func (vpc *VpcV1) ListNetworkInterfaceFloatingIps(listNetworkInterfaceFloatingIpsOptions *ListNetworkInterfaceFloatingIpsOptions) (result *FloatingIPCollectionVirtualNetworkInterfaceContext, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListNetworkInterfaceFloatingIpsWithContext(context.Background(), listNetworkInterfaceFloatingIpsOptions) +// UpdateReservation : Update a reservation +// This request updates a reservation with the information provided in a reservation patch object. The patch object is +// structured in the same way as a retrieved reservation and needs to contain only the information to be updated. +func (vpc *VpcV1) UpdateReservation(updateReservationOptions *UpdateReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateReservationWithContext(context.Background(), updateReservationOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListNetworkInterfaceFloatingIpsWithContext is an alternate form of the ListNetworkInterfaceFloatingIps method which supports a Context parameter -func (vpc *VpcV1) ListNetworkInterfaceFloatingIpsWithContext(ctx context.Context, listNetworkInterfaceFloatingIpsOptions *ListNetworkInterfaceFloatingIpsOptions) (result *FloatingIPCollectionVirtualNetworkInterfaceContext, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listNetworkInterfaceFloatingIpsOptions, "listNetworkInterfaceFloatingIpsOptions cannot be nil") +// UpdateReservationWithContext is an alternate form of the UpdateReservation method which supports a Context parameter +func (vpc *VpcV1) UpdateReservationWithContext(ctx context.Context, updateReservationOptions *UpdateReservationOptions) (result *Reservation, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateReservationOptions, "updateReservationOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listNetworkInterfaceFloatingIpsOptions, "listNetworkInterfaceFloatingIpsOptions") + err = core.ValidateStruct(updateReservationOptions, "updateReservationOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "virtual_network_interface_id": *listNetworkInterfaceFloatingIpsOptions.VirtualNetworkInterfaceID, + "id": *updateReservationOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/floating_ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listNetworkInterfaceFloatingIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateReservation") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListNetworkInterfaceFloatingIps") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateReservationOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listNetworkInterfaceFloatingIpsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listNetworkInterfaceFloatingIpsOptions.Start)) - } - if listNetworkInterfaceFloatingIpsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listNetworkInterfaceFloatingIpsOptions.Limit)) - } - if listNetworkInterfaceFloatingIpsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listNetworkInterfaceFloatingIpsOptions.Sort)) + + _, err = builder.SetBodyContentJSON(updateReservationOptions.ReservationPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -20736,12 +21638,12 @@ func (vpc *VpcV1) ListNetworkInterfaceFloatingIpsWithContext(ctx context.Context var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_network_interface_floating_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_reservation", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPCollectionVirtualNetworkInterfaceContext) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservation) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20752,47 +21654,46 @@ func (vpc *VpcV1) ListNetworkInterfaceFloatingIpsWithContext(ctx context.Context return } -// RemoveNetworkInterfaceFloatingIP : Disassociate a floating IP from a virtual network interface -// This request disassociates the specified floating IP from the specified virtual network interface. -func (vpc *VpcV1) RemoveNetworkInterfaceFloatingIP(removeNetworkInterfaceFloatingIPOptions *RemoveNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RemoveNetworkInterfaceFloatingIPWithContext(context.Background(), removeNetworkInterfaceFloatingIPOptions) +// ActivateReservation : Activate a reservation +// This request activates a reservation. For this request to succeed, the reservation status must be `inactive`. +func (vpc *VpcV1) ActivateReservation(activateReservationOptions *ActivateReservationOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.ActivateReservationWithContext(context.Background(), activateReservationOptions) err = core.RepurposeSDKProblem(err, "") return } -// RemoveNetworkInterfaceFloatingIPWithContext is an alternate form of the RemoveNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) RemoveNetworkInterfaceFloatingIPWithContext(ctx context.Context, removeNetworkInterfaceFloatingIPOptions *RemoveNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(removeNetworkInterfaceFloatingIPOptions, "removeNetworkInterfaceFloatingIPOptions cannot be nil") +// ActivateReservationWithContext is an alternate form of the ActivateReservation method which supports a Context parameter +func (vpc *VpcV1) ActivateReservationWithContext(ctx context.Context, activateReservationOptions *ActivateReservationOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(activateReservationOptions, "activateReservationOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(removeNetworkInterfaceFloatingIPOptions, "removeNetworkInterfaceFloatingIPOptions") + err = core.ValidateStruct(activateReservationOptions, "activateReservationOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "virtual_network_interface_id": *removeNetworkInterfaceFloatingIPOptions.VirtualNetworkInterfaceID, - "id": *removeNetworkInterfaceFloatingIPOptions.ID, + "id": *activateReservationOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/reservations/{id}/activate`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range removeNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ActivateReservation") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range activateReservationOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -20807,7 +21708,7 @@ func (vpc *VpcV1) RemoveNetworkInterfaceFloatingIPWithContext(ctx context.Contex response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "remove_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "activate_reservation", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -20815,54 +21716,63 @@ func (vpc *VpcV1) RemoveNetworkInterfaceFloatingIPWithContext(ctx context.Contex return } -// GetNetworkInterfaceFloatingIP : Retrieve associated floating IP -// This request retrieves a specified floating IP if it is associated with the virtual network interface specified in -// the URL. -func (vpc *VpcV1) GetNetworkInterfaceFloatingIP(getNetworkInterfaceFloatingIPOptions *GetNetworkInterfaceFloatingIPOptions) (result *FloatingIPReference, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetNetworkInterfaceFloatingIPWithContext(context.Background(), getNetworkInterfaceFloatingIPOptions) +// ListSecurityGroups : List security groups +// This request lists security groups in the region. A security group defines a set of packet filtering rules to allow +// traffic in and out of the resources targeted by the security group. No traffic is allowed by default. Security group +// rules are stateful so that reverse traffic in response to allowed traffic is automatically allowed. +func (vpc *VpcV1) ListSecurityGroups(listSecurityGroupsOptions *ListSecurityGroupsOptions) (result *SecurityGroupCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSecurityGroupsWithContext(context.Background(), listSecurityGroupsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetNetworkInterfaceFloatingIPWithContext is an alternate form of the GetNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) GetNetworkInterfaceFloatingIPWithContext(ctx context.Context, getNetworkInterfaceFloatingIPOptions *GetNetworkInterfaceFloatingIPOptions) (result *FloatingIPReference, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getNetworkInterfaceFloatingIPOptions, "getNetworkInterfaceFloatingIPOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getNetworkInterfaceFloatingIPOptions, "getNetworkInterfaceFloatingIPOptions") +// ListSecurityGroupsWithContext is an alternate form of the ListSecurityGroups method which supports a Context parameter +func (vpc *VpcV1) ListSecurityGroupsWithContext(ctx context.Context, listSecurityGroupsOptions *ListSecurityGroupsOptions) (result *SecurityGroupCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listSecurityGroupsOptions, "listSecurityGroupsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "virtual_network_interface_id": *getNetworkInterfaceFloatingIPOptions.VirtualNetworkInterfaceID, - "id": *getNetworkInterfaceFloatingIPOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSecurityGroups") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listSecurityGroupsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listSecurityGroupsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listSecurityGroupsOptions.Start)) + } + if listSecurityGroupsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listSecurityGroupsOptions.Limit)) + } + if listSecurityGroupsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listSecurityGroupsOptions.ResourceGroupID)) + } + if listSecurityGroupsOptions.VPCID != nil { + builder.AddQuery("vpc.id", fmt.Sprint(*listSecurityGroupsOptions.VPCID)) + } + if listSecurityGroupsOptions.VPCCRN != nil { + builder.AddQuery("vpc.crn", fmt.Sprint(*listSecurityGroupsOptions.VPCCRN)) + } + if listSecurityGroupsOptions.VPCName != nil { + builder.AddQuery("vpc.name", fmt.Sprint(*listSecurityGroupsOptions.VPCName)) + } request, err := builder.Build() if err != nil { @@ -20873,12 +21783,12 @@ func (vpc *VpcV1) GetNetworkInterfaceFloatingIPWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_security_groups", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20889,69 +21799,72 @@ func (vpc *VpcV1) GetNetworkInterfaceFloatingIPWithContext(ctx context.Context, return } -// AddNetworkInterfaceFloatingIP : Add an association between a floating IP and a virtual network interface -// This request adds an association between the specified floating IP and the specified virtual network interface. -// -// If the virtual network interface has `enable_infrastructure_nat` set to `true`, no more than one floating IP can be -// associated, and network address translation is performed between the floating IP address and the virtual network -// interface's `primary_ip` address. -// -// If the virtual network interface has `enable_infrastructure_nat` set to `false`, packets are passed unchanged to/from -// the virtual network interface. -// -// The floating IP must: -// - be in the same `zone` as the virtual network interface -// - not currently be associated with another resource -// -// The virtual network interface's `target` must not currently be a file share mount target. -// -// A request body is not required, and if provided, is ignored. -func (vpc *VpcV1) AddNetworkInterfaceFloatingIP(addNetworkInterfaceFloatingIPOptions *AddNetworkInterfaceFloatingIPOptions) (result *FloatingIPReference, response *core.DetailedResponse, err error) { - result, response, err = vpc.AddNetworkInterfaceFloatingIPWithContext(context.Background(), addNetworkInterfaceFloatingIPOptions) +// CreateSecurityGroup : Create a security group +// This request creates a new security group from a security group prototype object. The prototype object is structured +// in the same way as a retrieved security group, and contains the information necessary to create the new security +// group. If security group rules are included in the prototype object, those rules will be added to the security group. +// Each security group is scoped to one VPC. Only resources in that VPC can be added to the security group. +func (vpc *VpcV1) CreateSecurityGroup(createSecurityGroupOptions *CreateSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateSecurityGroupWithContext(context.Background(), createSecurityGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// AddNetworkInterfaceFloatingIPWithContext is an alternate form of the AddNetworkInterfaceFloatingIP method which supports a Context parameter -func (vpc *VpcV1) AddNetworkInterfaceFloatingIPWithContext(ctx context.Context, addNetworkInterfaceFloatingIPOptions *AddNetworkInterfaceFloatingIPOptions) (result *FloatingIPReference, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(addNetworkInterfaceFloatingIPOptions, "addNetworkInterfaceFloatingIPOptions cannot be nil") +// CreateSecurityGroupWithContext is an alternate form of the CreateSecurityGroup method which supports a Context parameter +func (vpc *VpcV1) CreateSecurityGroupWithContext(ctx context.Context, createSecurityGroupOptions *CreateSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createSecurityGroupOptions, "createSecurityGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(addNetworkInterfaceFloatingIPOptions, "addNetworkInterfaceFloatingIPOptions") + err = core.ValidateStruct(createSecurityGroupOptions, "createSecurityGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "virtual_network_interface_id": *addNetworkInterfaceFloatingIPOptions.VirtualNetworkInterfaceID, - "id": *addNetworkInterfaceFloatingIPOptions.ID, - } - - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range addNetworkInterfaceFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSecurityGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddNetworkInterfaceFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createSecurityGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createSecurityGroupOptions.VPC != nil { + body["vpc"] = createSecurityGroupOptions.VPC + } + if createSecurityGroupOptions.Name != nil { + body["name"] = createSecurityGroupOptions.Name + } + if createSecurityGroupOptions.ResourceGroup != nil { + body["resource_group"] = createSecurityGroupOptions.ResourceGroup + } + if createSecurityGroupOptions.Rules != nil { + body["rules"] = createSecurityGroupOptions.Rules + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -20961,12 +21874,12 @@ func (vpc *VpcV1) AddNetworkInterfaceFloatingIPWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "add_network_interface_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_security_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -20977,61 +21890,52 @@ func (vpc *VpcV1) AddNetworkInterfaceFloatingIPWithContext(ctx context.Context, return } -// ListVirtualNetworkInterfaceIps : List reserved IPs bound to a virtual network interface -// This request lists reserved IPs bound to a virtual network interface. -func (vpc *VpcV1) ListVirtualNetworkInterfaceIps(listVirtualNetworkInterfaceIpsOptions *ListVirtualNetworkInterfaceIpsOptions) (result *ReservedIPCollectionVirtualNetworkInterfaceContext, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVirtualNetworkInterfaceIpsWithContext(context.Background(), listVirtualNetworkInterfaceIpsOptions) +// DeleteSecurityGroup : Delete a security group +// This request deletes a security group. A security group cannot be deleted if it is referenced by any security group +// targets or rules. Additionally, a VPC's default security group cannot be deleted. This operation cannot be reversed. +func (vpc *VpcV1) DeleteSecurityGroup(deleteSecurityGroupOptions *DeleteSecurityGroupOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteSecurityGroupWithContext(context.Background(), deleteSecurityGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVirtualNetworkInterfaceIpsWithContext is an alternate form of the ListVirtualNetworkInterfaceIps method which supports a Context parameter -func (vpc *VpcV1) ListVirtualNetworkInterfaceIpsWithContext(ctx context.Context, listVirtualNetworkInterfaceIpsOptions *ListVirtualNetworkInterfaceIpsOptions) (result *ReservedIPCollectionVirtualNetworkInterfaceContext, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVirtualNetworkInterfaceIpsOptions, "listVirtualNetworkInterfaceIpsOptions cannot be nil") +// DeleteSecurityGroupWithContext is an alternate form of the DeleteSecurityGroup method which supports a Context parameter +func (vpc *VpcV1) DeleteSecurityGroupWithContext(ctx context.Context, deleteSecurityGroupOptions *DeleteSecurityGroupOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSecurityGroupOptions, "deleteSecurityGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVirtualNetworkInterfaceIpsOptions, "listVirtualNetworkInterfaceIpsOptions") + err = core.ValidateStruct(deleteSecurityGroupOptions, "deleteSecurityGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "virtual_network_interface_id": *listVirtualNetworkInterfaceIpsOptions.VirtualNetworkInterfaceID, + "id": *deleteSecurityGroupOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVirtualNetworkInterfaceIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSecurityGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVirtualNetworkInterfaceIps") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteSecurityGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVirtualNetworkInterfaceIpsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVirtualNetworkInterfaceIpsOptions.Start)) - } - if listVirtualNetworkInterfaceIpsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVirtualNetworkInterfaceIpsOptions.Limit)) - } - if listVirtualNetworkInterfaceIpsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listVirtualNetworkInterfaceIpsOptions.Sort)) - } request, err := builder.Build() if err != nil { @@ -21039,71 +21943,59 @@ func (vpc *VpcV1) ListVirtualNetworkInterfaceIpsWithContext(ctx context.Context, return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_virtual_network_interface_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_security_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollectionVirtualNetworkInterfaceContext) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// RemoveVirtualNetworkInterfaceIP : Unbind a reserved IP from a virtual network interface -// This request unbinds the specified reserved IP from the specified virtual network interface. If the reserved IP has -// `auto_delete` set to `true`, the reserved IP will be deleted. -// -// The reserved IP for the `primary_ip` cannot be unbound. -func (vpc *VpcV1) RemoveVirtualNetworkInterfaceIP(removeVirtualNetworkInterfaceIPOptions *RemoveVirtualNetworkInterfaceIPOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RemoveVirtualNetworkInterfaceIPWithContext(context.Background(), removeVirtualNetworkInterfaceIPOptions) +// GetSecurityGroup : Retrieve a security group +// This request retrieves a single security group specified by the identifier in the URL path. +func (vpc *VpcV1) GetSecurityGroup(getSecurityGroupOptions *GetSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSecurityGroupWithContext(context.Background(), getSecurityGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// RemoveVirtualNetworkInterfaceIPWithContext is an alternate form of the RemoveVirtualNetworkInterfaceIP method which supports a Context parameter -func (vpc *VpcV1) RemoveVirtualNetworkInterfaceIPWithContext(ctx context.Context, removeVirtualNetworkInterfaceIPOptions *RemoveVirtualNetworkInterfaceIPOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(removeVirtualNetworkInterfaceIPOptions, "removeVirtualNetworkInterfaceIPOptions cannot be nil") +// GetSecurityGroupWithContext is an alternate form of the GetSecurityGroup method which supports a Context parameter +func (vpc *VpcV1) GetSecurityGroupWithContext(ctx context.Context, getSecurityGroupOptions *GetSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSecurityGroupOptions, "getSecurityGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(removeVirtualNetworkInterfaceIPOptions, "removeVirtualNetworkInterfaceIPOptions") + err = core.ValidateStruct(getSecurityGroupOptions, "getSecurityGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "virtual_network_interface_id": *removeVirtualNetworkInterfaceIPOptions.VirtualNetworkInterfaceID, - "id": *removeVirtualNetworkInterfaceIPOptions.ID, + "id": *getSecurityGroupOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range removeVirtualNetworkInterfaceIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSecurityGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveVirtualNetworkInterfaceIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSecurityGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -21114,65 +22006,81 @@ func (vpc *VpcV1) RemoveVirtualNetworkInterfaceIPWithContext(ctx context.Context return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "remove_virtual_network_interface_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_security_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroup) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetVirtualNetworkInterfaceIP : Retrieve bound reserved IP -// This request retrieves the specified reserved IP address if it is bound to the virtual network interface specified in -// the URL. -func (vpc *VpcV1) GetVirtualNetworkInterfaceIP(getVirtualNetworkInterfaceIPOptions *GetVirtualNetworkInterfaceIPOptions) (result *ReservedIPReference, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVirtualNetworkInterfaceIPWithContext(context.Background(), getVirtualNetworkInterfaceIPOptions) +// UpdateSecurityGroup : Update a security group +// This request updates a security group with the information provided in a security group patch object. The security +// group patch object is structured in the same way as a retrieved security group and contains only the information to +// be updated. +func (vpc *VpcV1) UpdateSecurityGroup(updateSecurityGroupOptions *UpdateSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateSecurityGroupWithContext(context.Background(), updateSecurityGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVirtualNetworkInterfaceIPWithContext is an alternate form of the GetVirtualNetworkInterfaceIP method which supports a Context parameter -func (vpc *VpcV1) GetVirtualNetworkInterfaceIPWithContext(ctx context.Context, getVirtualNetworkInterfaceIPOptions *GetVirtualNetworkInterfaceIPOptions) (result *ReservedIPReference, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVirtualNetworkInterfaceIPOptions, "getVirtualNetworkInterfaceIPOptions cannot be nil") +// UpdateSecurityGroupWithContext is an alternate form of the UpdateSecurityGroup method which supports a Context parameter +func (vpc *VpcV1) UpdateSecurityGroupWithContext(ctx context.Context, updateSecurityGroupOptions *UpdateSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateSecurityGroupOptions, "updateSecurityGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVirtualNetworkInterfaceIPOptions, "getVirtualNetworkInterfaceIPOptions") + err = core.ValidateStruct(updateSecurityGroupOptions, "updateSecurityGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "virtual_network_interface_id": *getVirtualNetworkInterfaceIPOptions.VirtualNetworkInterfaceID, - "id": *getVirtualNetworkInterfaceIPOptions.ID, + "id": *updateSecurityGroupOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVirtualNetworkInterfaceIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSecurityGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVirtualNetworkInterfaceIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateSecurityGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateSecurityGroupOptions.SecurityGroupPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -21182,12 +22090,12 @@ func (vpc *VpcV1) GetVirtualNetworkInterfaceIPWithContext(ctx context.Context, g var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_virtual_network_interface_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_security_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -21198,50 +22106,47 @@ func (vpc *VpcV1) GetVirtualNetworkInterfaceIPWithContext(ctx context.Context, g return } -// AddVirtualNetworkInterfaceIP : Bind a reserved IP to a virtual network interface -// This request binds the specified reserved IP to the specified virtual network interface. -// -// The reserved IP must currently be unbound and in the primary IP's subnet. The virtual network interface's `target` -// must not currently be a file share mount target. -func (vpc *VpcV1) AddVirtualNetworkInterfaceIP(addVirtualNetworkInterfaceIPOptions *AddVirtualNetworkInterfaceIPOptions) (result *ReservedIPReference, response *core.DetailedResponse, err error) { - result, response, err = vpc.AddVirtualNetworkInterfaceIPWithContext(context.Background(), addVirtualNetworkInterfaceIPOptions) +// ListSecurityGroupRules : List rules in a security group +// This request lists rules in a security group. These rules define what traffic the security group permits. Security +// group rules are stateful, such that reverse traffic in response to allowed traffic is automatically permitted. +func (vpc *VpcV1) ListSecurityGroupRules(listSecurityGroupRulesOptions *ListSecurityGroupRulesOptions) (result *SecurityGroupRuleCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSecurityGroupRulesWithContext(context.Background(), listSecurityGroupRulesOptions) err = core.RepurposeSDKProblem(err, "") return } -// AddVirtualNetworkInterfaceIPWithContext is an alternate form of the AddVirtualNetworkInterfaceIP method which supports a Context parameter -func (vpc *VpcV1) AddVirtualNetworkInterfaceIPWithContext(ctx context.Context, addVirtualNetworkInterfaceIPOptions *AddVirtualNetworkInterfaceIPOptions) (result *ReservedIPReference, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(addVirtualNetworkInterfaceIPOptions, "addVirtualNetworkInterfaceIPOptions cannot be nil") +// ListSecurityGroupRulesWithContext is an alternate form of the ListSecurityGroupRules method which supports a Context parameter +func (vpc *VpcV1) ListSecurityGroupRulesWithContext(ctx context.Context, listSecurityGroupRulesOptions *ListSecurityGroupRulesOptions) (result *SecurityGroupRuleCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listSecurityGroupRulesOptions, "listSecurityGroupRulesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(addVirtualNetworkInterfaceIPOptions, "addVirtualNetworkInterfaceIPOptions") + err = core.ValidateStruct(listSecurityGroupRulesOptions, "listSecurityGroupRulesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "virtual_network_interface_id": *addVirtualNetworkInterfaceIPOptions.VirtualNetworkInterfaceID, - "id": *addVirtualNetworkInterfaceIPOptions.ID, + "security_group_id": *listSecurityGroupRulesOptions.SecurityGroupID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range addVirtualNetworkInterfaceIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSecurityGroupRules") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddVirtualNetworkInterfaceIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listSecurityGroupRulesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -21258,12 +22163,12 @@ func (vpc *VpcV1) AddVirtualNetworkInterfaceIPWithContext(ctx context.Context, a var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "add_virtual_network_interface_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_security_group_rules", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupRuleCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -21274,49 +22179,63 @@ func (vpc *VpcV1) AddVirtualNetworkInterfaceIPWithContext(ctx context.Context, a return } -// ListClusterNetworkProfiles : List cluster network profiles -// This request lists cluster network profiles available in the region. A cluster network profile specifies the -// performance characteristics and capabilities for a cluster network. -func (vpc *VpcV1) ListClusterNetworkProfiles(listClusterNetworkProfilesOptions *ListClusterNetworkProfilesOptions) (result *ClusterNetworkProfileCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListClusterNetworkProfilesWithContext(context.Background(), listClusterNetworkProfilesOptions) +// CreateSecurityGroupRule : Create a rule for a security group +// This request creates a new security group rule from a security group rule prototype object. The prototype object is +// structured in the same way as a retrieved security group rule and contains the information necessary to create the +// rule. As part of creating a new rule in a security group, the rule is applied to all the networking interfaces in the +// security group. Rules specify which IP traffic a security group will allow. Security group rules are stateful, such +// that reverse traffic in response to allowed traffic is automatically permitted. A rule allowing inbound TCP traffic +// on port 80 also allows outbound TCP traffic on port 80 without the need for an additional rule. +func (vpc *VpcV1) CreateSecurityGroupRule(createSecurityGroupRuleOptions *CreateSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateSecurityGroupRuleWithContext(context.Background(), createSecurityGroupRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListClusterNetworkProfilesWithContext is an alternate form of the ListClusterNetworkProfiles method which supports a Context parameter -func (vpc *VpcV1) ListClusterNetworkProfilesWithContext(ctx context.Context, listClusterNetworkProfilesOptions *ListClusterNetworkProfilesOptions) (result *ClusterNetworkProfileCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listClusterNetworkProfilesOptions, "listClusterNetworkProfilesOptions") +// CreateSecurityGroupRuleWithContext is an alternate form of the CreateSecurityGroupRule method which supports a Context parameter +func (vpc *VpcV1) CreateSecurityGroupRuleWithContext(ctx context.Context, createSecurityGroupRuleOptions *CreateSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createSecurityGroupRuleOptions, "createSecurityGroupRuleOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(createSecurityGroupRuleOptions, "createSecurityGroupRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "security_group_id": *createSecurityGroupRuleOptions.SecurityGroupID, + } + + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_network/profiles`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listClusterNetworkProfilesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSecurityGroupRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworkProfiles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createSecurityGroupRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listClusterNetworkProfilesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listClusterNetworkProfilesOptions.Start)) - } - if listClusterNetworkProfilesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listClusterNetworkProfilesOptions.Limit)) + + _, err = builder.SetBodyContentJSON(createSecurityGroupRuleOptions.SecurityGroupRulePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -21328,12 +22247,12 @@ func (vpc *VpcV1) ListClusterNetworkProfilesWithContext(ctx context.Context, lis var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_cluster_network_profiles", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_security_group_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkProfileCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupRule) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -21344,49 +22263,50 @@ func (vpc *VpcV1) ListClusterNetworkProfilesWithContext(ctx context.Context, lis return } -// GetClusterNetworkProfile : Retrieve a cluster network profile -// This request retrieves a single cluster network profile specified by the name in the URL. -func (vpc *VpcV1) GetClusterNetworkProfile(getClusterNetworkProfileOptions *GetClusterNetworkProfileOptions) (result *ClusterNetworkProfile, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetClusterNetworkProfileWithContext(context.Background(), getClusterNetworkProfileOptions) +// DeleteSecurityGroupRule : Delete a security group rule +// This request deletes a security group rule. This operation cannot be reversed. Removing a security group rule will +// not end existing connections allowed by that rule. +func (vpc *VpcV1) DeleteSecurityGroupRule(deleteSecurityGroupRuleOptions *DeleteSecurityGroupRuleOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteSecurityGroupRuleWithContext(context.Background(), deleteSecurityGroupRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetClusterNetworkProfileWithContext is an alternate form of the GetClusterNetworkProfile method which supports a Context parameter -func (vpc *VpcV1) GetClusterNetworkProfileWithContext(ctx context.Context, getClusterNetworkProfileOptions *GetClusterNetworkProfileOptions) (result *ClusterNetworkProfile, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getClusterNetworkProfileOptions, "getClusterNetworkProfileOptions cannot be nil") +// DeleteSecurityGroupRuleWithContext is an alternate form of the DeleteSecurityGroupRule method which supports a Context parameter +func (vpc *VpcV1) DeleteSecurityGroupRuleWithContext(ctx context.Context, deleteSecurityGroupRuleOptions *DeleteSecurityGroupRuleOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSecurityGroupRuleOptions, "deleteSecurityGroupRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getClusterNetworkProfileOptions, "getClusterNetworkProfileOptions") + err = core.ValidateStruct(deleteSecurityGroupRuleOptions, "deleteSecurityGroupRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "name": *getClusterNetworkProfileOptions.Name, + "security_group_id": *deleteSecurityGroupRuleOptions.SecurityGroupID, + "id": *deleteSecurityGroupRuleOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_network/profiles/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getClusterNetworkProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSecurityGroupRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetworkProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteSecurityGroupRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -21397,88 +22317,63 @@ func (vpc *VpcV1) GetClusterNetworkProfileWithContext(ctx context.Context, getCl return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_cluster_network_profile", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_security_group_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkProfile) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListClusterNetworks : List cluster networks -// This request lists [cluster networks](https://cloud.ibm.com/docs/vpc?topic=vpc-about-cluster-network) in the region. -// A cluster network is a grouping of resources in a separate networking space for high performance computing and -// networking. -func (vpc *VpcV1) ListClusterNetworks(listClusterNetworksOptions *ListClusterNetworksOptions) (result *ClusterNetworkCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListClusterNetworksWithContext(context.Background(), listClusterNetworksOptions) +// GetSecurityGroupRule : Retrieve a security group rule +// This request retrieves a single security group rule specified by the identifier in the URL path. +func (vpc *VpcV1) GetSecurityGroupRule(getSecurityGroupRuleOptions *GetSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSecurityGroupRuleWithContext(context.Background(), getSecurityGroupRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListClusterNetworksWithContext is an alternate form of the ListClusterNetworks method which supports a Context parameter -func (vpc *VpcV1) ListClusterNetworksWithContext(ctx context.Context, listClusterNetworksOptions *ListClusterNetworksOptions) (result *ClusterNetworkCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listClusterNetworksOptions, "listClusterNetworksOptions") +// GetSecurityGroupRuleWithContext is an alternate form of the GetSecurityGroupRule method which supports a Context parameter +func (vpc *VpcV1) GetSecurityGroupRuleWithContext(ctx context.Context, getSecurityGroupRuleOptions *GetSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSecurityGroupRuleOptions, "getSecurityGroupRuleOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getSecurityGroupRuleOptions, "getSecurityGroupRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "security_group_id": *getSecurityGroupRuleOptions.SecurityGroupID, + "id": *getSecurityGroupRuleOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listClusterNetworksOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSecurityGroupRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworks") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSecurityGroupRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listClusterNetworksOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listClusterNetworksOptions.Start)) - } - if listClusterNetworksOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listClusterNetworksOptions.Limit)) - } - if listClusterNetworksOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listClusterNetworksOptions.ResourceGroupID)) - } - if listClusterNetworksOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listClusterNetworksOptions.Name)) - } - if listClusterNetworksOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listClusterNetworksOptions.Sort)) - } - if listClusterNetworksOptions.VPCID != nil { - builder.AddQuery("vpc.id", fmt.Sprint(*listClusterNetworksOptions.VPCID)) - } - if listClusterNetworksOptions.VPCCRN != nil { - builder.AddQuery("vpc.crn", fmt.Sprint(*listClusterNetworksOptions.VPCCRN)) - } - if listClusterNetworksOptions.VPCName != nil { - builder.AddQuery("vpc.name", fmt.Sprint(*listClusterNetworksOptions.VPCName)) - } request, err := builder.Build() if err != nil { @@ -21489,12 +22384,12 @@ func (vpc *VpcV1) ListClusterNetworksWithContext(ctx context.Context, listCluste var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_cluster_networks", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_security_group_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupRule) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -21505,72 +22400,58 @@ func (vpc *VpcV1) ListClusterNetworksWithContext(ctx context.Context, listCluste return } -// CreateClusterNetwork : Create a cluster network -// This request creates a new cluster network from a cluster network prototype object. The prototype object is -// structured in the same way as a retrieved cluster network, and contains the information necessary to create the new -// cluster network. -func (vpc *VpcV1) CreateClusterNetwork(createClusterNetworkOptions *CreateClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateClusterNetworkWithContext(context.Background(), createClusterNetworkOptions) +// UpdateSecurityGroupRule : Update a security group rule +// This request updates a security group rule with the information in a provided rule patch object. The rule patch +// object contains only the information to be updated. The request will fail if the provided patch includes properties +// that are not used by the rule's protocol. +func (vpc *VpcV1) UpdateSecurityGroupRule(updateSecurityGroupRuleOptions *UpdateSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateSecurityGroupRuleWithContext(context.Background(), updateSecurityGroupRuleOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateClusterNetworkWithContext is an alternate form of the CreateClusterNetwork method which supports a Context parameter -func (vpc *VpcV1) CreateClusterNetworkWithContext(ctx context.Context, createClusterNetworkOptions *CreateClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createClusterNetworkOptions, "createClusterNetworkOptions cannot be nil") +// UpdateSecurityGroupRuleWithContext is an alternate form of the UpdateSecurityGroupRule method which supports a Context parameter +func (vpc *VpcV1) UpdateSecurityGroupRuleWithContext(ctx context.Context, updateSecurityGroupRuleOptions *UpdateSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateSecurityGroupRuleOptions, "updateSecurityGroupRuleOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createClusterNetworkOptions, "createClusterNetworkOptions") + err = core.ValidateStruct(updateSecurityGroupRuleOptions, "updateSecurityGroupRuleOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "security_group_id": *updateSecurityGroupRuleOptions.SecurityGroupID, + "id": *updateSecurityGroupRuleOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createClusterNetworkOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSecurityGroupRule") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetwork") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateSecurityGroupRuleOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createClusterNetworkOptions.Profile != nil { - body["profile"] = createClusterNetworkOptions.Profile - } - if createClusterNetworkOptions.VPC != nil { - body["vpc"] = createClusterNetworkOptions.VPC - } - if createClusterNetworkOptions.Zone != nil { - body["zone"] = createClusterNetworkOptions.Zone - } - if createClusterNetworkOptions.Name != nil { - body["name"] = createClusterNetworkOptions.Name - } - if createClusterNetworkOptions.ResourceGroup != nil { - body["resource_group"] = createClusterNetworkOptions.ResourceGroup - } - if createClusterNetworkOptions.SubnetPrefixes != nil { - body["subnet_prefixes"] = createClusterNetworkOptions.SubnetPrefixes - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(updateSecurityGroupRuleOptions.SecurityGroupRulePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -21585,12 +22466,12 @@ func (vpc *VpcV1) CreateClusterNetworkWithContext(ctx context.Context, createClu var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_cluster_network", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_security_group_rule", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetwork) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupRule) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -21601,68 +22482,57 @@ func (vpc *VpcV1) CreateClusterNetworkWithContext(ctx context.Context, createClu return } -// ListClusterNetworkInterfaces : List cluster network interfaces -// This request lists cluster network interfaces in the region. A cluster network interface is a logical abstraction of -// a cluster network interface in a subnet, and may be attached to a target resource. -// -// The cluster network interfaces will be sorted by their `created_at` property values, with newest cluster network -// interfaces first. Cluster network interfaces with identical -// `created_at` property values will in turn be sorted by ascending `name` property values. -func (vpc *VpcV1) ListClusterNetworkInterfaces(listClusterNetworkInterfacesOptions *ListClusterNetworkInterfacesOptions) (result *ClusterNetworkInterfaceCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListClusterNetworkInterfacesWithContext(context.Background(), listClusterNetworkInterfacesOptions) +// ListSecurityGroupTargets : List targets associated with a security group +// This request lists targets associated with a security group, to which the rules in the security group are applied. +func (vpc *VpcV1) ListSecurityGroupTargets(listSecurityGroupTargetsOptions *ListSecurityGroupTargetsOptions) (result *SecurityGroupTargetCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSecurityGroupTargetsWithContext(context.Background(), listSecurityGroupTargetsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListClusterNetworkInterfacesWithContext is an alternate form of the ListClusterNetworkInterfaces method which supports a Context parameter -func (vpc *VpcV1) ListClusterNetworkInterfacesWithContext(ctx context.Context, listClusterNetworkInterfacesOptions *ListClusterNetworkInterfacesOptions) (result *ClusterNetworkInterfaceCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listClusterNetworkInterfacesOptions, "listClusterNetworkInterfacesOptions cannot be nil") +// ListSecurityGroupTargetsWithContext is an alternate form of the ListSecurityGroupTargets method which supports a Context parameter +func (vpc *VpcV1) ListSecurityGroupTargetsWithContext(ctx context.Context, listSecurityGroupTargetsOptions *ListSecurityGroupTargetsOptions) (result *SecurityGroupTargetCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listSecurityGroupTargetsOptions, "listSecurityGroupTargetsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listClusterNetworkInterfacesOptions, "listClusterNetworkInterfacesOptions") + err = core.ValidateStruct(listSecurityGroupTargetsOptions, "listSecurityGroupTargetsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *listClusterNetworkInterfacesOptions.ClusterNetworkID, + "security_group_id": *listSecurityGroupTargetsOptions.SecurityGroupID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/targets`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listClusterNetworkInterfacesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSecurityGroupTargets") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworkInterfaces") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listSecurityGroupTargetsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listClusterNetworkInterfacesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listClusterNetworkInterfacesOptions.Start)) - } - if listClusterNetworkInterfacesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listClusterNetworkInterfacesOptions.Limit)) - } - if listClusterNetworkInterfacesOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listClusterNetworkInterfacesOptions.Name)) + if listSecurityGroupTargetsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listSecurityGroupTargetsOptions.Start)) } - if listClusterNetworkInterfacesOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listClusterNetworkInterfacesOptions.Sort)) + if listSecurityGroupTargetsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listSecurityGroupTargetsOptions.Limit)) } request, err := builder.Build() @@ -21674,12 +22544,12 @@ func (vpc *VpcV1) ListClusterNetworkInterfacesWithContext(ctx context.Context, l var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_cluster_network_interfaces", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_security_group_targets", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterfaceCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupTargetCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -21690,146 +22560,125 @@ func (vpc *VpcV1) ListClusterNetworkInterfacesWithContext(ctx context.Context, l return } -// CreateClusterNetworkInterface : Create a cluster network interface -// This request creates a new cluster network interface from a cluster network interface prototype object. The prototype -// object is structured in the same way as a retrieved cluster network interface, and contains the information necessary -// to create the new cluster network interface. -func (vpc *VpcV1) CreateClusterNetworkInterface(createClusterNetworkInterfaceOptions *CreateClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateClusterNetworkInterfaceWithContext(context.Background(), createClusterNetworkInterfaceOptions) +// DeleteSecurityGroupTargetBinding : Remove a target from a security group +// This request removes a target from a security group. For this request to succeed, the target must be attached to at +// least one other security group. The specified target identifier can be: +// +// - A bare metal server network interface identifier +// - A virtual network interface identifier +// - A VPN server identifier +// - A load balancer identifier +// - An endpoint gateway identifier +// - An instance network interface identifier +// +// Security groups are stateful, so any changes to a target's security groups are applied to new connections. Existing +// connections are not affected. +func (vpc *VpcV1) DeleteSecurityGroupTargetBinding(deleteSecurityGroupTargetBindingOptions *DeleteSecurityGroupTargetBindingOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteSecurityGroupTargetBindingWithContext(context.Background(), deleteSecurityGroupTargetBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateClusterNetworkInterfaceWithContext is an alternate form of the CreateClusterNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) CreateClusterNetworkInterfaceWithContext(ctx context.Context, createClusterNetworkInterfaceOptions *CreateClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createClusterNetworkInterfaceOptions, "createClusterNetworkInterfaceOptions cannot be nil") +// DeleteSecurityGroupTargetBindingWithContext is an alternate form of the DeleteSecurityGroupTargetBinding method which supports a Context parameter +func (vpc *VpcV1) DeleteSecurityGroupTargetBindingWithContext(ctx context.Context, deleteSecurityGroupTargetBindingOptions *DeleteSecurityGroupTargetBindingOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSecurityGroupTargetBindingOptions, "deleteSecurityGroupTargetBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createClusterNetworkInterfaceOptions, "createClusterNetworkInterfaceOptions") + err = core.ValidateStruct(deleteSecurityGroupTargetBindingOptions, "deleteSecurityGroupTargetBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *createClusterNetworkInterfaceOptions.ClusterNetworkID, + "security_group_id": *deleteSecurityGroupTargetBindingOptions.SecurityGroupID, + "id": *deleteSecurityGroupTargetBindingOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/targets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createClusterNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSecurityGroupTargetBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteSecurityGroupTargetBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createClusterNetworkInterfaceOptions.Name != nil { - body["name"] = createClusterNetworkInterfaceOptions.Name - } - if createClusterNetworkInterfaceOptions.PrimaryIP != nil { - body["primary_ip"] = createClusterNetworkInterfaceOptions.PrimaryIP - } - if createClusterNetworkInterfaceOptions.Subnet != nil { - body["subnet"] = createClusterNetworkInterfaceOptions.Subnet - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "create_cluster_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_security_group_target_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterface) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// DeleteClusterNetworkInterface : Delete a cluster network interface -// This request deletes a cluster network interface. This operation cannot be reversed. For this request to succeed, -// the cluster network interface must not be required by another resource, such as a cluster network attachment for a -// virtual server instance. -func (vpc *VpcV1) DeleteClusterNetworkInterface(deleteClusterNetworkInterfaceOptions *DeleteClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteClusterNetworkInterfaceWithContext(context.Background(), deleteClusterNetworkInterfaceOptions) +// GetSecurityGroupTarget : Retrieve a security group target +// This request retrieves a single target specified by the identifier in the URL path. The target must be an existing +// target of the security group. +func (vpc *VpcV1) GetSecurityGroupTarget(getSecurityGroupTargetOptions *GetSecurityGroupTargetOptions) (result SecurityGroupTargetReferenceIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSecurityGroupTargetWithContext(context.Background(), getSecurityGroupTargetOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteClusterNetworkInterfaceWithContext is an alternate form of the DeleteClusterNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) DeleteClusterNetworkInterfaceWithContext(ctx context.Context, deleteClusterNetworkInterfaceOptions *DeleteClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteClusterNetworkInterfaceOptions, "deleteClusterNetworkInterfaceOptions cannot be nil") +// GetSecurityGroupTargetWithContext is an alternate form of the GetSecurityGroupTarget method which supports a Context parameter +func (vpc *VpcV1) GetSecurityGroupTargetWithContext(ctx context.Context, getSecurityGroupTargetOptions *GetSecurityGroupTargetOptions) (result SecurityGroupTargetReferenceIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSecurityGroupTargetOptions, "getSecurityGroupTargetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteClusterNetworkInterfaceOptions, "deleteClusterNetworkInterfaceOptions") + err = core.ValidateStruct(getSecurityGroupTargetOptions, "getSecurityGroupTargetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *deleteClusterNetworkInterfaceOptions.ClusterNetworkID, - "id": *deleteClusterNetworkInterfaceOptions.ID, + "security_group_id": *getSecurityGroupTargetOptions.SecurityGroupID, + "id": *getSecurityGroupTargetOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/targets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteClusterNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSecurityGroupTarget") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteClusterNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSecurityGroupTargetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if deleteClusterNetworkInterfaceOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteClusterNetworkInterfaceOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -21843,12 +22692,12 @@ func (vpc *VpcV1) DeleteClusterNetworkInterfaceWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_cluster_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_security_group_target", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupTargetReference) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -21859,47 +22708,57 @@ func (vpc *VpcV1) DeleteClusterNetworkInterfaceWithContext(ctx context.Context, return } -// GetClusterNetworkInterface : Retrieve a cluster network interface -// This request retrieves a single cluster network interface specified by the identifier in the URL. -func (vpc *VpcV1) GetClusterNetworkInterface(getClusterNetworkInterfaceOptions *GetClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetClusterNetworkInterfaceWithContext(context.Background(), getClusterNetworkInterfaceOptions) +// CreateSecurityGroupTargetBinding : Add a target to a security group +// This request adds a resource to an existing security group. The specified target identifier can be: +// +// - A bare metal server network interface identifier +// - A virtual network interface identifier +// - A VPN server identifier +// - A load balancer identifier +// - An endpoint gateway identifier +// - An instance network interface identifier +// +// When a target is added to a security group, the security group rules are applied to the target. A request body is not +// required, and if provided, is ignored. +func (vpc *VpcV1) CreateSecurityGroupTargetBinding(createSecurityGroupTargetBindingOptions *CreateSecurityGroupTargetBindingOptions) (result SecurityGroupTargetReferenceIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateSecurityGroupTargetBindingWithContext(context.Background(), createSecurityGroupTargetBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetClusterNetworkInterfaceWithContext is an alternate form of the GetClusterNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) GetClusterNetworkInterfaceWithContext(ctx context.Context, getClusterNetworkInterfaceOptions *GetClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getClusterNetworkInterfaceOptions, "getClusterNetworkInterfaceOptions cannot be nil") +// CreateSecurityGroupTargetBindingWithContext is an alternate form of the CreateSecurityGroupTargetBinding method which supports a Context parameter +func (vpc *VpcV1) CreateSecurityGroupTargetBindingWithContext(ctx context.Context, createSecurityGroupTargetBindingOptions *CreateSecurityGroupTargetBindingOptions) (result SecurityGroupTargetReferenceIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createSecurityGroupTargetBindingOptions, "createSecurityGroupTargetBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getClusterNetworkInterfaceOptions, "getClusterNetworkInterfaceOptions") + err = core.ValidateStruct(createSecurityGroupTargetBindingOptions, "createSecurityGroupTargetBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *getClusterNetworkInterfaceOptions.ClusterNetworkID, - "id": *getClusterNetworkInterfaceOptions.ID, + "security_group_id": *createSecurityGroupTargetBindingOptions.SecurityGroupID, + "id": *createSecurityGroupTargetBindingOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/targets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getClusterNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSecurityGroupTargetBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createSecurityGroupTargetBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -21916,12 +22775,12 @@ func (vpc *VpcV1) GetClusterNetworkInterfaceWithContext(ctx context.Context, get var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_cluster_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_security_group_target_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupTargetReference) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -21932,64 +22791,52 @@ func (vpc *VpcV1) GetClusterNetworkInterfaceWithContext(ctx context.Context, get return } -// UpdateClusterNetworkInterface : Update a cluster network interface -// This request updates a cluster network interface with the information provided in a cluster network interface patch -// object. The patch object is structured in the same way as a retrieved cluster network interface and needs to contain -// only the information to be updated. -func (vpc *VpcV1) UpdateClusterNetworkInterface(updateClusterNetworkInterfaceOptions *UpdateClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateClusterNetworkInterfaceWithContext(context.Background(), updateClusterNetworkInterfaceOptions) +// ListShareProfiles : List file share profiles +// This request lists [file share profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-file-storage-profiles) available in +// the region. A file share profile specifies the performance characteristics and pricing model for a file share. +func (vpc *VpcV1) ListShareProfiles(listShareProfilesOptions *ListShareProfilesOptions) (result *ShareProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListShareProfilesWithContext(context.Background(), listShareProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateClusterNetworkInterfaceWithContext is an alternate form of the UpdateClusterNetworkInterface method which supports a Context parameter -func (vpc *VpcV1) UpdateClusterNetworkInterfaceWithContext(ctx context.Context, updateClusterNetworkInterfaceOptions *UpdateClusterNetworkInterfaceOptions) (result *ClusterNetworkInterface, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateClusterNetworkInterfaceOptions, "updateClusterNetworkInterfaceOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(updateClusterNetworkInterfaceOptions, "updateClusterNetworkInterfaceOptions") +// ListShareProfilesWithContext is an alternate form of the ListShareProfiles method which supports a Context parameter +func (vpc *VpcV1) ListShareProfilesWithContext(ctx context.Context, listShareProfilesOptions *ListShareProfilesOptions) (result *ShareProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listShareProfilesOptions, "listShareProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "cluster_network_id": *updateClusterNetworkInterfaceOptions.ClusterNetworkID, - "id": *updateClusterNetworkInterfaceOptions.ID, - } - - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/interfaces/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/share/profiles`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateClusterNetworkInterfaceOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShareProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateClusterNetworkInterface") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listShareProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateClusterNetworkInterfaceOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateClusterNetworkInterfaceOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - _, err = builder.SetBodyContentJSON(updateClusterNetworkInterfaceOptions.ClusterNetworkInterfacePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listShareProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listShareProfilesOptions.Start)) + } + if listShareProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listShareProfilesOptions.Limit)) + } + if listShareProfilesOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listShareProfilesOptions.Sort)) } request, err := builder.Build() @@ -22001,12 +22848,12 @@ func (vpc *VpcV1) UpdateClusterNetworkInterfaceWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_cluster_network_interface", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_share_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkInterface) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22017,64 +22864,132 @@ func (vpc *VpcV1) UpdateClusterNetworkInterfaceWithContext(ctx context.Context, return } -// ListClusterNetworkSubnets : List cluster network subnets -// This request lists cluster network subnets in the cluster network. A cluster network subnet provides network routing -// between other cluster network subnets within a cluster network. -func (vpc *VpcV1) ListClusterNetworkSubnets(listClusterNetworkSubnetsOptions *ListClusterNetworkSubnetsOptions) (result *ClusterNetworkSubnetCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListClusterNetworkSubnetsWithContext(context.Background(), listClusterNetworkSubnetsOptions) +// GetShareProfile : Retrieve a file share profile +// This request retrieves a single file share profile specified by the name in the URL. +func (vpc *VpcV1) GetShareProfile(getShareProfileOptions *GetShareProfileOptions) (result *ShareProfile, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetShareProfileWithContext(context.Background(), getShareProfileOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListClusterNetworkSubnetsWithContext is an alternate form of the ListClusterNetworkSubnets method which supports a Context parameter -func (vpc *VpcV1) ListClusterNetworkSubnetsWithContext(ctx context.Context, listClusterNetworkSubnetsOptions *ListClusterNetworkSubnetsOptions) (result *ClusterNetworkSubnetCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listClusterNetworkSubnetsOptions, "listClusterNetworkSubnetsOptions cannot be nil") +// GetShareProfileWithContext is an alternate form of the GetShareProfile method which supports a Context parameter +func (vpc *VpcV1) GetShareProfileWithContext(ctx context.Context, getShareProfileOptions *GetShareProfileOptions) (result *ShareProfile, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getShareProfileOptions, "getShareProfileOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listClusterNetworkSubnetsOptions, "listClusterNetworkSubnetsOptions") + err = core.ValidateStruct(getShareProfileOptions, "getShareProfileOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *listClusterNetworkSubnetsOptions.ClusterNetworkID, + "name": *getShareProfileOptions.Name, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/share/profiles/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listClusterNetworkSubnetsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworkSubnets") + for headerName, headerValue := range getShareProfileOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "get_share_profile", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareProfile) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// ListShares : List file shares +// This request lists file shares in the region. +func (vpc *VpcV1) ListShares(listSharesOptions *ListSharesOptions) (result *ShareCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSharesWithContext(context.Background(), listSharesOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListSharesWithContext is an alternate form of the ListShares method which supports a Context parameter +func (vpc *VpcV1) ListSharesWithContext(ctx context.Context, listSharesOptions *ListSharesOptions) (result *ShareCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listSharesOptions, "listSharesOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShares") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range listSharesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listClusterNetworkSubnetsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listClusterNetworkSubnetsOptions.Start)) + if listSharesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listSharesOptions.Start)) } - if listClusterNetworkSubnetsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listClusterNetworkSubnetsOptions.Limit)) + if listSharesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listSharesOptions.Limit)) } - if listClusterNetworkSubnetsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listClusterNetworkSubnetsOptions.Name)) + if listSharesOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listSharesOptions.ResourceGroupID)) } - if listClusterNetworkSubnetsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listClusterNetworkSubnetsOptions.Sort)) + if listSharesOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listSharesOptions.Name)) + } + if listSharesOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listSharesOptions.Sort)) + } + if listSharesOptions.ReplicationRole != nil { + builder.AddQuery("replication_role", fmt.Sprint(*listSharesOptions.ReplicationRole)) } request, err := builder.Build() @@ -22086,12 +23001,12 @@ func (vpc *VpcV1) ListClusterNetworkSubnetsWithContext(ctx context.Context, list var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_cluster_network_subnets", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_shares", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22102,48 +23017,46 @@ func (vpc *VpcV1) ListClusterNetworkSubnetsWithContext(ctx context.Context, list return } -// CreateClusterNetworkSubnet : Create a cluster network subnet -// This request creates a new cluster network subnet from a cluster network subnet prototype object. The prototype -// object is structured in the same way as a retrieved cluster network subnet, and contains the information necessary to -// create the new cluster network subnet. -func (vpc *VpcV1) CreateClusterNetworkSubnet(createClusterNetworkSubnetOptions *CreateClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateClusterNetworkSubnetWithContext(context.Background(), createClusterNetworkSubnetOptions) +// CreateShare : Create a file share +// This request provisions new file shares from a share prototype object. The new file shares can be a standalone share, +// a replica share, or both a source and replica share. +// +// The prototype object is structured in the same way as a retrieved share, and contains the information necessary to +// provision the new file shares. +func (vpc *VpcV1) CreateShare(createShareOptions *CreateShareOptions) (result *Share, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateShareWithContext(context.Background(), createShareOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateClusterNetworkSubnetWithContext is an alternate form of the CreateClusterNetworkSubnet method which supports a Context parameter -func (vpc *VpcV1) CreateClusterNetworkSubnetWithContext(ctx context.Context, createClusterNetworkSubnetOptions *CreateClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createClusterNetworkSubnetOptions, "createClusterNetworkSubnetOptions cannot be nil") +// CreateShareWithContext is an alternate form of the CreateShare method which supports a Context parameter +func (vpc *VpcV1) CreateShareWithContext(ctx context.Context, createShareOptions *CreateShareOptions) (result *Share, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createShareOptions, "createShareOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createClusterNetworkSubnetOptions, "createClusterNetworkSubnetOptions") + err = core.ValidateStruct(createShareOptions, "createShareOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "cluster_network_id": *createClusterNetworkSubnetOptions.ClusterNetworkID, - } - builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createClusterNetworkSubnetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateShare") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetworkSubnet") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createShareOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -22152,7 +23065,7 @@ func (vpc *VpcV1) CreateClusterNetworkSubnetWithContext(ctx context.Context, cre builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createClusterNetworkSubnetOptions.ClusterNetworkSubnetPrototype) + _, err = builder.SetBodyContentJSON(createShareOptions.SharePrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -22167,12 +23080,12 @@ func (vpc *VpcV1) CreateClusterNetworkSubnetWithContext(ctx context.Context, cre var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_cluster_network_subnet", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_share", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnet) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShare) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22183,65 +23096,61 @@ func (vpc *VpcV1) CreateClusterNetworkSubnetWithContext(ctx context.Context, cre return } -// ListClusterNetworkSubnetReservedIps : List cluster network subnet reserved IPs -// This request lists cluster network subnet reserved IPs in the cluster network. -func (vpc *VpcV1) ListClusterNetworkSubnetReservedIps(listClusterNetworkSubnetReservedIpsOptions *ListClusterNetworkSubnetReservedIpsOptions) (result *ClusterNetworkSubnetReservedIPCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListClusterNetworkSubnetReservedIpsWithContext(context.Background(), listClusterNetworkSubnetReservedIpsOptions) +// DeleteShare : Delete a file share +// This request deletes a share. This operation cannot be reversed. A share cannot be deleted if it: +// - has share mount targets +// - has a `lifecycle_state` of `updating` +// - has a replication operation in progress +// +// If the request is accepted, the share `lifecycle_state` will be set to `deleting`. Once deletion processing +// completes, it will no longer be retrievable. +func (vpc *VpcV1) DeleteShare(deleteShareOptions *DeleteShareOptions) (result *Share, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteShareWithContext(context.Background(), deleteShareOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListClusterNetworkSubnetReservedIpsWithContext is an alternate form of the ListClusterNetworkSubnetReservedIps method which supports a Context parameter -func (vpc *VpcV1) ListClusterNetworkSubnetReservedIpsWithContext(ctx context.Context, listClusterNetworkSubnetReservedIpsOptions *ListClusterNetworkSubnetReservedIpsOptions) (result *ClusterNetworkSubnetReservedIPCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listClusterNetworkSubnetReservedIpsOptions, "listClusterNetworkSubnetReservedIpsOptions cannot be nil") +// DeleteShareWithContext is an alternate form of the DeleteShare method which supports a Context parameter +func (vpc *VpcV1) DeleteShareWithContext(ctx context.Context, deleteShareOptions *DeleteShareOptions) (result *Share, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteShareOptions, "deleteShareOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listClusterNetworkSubnetReservedIpsOptions, "listClusterNetworkSubnetReservedIpsOptions") + err = core.ValidateStruct(deleteShareOptions, "deleteShareOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *listClusterNetworkSubnetReservedIpsOptions.ClusterNetworkID, - "cluster_network_subnet_id": *listClusterNetworkSubnetReservedIpsOptions.ClusterNetworkSubnetID, + "id": *deleteShareOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listClusterNetworkSubnetReservedIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShare") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListClusterNetworkSubnetReservedIps") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteShareOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + if deleteShareOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteShareOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listClusterNetworkSubnetReservedIpsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listClusterNetworkSubnetReservedIpsOptions.Start)) - } - if listClusterNetworkSubnetReservedIpsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listClusterNetworkSubnetReservedIpsOptions.Limit)) - } - if listClusterNetworkSubnetReservedIpsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listClusterNetworkSubnetReservedIpsOptions.Name)) - } - if listClusterNetworkSubnetReservedIpsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listClusterNetworkSubnetReservedIpsOptions.Sort)) - } request, err := builder.Build() if err != nil { @@ -22252,12 +23161,12 @@ func (vpc *VpcV1) ListClusterNetworkSubnetReservedIpsWithContext(ctx context.Con var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_cluster_network_subnet_reserved_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_share", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIPCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShare) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22268,70 +23177,53 @@ func (vpc *VpcV1) ListClusterNetworkSubnetReservedIpsWithContext(ctx context.Con return } -// CreateClusterNetworkSubnetReservedIP : Create a cluster network subnet reserved IP -// This request creates a new cluster network subnet reserved IP from a cluster network subnet reserved IP prototype -// object. The prototype object is structured in the same way as a retrieved cluster network subnet reserved IP, and -// contains the information necessary to create the new cluster network subnet reserved IP. -func (vpc *VpcV1) CreateClusterNetworkSubnetReservedIP(createClusterNetworkSubnetReservedIPOptions *CreateClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateClusterNetworkSubnetReservedIPWithContext(context.Background(), createClusterNetworkSubnetReservedIPOptions) +// GetShare : Retrieve a file share +// This request retrieves a single file share specified by the identifier in the URL. +func (vpc *VpcV1) GetShare(getShareOptions *GetShareOptions) (result *Share, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetShareWithContext(context.Background(), getShareOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateClusterNetworkSubnetReservedIPWithContext is an alternate form of the CreateClusterNetworkSubnetReservedIP method which supports a Context parameter -func (vpc *VpcV1) CreateClusterNetworkSubnetReservedIPWithContext(ctx context.Context, createClusterNetworkSubnetReservedIPOptions *CreateClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createClusterNetworkSubnetReservedIPOptions, "createClusterNetworkSubnetReservedIPOptions cannot be nil") +// GetShareWithContext is an alternate form of the GetShare method which supports a Context parameter +func (vpc *VpcV1) GetShareWithContext(ctx context.Context, getShareOptions *GetShareOptions) (result *Share, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getShareOptions, "getShareOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createClusterNetworkSubnetReservedIPOptions, "createClusterNetworkSubnetReservedIPOptions") + err = core.ValidateStruct(getShareOptions, "getShareOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *createClusterNetworkSubnetReservedIPOptions.ClusterNetworkID, - "cluster_network_subnet_id": *createClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetID, + "id": *getShareOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createClusterNetworkSubnetReservedIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShare") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateClusterNetworkSubnetReservedIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getShareOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createClusterNetworkSubnetReservedIPOptions.Address != nil { - body["address"] = createClusterNetworkSubnetReservedIPOptions.Address - } - if createClusterNetworkSubnetReservedIPOptions.Name != nil { - body["name"] = createClusterNetworkSubnetReservedIPOptions.Name - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -22341,12 +23233,12 @@ func (vpc *VpcV1) CreateClusterNetworkSubnetReservedIPWithContext(ctx context.Co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_cluster_network_subnet_reserved_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_share", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShare) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22357,61 +23249,64 @@ func (vpc *VpcV1) CreateClusterNetworkSubnetReservedIPWithContext(ctx context.Co return } -// DeleteClusterNetworkSubnetReservedIP : Delete a cluster network subnet reserved IP -// This request deletes a cluster network subnet reserved IP. This operation cannot be reversed. -// -// For this request to succeed, the reserved IP must be unbound. A provider-owned reserved IP is not allowed to be -// deleted. -func (vpc *VpcV1) DeleteClusterNetworkSubnetReservedIP(deleteClusterNetworkSubnetReservedIPOptions *DeleteClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteClusterNetworkSubnetReservedIPWithContext(context.Background(), deleteClusterNetworkSubnetReservedIPOptions) +// UpdateShare : Update a file share +// This request updates a share with the information in a provided share patch. The share patch object is structured in +// the same way as a retrieved share and contains only the information to be updated. +func (vpc *VpcV1) UpdateShare(updateShareOptions *UpdateShareOptions) (result *Share, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateShareWithContext(context.Background(), updateShareOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteClusterNetworkSubnetReservedIPWithContext is an alternate form of the DeleteClusterNetworkSubnetReservedIP method which supports a Context parameter -func (vpc *VpcV1) DeleteClusterNetworkSubnetReservedIPWithContext(ctx context.Context, deleteClusterNetworkSubnetReservedIPOptions *DeleteClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteClusterNetworkSubnetReservedIPOptions, "deleteClusterNetworkSubnetReservedIPOptions cannot be nil") +// UpdateShareWithContext is an alternate form of the UpdateShare method which supports a Context parameter +func (vpc *VpcV1) UpdateShareWithContext(ctx context.Context, updateShareOptions *UpdateShareOptions) (result *Share, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateShareOptions, "updateShareOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteClusterNetworkSubnetReservedIPOptions, "deleteClusterNetworkSubnetReservedIPOptions") + err = core.ValidateStruct(updateShareOptions, "updateShareOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *deleteClusterNetworkSubnetReservedIPOptions.ClusterNetworkID, - "cluster_network_subnet_id": *deleteClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetID, - "id": *deleteClusterNetworkSubnetReservedIPOptions.ID, + "id": *updateShareOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteClusterNetworkSubnetReservedIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateShare") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteClusterNetworkSubnetReservedIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateShareOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if deleteClusterNetworkSubnetReservedIPOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteClusterNetworkSubnetReservedIPOptions.IfMatch)) + builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateShareOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateShareOptions.IfMatch)) } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateShareOptions.SharePatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -22421,12 +23316,12 @@ func (vpc *VpcV1) DeleteClusterNetworkSubnetReservedIPWithContext(ctx context.Co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_cluster_network_subnet_reserved_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_share", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShare) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22437,54 +23332,61 @@ func (vpc *VpcV1) DeleteClusterNetworkSubnetReservedIPWithContext(ctx context.Co return } -// GetClusterNetworkSubnetReservedIP : Retrieve a cluster network subnet reserved IP -// This request retrieves a single cluster network subnet reserved IP specified by the identifier in the URL. -func (vpc *VpcV1) GetClusterNetworkSubnetReservedIP(getClusterNetworkSubnetReservedIPOptions *GetClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetClusterNetworkSubnetReservedIPWithContext(context.Background(), getClusterNetworkSubnetReservedIPOptions) +// ListShareAccessorBindings : List accessor bindings for a file share +// This request lists accessor bindings for a share. Each accessor binding identifies a resource (possibly in another +// account) with access to this file share including its snapshots. +// +// The share accessor bindings will be sorted by their `created_at` property values, with newest bindings first. +func (vpc *VpcV1) ListShareAccessorBindings(listShareAccessorBindingsOptions *ListShareAccessorBindingsOptions) (result *ShareAccessorBindingCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListShareAccessorBindingsWithContext(context.Background(), listShareAccessorBindingsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetClusterNetworkSubnetReservedIPWithContext is an alternate form of the GetClusterNetworkSubnetReservedIP method which supports a Context parameter -func (vpc *VpcV1) GetClusterNetworkSubnetReservedIPWithContext(ctx context.Context, getClusterNetworkSubnetReservedIPOptions *GetClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getClusterNetworkSubnetReservedIPOptions, "getClusterNetworkSubnetReservedIPOptions cannot be nil") +// ListShareAccessorBindingsWithContext is an alternate form of the ListShareAccessorBindings method which supports a Context parameter +func (vpc *VpcV1) ListShareAccessorBindingsWithContext(ctx context.Context, listShareAccessorBindingsOptions *ListShareAccessorBindingsOptions) (result *ShareAccessorBindingCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listShareAccessorBindingsOptions, "listShareAccessorBindingsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getClusterNetworkSubnetReservedIPOptions, "getClusterNetworkSubnetReservedIPOptions") + err = core.ValidateStruct(listShareAccessorBindingsOptions, "listShareAccessorBindingsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *getClusterNetworkSubnetReservedIPOptions.ClusterNetworkID, - "cluster_network_subnet_id": *getClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetID, - "id": *getClusterNetworkSubnetReservedIPOptions.ID, + "id": *listShareAccessorBindingsOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{id}/accessor_bindings`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getClusterNetworkSubnetReservedIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShareAccessorBindings") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetworkSubnetReservedIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listShareAccessorBindingsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listShareAccessorBindingsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listShareAccessorBindingsOptions.Start)) + } + if listShareAccessorBindingsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listShareAccessorBindingsOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -22495,12 +23397,12 @@ func (vpc *VpcV1) GetClusterNetworkSubnetReservedIPWithContext(ctx context.Conte var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_cluster_network_subnet_reserved_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_share_accessor_bindings", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareAccessorBindingCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22511,66 +23413,116 @@ func (vpc *VpcV1) GetClusterNetworkSubnetReservedIPWithContext(ctx context.Conte return } -// UpdateClusterNetworkSubnetReservedIP : Update a cluster network subnet reserved IP -// This request updates a cluster network subnet reserved IP with the information provided in a cluster network subnet -// reserved IP patch object. The patch object is structured in the same way as a retrieved cluster network subnet -// reserved IP and needs to contain only the information to be updated. -func (vpc *VpcV1) UpdateClusterNetworkSubnetReservedIP(updateClusterNetworkSubnetReservedIPOptions *UpdateClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateClusterNetworkSubnetReservedIPWithContext(context.Background(), updateClusterNetworkSubnetReservedIPOptions) +// DeleteShareAccessorBinding : Delete a file share accessor binding +// This request deletes a share accessor binding. This operation cannot be reversed. +func (vpc *VpcV1) DeleteShareAccessorBinding(deleteShareAccessorBindingOptions *DeleteShareAccessorBindingOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteShareAccessorBindingWithContext(context.Background(), deleteShareAccessorBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateClusterNetworkSubnetReservedIPWithContext is an alternate form of the UpdateClusterNetworkSubnetReservedIP method which supports a Context parameter -func (vpc *VpcV1) UpdateClusterNetworkSubnetReservedIPWithContext(ctx context.Context, updateClusterNetworkSubnetReservedIPOptions *UpdateClusterNetworkSubnetReservedIPOptions) (result *ClusterNetworkSubnetReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateClusterNetworkSubnetReservedIPOptions, "updateClusterNetworkSubnetReservedIPOptions cannot be nil") +// DeleteShareAccessorBindingWithContext is an alternate form of the DeleteShareAccessorBinding method which supports a Context parameter +func (vpc *VpcV1) DeleteShareAccessorBindingWithContext(ctx context.Context, deleteShareAccessorBindingOptions *DeleteShareAccessorBindingOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteShareAccessorBindingOptions, "deleteShareAccessorBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateClusterNetworkSubnetReservedIPOptions, "updateClusterNetworkSubnetReservedIPOptions") + err = core.ValidateStruct(deleteShareAccessorBindingOptions, "deleteShareAccessorBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *updateClusterNetworkSubnetReservedIPOptions.ClusterNetworkID, - "cluster_network_subnet_id": *updateClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetID, - "id": *updateClusterNetworkSubnetReservedIPOptions.ID, + "share_id": *deleteShareAccessorBindingOptions.ShareID, + "id": *deleteShareAccessorBindingOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{cluster_network_subnet_id}/reserved_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/accessor_bindings/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateClusterNetworkSubnetReservedIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShareAccessorBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateClusterNetworkSubnetReservedIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteShareAccessorBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateClusterNetworkSubnetReservedIPOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateClusterNetworkSubnetReservedIPOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateClusterNetworkSubnetReservedIPOptions.ClusterNetworkSubnetReservedIPPatch) + request, err := builder.Build() if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "delete_share_accessor_binding", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// GetShareAccessorBinding : Retrieve a file share accessor binding +// This request retrieves a single accessor binding specified by the identifier in the URL. +func (vpc *VpcV1) GetShareAccessorBinding(getShareAccessorBindingOptions *GetShareAccessorBindingOptions) (result *ShareAccessorBinding, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetShareAccessorBindingWithContext(context.Background(), getShareAccessorBindingOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetShareAccessorBindingWithContext is an alternate form of the GetShareAccessorBinding method which supports a Context parameter +func (vpc *VpcV1) GetShareAccessorBindingWithContext(ctx context.Context, getShareAccessorBindingOptions *GetShareAccessorBindingOptions) (result *ShareAccessorBinding, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getShareAccessorBindingOptions, "getShareAccessorBindingOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } + err = core.ValidateStruct(getShareAccessorBindingOptions, "getShareAccessorBindingOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "share_id": *getShareAccessorBindingOptions.ShareID, + "id": *getShareAccessorBindingOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/accessor_bindings/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareAccessorBinding") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range getShareAccessorBindingOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) request, err := builder.Build() if err != nil { @@ -22581,12 +23533,12 @@ func (vpc *VpcV1) UpdateClusterNetworkSubnetReservedIPWithContext(ctx context.Co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_cluster_network_subnet_reserved_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_share_accessor_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnetReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareAccessorBinding) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22597,131 +23549,145 @@ func (vpc *VpcV1) UpdateClusterNetworkSubnetReservedIPWithContext(ctx context.Co return } -// DeleteClusterNetworkSubnet : Delete a cluster network subnet -// This request deletes a cluster network subnet. This operation cannot be reversed. +// FailoverShare : Failover to replica file share +// This request triggers a failover to the replica file share specified by the identifier in the URL. The failover +// cannot be started if a source share or the replica share has a `lifecycle_state` of `updating`, or has a replication +// operation in progress. // -// For this request to succeed, this cluster subnet must not be attached to a cluster network interface. -func (vpc *VpcV1) DeleteClusterNetworkSubnet(deleteClusterNetworkSubnetOptions *DeleteClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteClusterNetworkSubnetWithContext(context.Background(), deleteClusterNetworkSubnetOptions) +// If `fallback_policy` is specified as `split`, and the request is accepted but the failover operation cannot be +// performed, a split will be triggered. +func (vpc *VpcV1) FailoverShare(failoverShareOptions *FailoverShareOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.FailoverShareWithContext(context.Background(), failoverShareOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteClusterNetworkSubnetWithContext is an alternate form of the DeleteClusterNetworkSubnet method which supports a Context parameter -func (vpc *VpcV1) DeleteClusterNetworkSubnetWithContext(ctx context.Context, deleteClusterNetworkSubnetOptions *DeleteClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteClusterNetworkSubnetOptions, "deleteClusterNetworkSubnetOptions cannot be nil") +// FailoverShareWithContext is an alternate form of the FailoverShare method which supports a Context parameter +func (vpc *VpcV1) FailoverShareWithContext(ctx context.Context, failoverShareOptions *FailoverShareOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(failoverShareOptions, "failoverShareOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteClusterNetworkSubnetOptions, "deleteClusterNetworkSubnetOptions") + err = core.ValidateStruct(failoverShareOptions, "failoverShareOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *deleteClusterNetworkSubnetOptions.ClusterNetworkID, - "id": *deleteClusterNetworkSubnetOptions.ID, + "share_id": *failoverShareOptions.ShareID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/failover`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteClusterNetworkSubnetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "FailoverShare") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteClusterNetworkSubnet") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range failoverShareOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - if deleteClusterNetworkSubnetOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteClusterNetworkSubnetOptions.IfMatch)) - } + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if failoverShareOptions.FallbackPolicy != nil { + body["fallback_policy"] = failoverShareOptions.FallbackPolicy + } + if failoverShareOptions.Timeout != nil { + body["timeout"] = failoverShareOptions.Timeout + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_cluster_network_subnet", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "failover_share", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnet) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// GetClusterNetworkSubnet : Retrieve a cluster network subnet -// This request retrieves a single cluster network subnet specified by the identifier in the URL. -func (vpc *VpcV1) GetClusterNetworkSubnet(getClusterNetworkSubnetOptions *GetClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetClusterNetworkSubnetWithContext(context.Background(), getClusterNetworkSubnetOptions) +// ListShareMountTargets : List mount targets for a file share +// This request lists mount targets for a file share. A mount target is a network endpoint at which a file share may be +// mounted. The file share can be mounted by clients in the same VPC and zone after creating share mount targets. +// +// The share mount targets will be sorted by their `created_at` property values, with newest targets first. +func (vpc *VpcV1) ListShareMountTargets(listShareMountTargetsOptions *ListShareMountTargetsOptions) (result *ShareMountTargetCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListShareMountTargetsWithContext(context.Background(), listShareMountTargetsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetClusterNetworkSubnetWithContext is an alternate form of the GetClusterNetworkSubnet method which supports a Context parameter -func (vpc *VpcV1) GetClusterNetworkSubnetWithContext(ctx context.Context, getClusterNetworkSubnetOptions *GetClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getClusterNetworkSubnetOptions, "getClusterNetworkSubnetOptions cannot be nil") +// ListShareMountTargetsWithContext is an alternate form of the ListShareMountTargets method which supports a Context parameter +func (vpc *VpcV1) ListShareMountTargetsWithContext(ctx context.Context, listShareMountTargetsOptions *ListShareMountTargetsOptions) (result *ShareMountTargetCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listShareMountTargetsOptions, "listShareMountTargetsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getClusterNetworkSubnetOptions, "getClusterNetworkSubnetOptions") + err = core.ValidateStruct(listShareMountTargetsOptions, "listShareMountTargetsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *getClusterNetworkSubnetOptions.ClusterNetworkID, - "id": *getClusterNetworkSubnetOptions.ID, + "share_id": *listShareMountTargetsOptions.ShareID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getClusterNetworkSubnetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShareMountTargets") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetworkSubnet") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listShareMountTargetsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listShareMountTargetsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listShareMountTargetsOptions.Name)) + } + if listShareMountTargetsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listShareMountTargetsOptions.Start)) + } + if listShareMountTargetsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listShareMountTargetsOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -22732,12 +23698,12 @@ func (vpc *VpcV1) GetClusterNetworkSubnetWithContext(ctx context.Context, getClu var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_cluster_network_subnet", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_share_mount_targets", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnet) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTargetCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22748,61 +23714,58 @@ func (vpc *VpcV1) GetClusterNetworkSubnetWithContext(ctx context.Context, getClu return } -// UpdateClusterNetworkSubnet : Update a cluster network subnet -// This request updates a cluster network subnet with the information provided in a cluster network subnet patch object. -// The patch object is structured in the same way as a retrieved cluster network subnet and needs to contain only the -// information to be updated. -func (vpc *VpcV1) UpdateClusterNetworkSubnet(updateClusterNetworkSubnetOptions *UpdateClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateClusterNetworkSubnetWithContext(context.Background(), updateClusterNetworkSubnetOptions) +// CreateShareMountTarget : Create a mount target for a file share +// This request creates a new share mount target from a share mount target prototype object. +// +// The prototype object is structured in the same way as a retrieved share mount target, and contains the information +// necessary to provision the new file share mount target. +func (vpc *VpcV1) CreateShareMountTarget(createShareMountTargetOptions *CreateShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateShareMountTargetWithContext(context.Background(), createShareMountTargetOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateClusterNetworkSubnetWithContext is an alternate form of the UpdateClusterNetworkSubnet method which supports a Context parameter -func (vpc *VpcV1) UpdateClusterNetworkSubnetWithContext(ctx context.Context, updateClusterNetworkSubnetOptions *UpdateClusterNetworkSubnetOptions) (result *ClusterNetworkSubnet, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateClusterNetworkSubnetOptions, "updateClusterNetworkSubnetOptions cannot be nil") +// CreateShareMountTargetWithContext is an alternate form of the CreateShareMountTarget method which supports a Context parameter +func (vpc *VpcV1) CreateShareMountTargetWithContext(ctx context.Context, createShareMountTargetOptions *CreateShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createShareMountTargetOptions, "createShareMountTargetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateClusterNetworkSubnetOptions, "updateClusterNetworkSubnetOptions") + err = core.ValidateStruct(createShareMountTargetOptions, "createShareMountTargetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "cluster_network_id": *updateClusterNetworkSubnetOptions.ClusterNetworkID, - "id": *updateClusterNetworkSubnetOptions.ID, + "share_id": *createShareMountTargetOptions.ShareID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{cluster_network_id}/subnets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateClusterNetworkSubnetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateShareMountTarget") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateClusterNetworkSubnet") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createShareMountTargetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateClusterNetworkSubnetOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateClusterNetworkSubnetOptions.IfMatch)) - } + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateClusterNetworkSubnetOptions.ClusterNetworkSubnetPatch) + _, err = builder.SetBodyContentJSON(createShareMountTargetOptions.ShareMountTargetPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -22817,12 +23780,12 @@ func (vpc *VpcV1) UpdateClusterNetworkSubnetWithContext(ctx context.Context, upd var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_cluster_network_subnet", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_share_mount_target", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetworkSubnet) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTarget) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22833,54 +23796,53 @@ func (vpc *VpcV1) UpdateClusterNetworkSubnetWithContext(ctx context.Context, upd return } -// DeleteClusterNetwork : Delete a cluster network -// This request deletes a cluster network. This operation cannot be reversed. +// DeleteShareMountTarget : Delete a file share mount target +// This request deletes a share mount target. This operation cannot be reversed. // -// For this request to succeed, virtual server instances must not reside in this cluster network. -func (vpc *VpcV1) DeleteClusterNetwork(deleteClusterNetworkOptions *DeleteClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { - result, response, err = vpc.DeleteClusterNetworkWithContext(context.Background(), deleteClusterNetworkOptions) +// If the request is accepted, the share mount target `lifecycle_state` will be set to +// `deleting`. Once deletion processing completes, it will no longer be retrievable. +func (vpc *VpcV1) DeleteShareMountTarget(deleteShareMountTargetOptions *DeleteShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteShareMountTargetWithContext(context.Background(), deleteShareMountTargetOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteClusterNetworkWithContext is an alternate form of the DeleteClusterNetwork method which supports a Context parameter -func (vpc *VpcV1) DeleteClusterNetworkWithContext(ctx context.Context, deleteClusterNetworkOptions *DeleteClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteClusterNetworkOptions, "deleteClusterNetworkOptions cannot be nil") +// DeleteShareMountTargetWithContext is an alternate form of the DeleteShareMountTarget method which supports a Context parameter +func (vpc *VpcV1) DeleteShareMountTargetWithContext(ctx context.Context, deleteShareMountTargetOptions *DeleteShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteShareMountTargetOptions, "deleteShareMountTargetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteClusterNetworkOptions, "deleteClusterNetworkOptions") + err = core.ValidateStruct(deleteShareMountTargetOptions, "deleteShareMountTargetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteClusterNetworkOptions.ID, + "share_id": *deleteShareMountTargetOptions.ShareID, + "id": *deleteShareMountTargetOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteClusterNetworkOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShareMountTarget") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteClusterNetwork") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteShareMountTargetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - if deleteClusterNetworkOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteClusterNetworkOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -22894,12 +23856,12 @@ func (vpc *VpcV1) DeleteClusterNetworkWithContext(ctx context.Context, deleteClu var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_cluster_network", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_share_mount_target", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetwork) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTarget) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22910,46 +23872,47 @@ func (vpc *VpcV1) DeleteClusterNetworkWithContext(ctx context.Context, deleteClu return } -// GetClusterNetwork : Retrieve a cluster network -// This request retrieves a single cluster network specified by the identifier in the URL. -func (vpc *VpcV1) GetClusterNetwork(getClusterNetworkOptions *GetClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetClusterNetworkWithContext(context.Background(), getClusterNetworkOptions) +// GetShareMountTarget : Retrieve a file share mount target +// This request retrieves a single share mount target specified by the identifier in the URL. +func (vpc *VpcV1) GetShareMountTarget(getShareMountTargetOptions *GetShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetShareMountTargetWithContext(context.Background(), getShareMountTargetOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetClusterNetworkWithContext is an alternate form of the GetClusterNetwork method which supports a Context parameter -func (vpc *VpcV1) GetClusterNetworkWithContext(ctx context.Context, getClusterNetworkOptions *GetClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getClusterNetworkOptions, "getClusterNetworkOptions cannot be nil") +// GetShareMountTargetWithContext is an alternate form of the GetShareMountTarget method which supports a Context parameter +func (vpc *VpcV1) GetShareMountTargetWithContext(ctx context.Context, getShareMountTargetOptions *GetShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getShareMountTargetOptions, "getShareMountTargetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getClusterNetworkOptions, "getClusterNetworkOptions") + err = core.ValidateStruct(getShareMountTargetOptions, "getShareMountTargetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getClusterNetworkOptions.ID, + "share_id": *getShareMountTargetOptions.ShareID, + "id": *getShareMountTargetOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getClusterNetworkOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareMountTarget") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetClusterNetwork") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getShareMountTargetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -22966,12 +23929,12 @@ func (vpc *VpcV1) GetClusterNetworkWithContext(ctx context.Context, getClusterNe var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_cluster_network", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_share_mount_target", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetwork) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTarget) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -22982,60 +23945,58 @@ func (vpc *VpcV1) GetClusterNetworkWithContext(ctx context.Context, getClusterNe return } -// UpdateClusterNetwork : Update a cluster -// This request updates a cluster network with the information provided in a cluster network patch object. The patch -// object is structured in the same way as a retrieved cluster network and needs to contain only the information to be -// updated. -func (vpc *VpcV1) UpdateClusterNetwork(updateClusterNetworkOptions *UpdateClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateClusterNetworkWithContext(context.Background(), updateClusterNetworkOptions) +// UpdateShareMountTarget : Update a file share mount target +// This request updates a share mount target with the information provided in a share mount target patch object. The +// share mount target patch object is structured in the same way as a retrieved share mount target and needs to contain +// only the information to be updated. +func (vpc *VpcV1) UpdateShareMountTarget(updateShareMountTargetOptions *UpdateShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateShareMountTargetWithContext(context.Background(), updateShareMountTargetOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateClusterNetworkWithContext is an alternate form of the UpdateClusterNetwork method which supports a Context parameter -func (vpc *VpcV1) UpdateClusterNetworkWithContext(ctx context.Context, updateClusterNetworkOptions *UpdateClusterNetworkOptions) (result *ClusterNetwork, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateClusterNetworkOptions, "updateClusterNetworkOptions cannot be nil") +// UpdateShareMountTargetWithContext is an alternate form of the UpdateShareMountTarget method which supports a Context parameter +func (vpc *VpcV1) UpdateShareMountTargetWithContext(ctx context.Context, updateShareMountTargetOptions *UpdateShareMountTargetOptions) (result *ShareMountTarget, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateShareMountTargetOptions, "updateShareMountTargetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateClusterNetworkOptions, "updateClusterNetworkOptions") + err = core.ValidateStruct(updateShareMountTargetOptions, "updateShareMountTargetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateClusterNetworkOptions.ID, + "share_id": *updateShareMountTargetOptions.ShareID, + "id": *updateShareMountTargetOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/cluster_networks/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/mount_targets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateClusterNetworkOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateShareMountTarget") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateClusterNetwork") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateShareMountTargetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateClusterNetworkOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateClusterNetworkOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateClusterNetworkOptions.ClusterNetworkPatch) + _, err = builder.SetBodyContentJSON(updateShareMountTargetOptions.ShareMountTargetPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -23050,12 +24011,12 @@ func (vpc *VpcV1) UpdateClusterNetworkWithContext(ctx context.Context, updateClu var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_cluster_network", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_share_mount_target", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalClusterNetwork) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareMountTarget) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23066,53 +24027,69 @@ func (vpc *VpcV1) UpdateClusterNetworkWithContext(ctx context.Context, updateClu return } -// ListPublicGateways : List public gateways -// This request lists public gateways in the region. A public gateway is a virtual network device associated with a VPC, -// which allows access to the Internet. A public gateway resides in a zone and can be connected to subnets in the same -// zone only. -func (vpc *VpcV1) ListPublicGateways(listPublicGatewaysOptions *ListPublicGatewaysOptions) (result *PublicGatewayCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListPublicGatewaysWithContext(context.Background(), listPublicGatewaysOptions) +// ListShareSnapshots : List file share snapshots +// This request lists snapshots for the specified file share, or across all accessible file shares. A snapshot preserves +// the data of a share at the time the snapshot was captured. +// +// If the file share is a replica, the list will contain snapshots corresponding to snapshots on the source. +func (vpc *VpcV1) ListShareSnapshots(listShareSnapshotsOptions *ListShareSnapshotsOptions) (result *ShareSnapshotCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListShareSnapshotsWithContext(context.Background(), listShareSnapshotsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListPublicGatewaysWithContext is an alternate form of the ListPublicGateways method which supports a Context parameter -func (vpc *VpcV1) ListPublicGatewaysWithContext(ctx context.Context, listPublicGatewaysOptions *ListPublicGatewaysOptions) (result *PublicGatewayCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listPublicGatewaysOptions, "listPublicGatewaysOptions") +// ListShareSnapshotsWithContext is an alternate form of the ListShareSnapshots method which supports a Context parameter +func (vpc *VpcV1) ListShareSnapshotsWithContext(ctx context.Context, listShareSnapshotsOptions *ListShareSnapshotsOptions) (result *ShareSnapshotCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listShareSnapshotsOptions, "listShareSnapshotsOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listShareSnapshotsOptions, "listShareSnapshotsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "share_id": *listShareSnapshotsOptions.ShareID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listPublicGatewaysOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListShareSnapshots") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPublicGateways") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listShareSnapshotsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listPublicGatewaysOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listPublicGatewaysOptions.Start)) + if listShareSnapshotsOptions.BackupPolicyPlanID != nil { + builder.AddQuery("backup_policy_plan.id", fmt.Sprint(*listShareSnapshotsOptions.BackupPolicyPlanID)) } - if listPublicGatewaysOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listPublicGatewaysOptions.Limit)) + if listShareSnapshotsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listShareSnapshotsOptions.Name)) } - if listPublicGatewaysOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listPublicGatewaysOptions.ResourceGroupID)) + if listShareSnapshotsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listShareSnapshotsOptions.Start)) + } + if listShareSnapshotsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listShareSnapshotsOptions.Limit)) + } + if listShareSnapshotsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listShareSnapshotsOptions.Sort)) } request, err := builder.Build() @@ -23124,12 +24101,12 @@ func (vpc *VpcV1) ListPublicGatewaysWithContext(ctx context.Context, listPublicG var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_public_gateways", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_share_snapshots", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGatewayCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshotCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23140,47 +24117,57 @@ func (vpc *VpcV1) ListPublicGatewaysWithContext(ctx context.Context, listPublicG return } -// CreatePublicGateway : Create a public gateway -// This request creates a new public gateway from a public gateway prototype object. For this to succeed, the VPC must -// not already have a public gateway in the specified zone. +// CreateShareSnapshot : Create a snapshot for a file share +// This request creates a new share snapshot from a share snapshot prototype object. The prototype object is structured +// in the same way as a retrieved share snapshot, and contains the information necessary to create the new share +// snapshot. // -// If a floating IP is provided, it must be unbound. If a floating IP is not provided, one will be created and bound to -// the public gateway. Once a public gateway has been created, its floating IP cannot be unbound. A public gateway must -// be explicitly attached to each subnet it will provide connectivity for. -func (vpc *VpcV1) CreatePublicGateway(createPublicGatewayOptions *CreatePublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreatePublicGatewayWithContext(context.Background(), createPublicGatewayOptions) +// The share must have an `access_control_mode` of `security_group` and a `replication_role` of `source` or `none`. +// +// The snapshot will inherit its `resource_group` and encryption settings from the share. +// +// If the share has a `replication_role` of `source`, a corresponding snapshot on the replica share will be created with +// a `status` of `pending`. It will remain in +// `pending` until the data is synchronized per the replication schedule determined by the replica share's +// `replication_cron_spec`. +func (vpc *VpcV1) CreateShareSnapshot(createShareSnapshotOptions *CreateShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateShareSnapshotWithContext(context.Background(), createShareSnapshotOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreatePublicGatewayWithContext is an alternate form of the CreatePublicGateway method which supports a Context parameter -func (vpc *VpcV1) CreatePublicGatewayWithContext(ctx context.Context, createPublicGatewayOptions *CreatePublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createPublicGatewayOptions, "createPublicGatewayOptions cannot be nil") +// CreateShareSnapshotWithContext is an alternate form of the CreateShareSnapshot method which supports a Context parameter +func (vpc *VpcV1) CreateShareSnapshotWithContext(ctx context.Context, createShareSnapshotOptions *CreateShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createShareSnapshotOptions, "createShareSnapshotOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createPublicGatewayOptions, "createPublicGatewayOptions") + err = core.ValidateStruct(createShareSnapshotOptions, "createShareSnapshotOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "share_id": *createShareSnapshotOptions.ShareID, + } + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createPublicGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateShareSnapshot") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePublicGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createShareSnapshotOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -23190,20 +24177,11 @@ func (vpc *VpcV1) CreatePublicGatewayWithContext(ctx context.Context, createPubl builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createPublicGatewayOptions.VPC != nil { - body["vpc"] = createPublicGatewayOptions.VPC - } - if createPublicGatewayOptions.Zone != nil { - body["zone"] = createPublicGatewayOptions.Zone - } - if createPublicGatewayOptions.FloatingIP != nil { - body["floating_ip"] = createPublicGatewayOptions.FloatingIP - } - if createPublicGatewayOptions.Name != nil { - body["name"] = createPublicGatewayOptions.Name + if createShareSnapshotOptions.Name != nil { + body["name"] = createShareSnapshotOptions.Name } - if createPublicGatewayOptions.ResourceGroup != nil { - body["resource_group"] = createPublicGatewayOptions.ResourceGroup + if createShareSnapshotOptions.UserTags != nil { + body["user_tags"] = createShareSnapshotOptions.UserTags } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -23220,12 +24198,12 @@ func (vpc *VpcV1) CreatePublicGatewayWithContext(ctx context.Context, createPubl var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_public_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_share_snapshot", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshot) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23236,50 +24214,61 @@ func (vpc *VpcV1) CreatePublicGatewayWithContext(ctx context.Context, createPubl return } -// DeletePublicGateway : Delete a public gateway -// This request deletes a public gateway. This operation cannot be reversed. For this request to succeed, the public -// gateway must not be attached to any subnets. The public gateway's floating IP will be automatically unbound. If the -// floating IP was created when the public gateway was created, it will be deleted. -func (vpc *VpcV1) DeletePublicGateway(deletePublicGatewayOptions *DeletePublicGatewayOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeletePublicGatewayWithContext(context.Background(), deletePublicGatewayOptions) +// DeleteShareSnapshot : Delete a share snapshot +// This request deletes a share snapshot. This operation cannot be reversed. For this request to succeed, the share must +// have a `replication_role` of `source` or `none`. +// +// If the request is accepted, the share snapshot `lifecycle_state` will be set to +// `deleting`. Once deletion processing completes, the share snapshot will no longer be retrievable. +// +// Deleting a share snapshot will not affect any previously-accepted requests to create a share from it. +// +// If the share has a `replication_role` of `source`, the corresponding snapshot on the replica share will be +// subsequently moved to a `lifecycle_state` of `deleting`. If the data for the corresponding snapshot has already been +// synchronized via the replication schedule determined by `replication_cron_spec`, the snapshot will remain available +// in the replica share's `.snapshot` directory until the next replication sync. +func (vpc *VpcV1) DeleteShareSnapshot(deleteShareSnapshotOptions *DeleteShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteShareSnapshotWithContext(context.Background(), deleteShareSnapshotOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeletePublicGatewayWithContext is an alternate form of the DeletePublicGateway method which supports a Context parameter -func (vpc *VpcV1) DeletePublicGatewayWithContext(ctx context.Context, deletePublicGatewayOptions *DeletePublicGatewayOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deletePublicGatewayOptions, "deletePublicGatewayOptions cannot be nil") +// DeleteShareSnapshotWithContext is an alternate form of the DeleteShareSnapshot method which supports a Context parameter +func (vpc *VpcV1) DeleteShareSnapshotWithContext(ctx context.Context, deleteShareSnapshotOptions *DeleteShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteShareSnapshotOptions, "deleteShareSnapshotOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deletePublicGatewayOptions, "deletePublicGatewayOptions") + err = core.ValidateStruct(deleteShareSnapshotOptions, "deleteShareSnapshotOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deletePublicGatewayOptions.ID, + "share_id": *deleteShareSnapshotOptions.ShareID, + "id": *deleteShareSnapshotOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deletePublicGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShareSnapshot") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePublicGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteShareSnapshotOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -23290,56 +24279,66 @@ func (vpc *VpcV1) DeletePublicGatewayWithContext(ctx context.Context, deletePubl return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_public_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_share_snapshot", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshot) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetPublicGateway : Retrieve a public gateway -// This request retrieves a single public gateway specified by the identifier in the URL. -func (vpc *VpcV1) GetPublicGateway(getPublicGatewayOptions *GetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetPublicGatewayWithContext(context.Background(), getPublicGatewayOptions) +// GetShareSnapshot : Retrieve a share snapshot +// This request retrieves a single share snapshot specified by the identifier in the URL. +func (vpc *VpcV1) GetShareSnapshot(getShareSnapshotOptions *GetShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetShareSnapshotWithContext(context.Background(), getShareSnapshotOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetPublicGatewayWithContext is an alternate form of the GetPublicGateway method which supports a Context parameter -func (vpc *VpcV1) GetPublicGatewayWithContext(ctx context.Context, getPublicGatewayOptions *GetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getPublicGatewayOptions, "getPublicGatewayOptions cannot be nil") +// GetShareSnapshotWithContext is an alternate form of the GetShareSnapshot method which supports a Context parameter +func (vpc *VpcV1) GetShareSnapshotWithContext(ctx context.Context, getShareSnapshotOptions *GetShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getShareSnapshotOptions, "getShareSnapshotOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getPublicGatewayOptions, "getPublicGatewayOptions") + err = core.ValidateStruct(getShareSnapshotOptions, "getShareSnapshotOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getPublicGatewayOptions.ID, + "share_id": *getShareSnapshotOptions.ShareID, + "id": *getShareSnapshotOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getPublicGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareSnapshot") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPublicGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getShareSnapshotOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -23356,12 +24355,12 @@ func (vpc *VpcV1) GetPublicGatewayWithContext(ctx context.Context, getPublicGate var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_public_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_share_snapshot", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshot) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23372,55 +24371,61 @@ func (vpc *VpcV1) GetPublicGatewayWithContext(ctx context.Context, getPublicGate return } -// UpdatePublicGateway : Update a public gateway -// This request updates a public gateway's name. -func (vpc *VpcV1) UpdatePublicGateway(updatePublicGatewayOptions *UpdatePublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdatePublicGatewayWithContext(context.Background(), updatePublicGatewayOptions) +// UpdateShareSnapshot : Update a share snapshot +// This request updates a share snapshot with the information provided in a share snapshot patch object. The share +// snapshot patch object is structured in the same way as a retrieved share snapshot and needs to contain only the +// information to be updated. +func (vpc *VpcV1) UpdateShareSnapshot(updateShareSnapshotOptions *UpdateShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateShareSnapshotWithContext(context.Background(), updateShareSnapshotOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdatePublicGatewayWithContext is an alternate form of the UpdatePublicGateway method which supports a Context parameter -func (vpc *VpcV1) UpdatePublicGatewayWithContext(ctx context.Context, updatePublicGatewayOptions *UpdatePublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updatePublicGatewayOptions, "updatePublicGatewayOptions cannot be nil") +// UpdateShareSnapshotWithContext is an alternate form of the UpdateShareSnapshot method which supports a Context parameter +func (vpc *VpcV1) UpdateShareSnapshotWithContext(ctx context.Context, updateShareSnapshotOptions *UpdateShareSnapshotOptions) (result *ShareSnapshot, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateShareSnapshotOptions, "updateShareSnapshotOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updatePublicGatewayOptions, "updatePublicGatewayOptions") + err = core.ValidateStruct(updateShareSnapshotOptions, "updateShareSnapshotOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updatePublicGatewayOptions.ID, + "share_id": *updateShareSnapshotOptions.ShareID, + "id": *updateShareSnapshotOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/public_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/snapshots/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updatePublicGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateShareSnapshot") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePublicGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateShareSnapshotOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateShareSnapshotOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateShareSnapshotOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updatePublicGatewayOptions.PublicGatewayPatch) + _, err = builder.SetBodyContentJSON(updateShareSnapshotOptions.ShareSnapshotPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -23435,12 +24440,12 @@ func (vpc *VpcV1) UpdatePublicGatewayWithContext(ctx context.Context, updatePubl var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_public_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_share_snapshot", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareSnapshot) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23451,67 +24456,200 @@ func (vpc *VpcV1) UpdatePublicGatewayWithContext(ctx context.Context, updatePubl return } -// ListFloatingIps : List floating IPs -// This request lists floating IPs in the region. Floating IPs allow inbound and outbound traffic from the Internet to -// an instance. -func (vpc *VpcV1) ListFloatingIps(listFloatingIpsOptions *ListFloatingIpsOptions) (result *FloatingIPCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListFloatingIpsWithContext(context.Background(), listFloatingIpsOptions) +// DeleteShareSource : Split the source file share from a replica file share +// This request removes the replication relationship between a source share and the replica share specified by the +// identifier in the URL. The replication relationship cannot be removed if a source share or the replica share has a +// `lifecycle_state` of `updating`, or has a replication operation in progress. +// +// This operation cannot be reversed. +func (vpc *VpcV1) DeleteShareSource(deleteShareSourceOptions *DeleteShareSourceOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteShareSourceWithContext(context.Background(), deleteShareSourceOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListFloatingIpsWithContext is an alternate form of the ListFloatingIps method which supports a Context parameter -func (vpc *VpcV1) ListFloatingIpsWithContext(ctx context.Context, listFloatingIpsOptions *ListFloatingIpsOptions) (result *FloatingIPCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listFloatingIpsOptions, "listFloatingIpsOptions") +// DeleteShareSourceWithContext is an alternate form of the DeleteShareSource method which supports a Context parameter +func (vpc *VpcV1) DeleteShareSourceWithContext(ctx context.Context, deleteShareSourceOptions *DeleteShareSourceOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteShareSourceOptions, "deleteShareSourceOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteShareSourceOptions, "deleteShareSourceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "share_id": *deleteShareSourceOptions.ShareID, + } + + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/source`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listFloatingIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteShareSource") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListFloatingIps") + for headerName, headerValue := range deleteShareSourceOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "delete_share_source", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// GetShareSource : Retrieve the source file share for a replica file share +// This request retrieves the source file share associated with the replica file share specified by the identifier in +// the URL. +func (vpc *VpcV1) GetShareSource(getShareSourceOptions *GetShareSourceOptions) (result *ShareReference, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetShareSourceWithContext(context.Background(), getShareSourceOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetShareSourceWithContext is an alternate form of the GetShareSource method which supports a Context parameter +func (vpc *VpcV1) GetShareSourceWithContext(ctx context.Context, getShareSourceOptions *GetShareSourceOptions) (result *ShareReference, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getShareSourceOptions, "getShareSourceOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getShareSourceOptions, "getShareSourceOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "share_id": *getShareSourceOptions.ShareID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/shares/{share_id}/source`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetShareSource") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range getShareSourceOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listFloatingIpsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listFloatingIpsOptions.Start)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return } - if listFloatingIpsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listFloatingIpsOptions.Limit)) + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "get_share_source", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return } - if listFloatingIpsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listFloatingIpsOptions.ResourceGroupID)) + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalShareReference) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result } - if listFloatingIpsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listFloatingIpsOptions.Sort)) + + return +} + +// ListSnapshotConsistencyGroups : List snapshot consistency groups +// This request lists snapshot consistency groups in the region. A snapshot consistency group is a collection of +// individual snapshots taken at the same time. +func (vpc *VpcV1) ListSnapshotConsistencyGroups(listSnapshotConsistencyGroupsOptions *ListSnapshotConsistencyGroupsOptions) (result *SnapshotConsistencyGroupCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSnapshotConsistencyGroupsWithContext(context.Background(), listSnapshotConsistencyGroupsOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListSnapshotConsistencyGroupsWithContext is an alternate form of the ListSnapshotConsistencyGroups method which supports a Context parameter +func (vpc *VpcV1) ListSnapshotConsistencyGroupsWithContext(ctx context.Context, listSnapshotConsistencyGroupsOptions *ListSnapshotConsistencyGroupsOptions) (result *SnapshotConsistencyGroupCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listSnapshotConsistencyGroupsOptions, "listSnapshotConsistencyGroupsOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return } - if listFloatingIpsOptions.TargetID != nil { - builder.AddQuery("target.id", fmt.Sprint(*listFloatingIpsOptions.TargetID)) + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return } - if listFloatingIpsOptions.TargetCRN != nil { - builder.AddQuery("target.crn", fmt.Sprint(*listFloatingIpsOptions.TargetCRN)) + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSnapshotConsistencyGroups") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) } - if listFloatingIpsOptions.TargetName != nil { - builder.AddQuery("target.name", fmt.Sprint(*listFloatingIpsOptions.TargetName)) + + for headerName, headerValue := range listSnapshotConsistencyGroupsOptions.Headers { + builder.AddHeader(headerName, headerValue) } - if listFloatingIpsOptions.TargetResourceType != nil { - builder.AddQuery("target.resource_type", fmt.Sprint(*listFloatingIpsOptions.TargetResourceType)) + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listSnapshotConsistencyGroupsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.Start)) + } + if listSnapshotConsistencyGroupsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.Limit)) + } + if listSnapshotConsistencyGroupsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.ResourceGroupID)) + } + if listSnapshotConsistencyGroupsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.Name)) + } + if listSnapshotConsistencyGroupsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.Sort)) + } + if listSnapshotConsistencyGroupsOptions.BackupPolicyPlanID != nil { + builder.AddQuery("backup_policy_plan.id", fmt.Sprint(*listSnapshotConsistencyGroupsOptions.BackupPolicyPlanID)) } request, err := builder.Build() @@ -23523,12 +24661,12 @@ func (vpc *VpcV1) ListFloatingIpsWithContext(ctx context.Context, listFloatingIp var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_floating_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_snapshot_consistency_groups", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroupCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23539,22 +24677,24 @@ func (vpc *VpcV1) ListFloatingIpsWithContext(ctx context.Context, listFloatingIp return } -// CreateFloatingIP : Reserve a floating IP -// This request reserves a new floating IP. -func (vpc *VpcV1) CreateFloatingIP(createFloatingIPOptions *CreateFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateFloatingIPWithContext(context.Background(), createFloatingIPOptions) +// CreateSnapshotConsistencyGroup : Create a snapshot consistency group +// This request creates a new snapshot consistency group from a snapshot consistency group object. The prototype object +// is structured in the same way as a retrieved consistency group, and contains the information necessary to provision +// the new snapshot consistency group. +func (vpc *VpcV1) CreateSnapshotConsistencyGroup(createSnapshotConsistencyGroupOptions *CreateSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateSnapshotConsistencyGroupWithContext(context.Background(), createSnapshotConsistencyGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateFloatingIPWithContext is an alternate form of the CreateFloatingIP method which supports a Context parameter -func (vpc *VpcV1) CreateFloatingIPWithContext(ctx context.Context, createFloatingIPOptions *CreateFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createFloatingIPOptions, "createFloatingIPOptions cannot be nil") +// CreateSnapshotConsistencyGroupWithContext is an alternate form of the CreateSnapshotConsistencyGroup method which supports a Context parameter +func (vpc *VpcV1) CreateSnapshotConsistencyGroupWithContext(ctx context.Context, createSnapshotConsistencyGroupOptions *CreateSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createSnapshotConsistencyGroupOptions, "createSnapshotConsistencyGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createFloatingIPOptions, "createFloatingIPOptions") + err = core.ValidateStruct(createSnapshotConsistencyGroupOptions, "createSnapshotConsistencyGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -23563,18 +24703,18 @@ func (vpc *VpcV1) CreateFloatingIPWithContext(ctx context.Context, createFloatin builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSnapshotConsistencyGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createSnapshotConsistencyGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -23583,7 +24723,7 @@ func (vpc *VpcV1) CreateFloatingIPWithContext(ctx context.Context, createFloatin builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createFloatingIPOptions.FloatingIPPrototype) + _, err = builder.SetBodyContentJSON(createSnapshotConsistencyGroupOptions.SnapshotConsistencyGroupPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -23598,12 +24738,12 @@ func (vpc *VpcV1) CreateFloatingIPWithContext(ctx context.Context, createFloatin var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_snapshot_consistency_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23614,49 +24754,50 @@ func (vpc *VpcV1) CreateFloatingIPWithContext(ctx context.Context, createFloatin return } -// DeleteFloatingIP : Delete a floating IP -// This request disassociates (if associated) and releases a floating IP. This operation cannot be reversed. For this -// request to succeed, the floating IP must not be required by another resource, such as a public gateway. -func (vpc *VpcV1) DeleteFloatingIP(deleteFloatingIPOptions *DeleteFloatingIPOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteFloatingIPWithContext(context.Background(), deleteFloatingIPOptions) +// DeleteSnapshotConsistencyGroup : Delete a snapshot consistency group +// This request deletes snapshot consistency group. This operation cannot be reversed. If the +// `delete_snapshots_on_delete` property is `true`, all snapshots in the consistency group will also be deleted. +func (vpc *VpcV1) DeleteSnapshotConsistencyGroup(deleteSnapshotConsistencyGroupOptions *DeleteSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteSnapshotConsistencyGroupWithContext(context.Background(), deleteSnapshotConsistencyGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteFloatingIPWithContext is an alternate form of the DeleteFloatingIP method which supports a Context parameter -func (vpc *VpcV1) DeleteFloatingIPWithContext(ctx context.Context, deleteFloatingIPOptions *DeleteFloatingIPOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteFloatingIPOptions, "deleteFloatingIPOptions cannot be nil") +// DeleteSnapshotConsistencyGroupWithContext is an alternate form of the DeleteSnapshotConsistencyGroup method which supports a Context parameter +func (vpc *VpcV1) DeleteSnapshotConsistencyGroupWithContext(ctx context.Context, deleteSnapshotConsistencyGroupOptions *DeleteSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSnapshotConsistencyGroupOptions, "deleteSnapshotConsistencyGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteFloatingIPOptions, "deleteFloatingIPOptions") + err = core.ValidateStruct(deleteSnapshotConsistencyGroupOptions, "deleteSnapshotConsistencyGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteFloatingIPOptions.ID, + "id": *deleteSnapshotConsistencyGroupOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSnapshotConsistencyGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteSnapshotConsistencyGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -23667,56 +24808,65 @@ func (vpc *VpcV1) DeleteFloatingIPWithContext(ctx context.Context, deleteFloatin return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_snapshot_consistency_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroup) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetFloatingIP : Retrieve a floating IP -// This request retrieves a single floating IP specified by the identifier in the URL. -func (vpc *VpcV1) GetFloatingIP(getFloatingIPOptions *GetFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetFloatingIPWithContext(context.Background(), getFloatingIPOptions) +// GetSnapshotConsistencyGroup : Retrieve a snapshot consistency group +// This request retrieves a single snapshot consistency group specified by the identifier in the URL. +func (vpc *VpcV1) GetSnapshotConsistencyGroup(getSnapshotConsistencyGroupOptions *GetSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSnapshotConsistencyGroupWithContext(context.Background(), getSnapshotConsistencyGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetFloatingIPWithContext is an alternate form of the GetFloatingIP method which supports a Context parameter -func (vpc *VpcV1) GetFloatingIPWithContext(ctx context.Context, getFloatingIPOptions *GetFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getFloatingIPOptions, "getFloatingIPOptions cannot be nil") +// GetSnapshotConsistencyGroupWithContext is an alternate form of the GetSnapshotConsistencyGroup method which supports a Context parameter +func (vpc *VpcV1) GetSnapshotConsistencyGroupWithContext(ctx context.Context, getSnapshotConsistencyGroupOptions *GetSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSnapshotConsistencyGroupOptions, "getSnapshotConsistencyGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getFloatingIPOptions, "getFloatingIPOptions") + err = core.ValidateStruct(getSnapshotConsistencyGroupOptions, "getSnapshotConsistencyGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getFloatingIPOptions.ID, + "id": *getSnapshotConsistencyGroupOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSnapshotConsistencyGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSnapshotConsistencyGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -23733,12 +24883,12 @@ func (vpc *VpcV1) GetFloatingIPWithContext(ctx context.Context, getFloatingIPOpt var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_snapshot_consistency_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23749,55 +24899,60 @@ func (vpc *VpcV1) GetFloatingIPWithContext(ctx context.Context, getFloatingIPOpt return } -// UpdateFloatingIP : Update a floating IP -// This request updates a floating IP's name and/or target. -func (vpc *VpcV1) UpdateFloatingIP(updateFloatingIPOptions *UpdateFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateFloatingIPWithContext(context.Background(), updateFloatingIPOptions) +// UpdateSnapshotConsistencyGroup : Update a snapshot consistency group +// This request updates a snapshot consistency group with the information in a provided snapshot consistency group +// patch. The snapshot consistency group patch object is structured in the same way as a retrieved snapshot consistency +// group and contains only the information to be updated. +func (vpc *VpcV1) UpdateSnapshotConsistencyGroup(updateSnapshotConsistencyGroupOptions *UpdateSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateSnapshotConsistencyGroupWithContext(context.Background(), updateSnapshotConsistencyGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateFloatingIPWithContext is an alternate form of the UpdateFloatingIP method which supports a Context parameter -func (vpc *VpcV1) UpdateFloatingIPWithContext(ctx context.Context, updateFloatingIPOptions *UpdateFloatingIPOptions) (result *FloatingIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateFloatingIPOptions, "updateFloatingIPOptions cannot be nil") +// UpdateSnapshotConsistencyGroupWithContext is an alternate form of the UpdateSnapshotConsistencyGroup method which supports a Context parameter +func (vpc *VpcV1) UpdateSnapshotConsistencyGroupWithContext(ctx context.Context, updateSnapshotConsistencyGroupOptions *UpdateSnapshotConsistencyGroupOptions) (result *SnapshotConsistencyGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateSnapshotConsistencyGroupOptions, "updateSnapshotConsistencyGroupOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateFloatingIPOptions, "updateFloatingIPOptions") + err = core.ValidateStruct(updateSnapshotConsistencyGroupOptions, "updateSnapshotConsistencyGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateFloatingIPOptions.ID, + "id": *updateSnapshotConsistencyGroupOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/floating_ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshot_consistency_groups/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateFloatingIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSnapshotConsistencyGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateFloatingIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateSnapshotConsistencyGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateSnapshotConsistencyGroupOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateSnapshotConsistencyGroupOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateFloatingIPOptions.FloatingIPPatch) + _, err = builder.SetBodyContentJSON(updateSnapshotConsistencyGroupOptions.SnapshotConsistencyGroupPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -23812,12 +24967,12 @@ func (vpc *VpcV1) UpdateFloatingIPWithContext(ctx context.Context, updateFloatin var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_floating_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_snapshot_consistency_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotConsistencyGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23828,54 +24983,168 @@ func (vpc *VpcV1) UpdateFloatingIPWithContext(ctx context.Context, updateFloatin return } -// ListNetworkAcls : List network ACLs -// This request lists network ACLs in the region. A network ACL defines a set of packet filtering rules for traffic in -// and out of the subnets the network ACL is attached to. No traffic is allowed by default. Both allow and deny rules -// can be defined, and rules are stateless so that reverse traffic in response to allowed traffic is not automatically -// allowed. -func (vpc *VpcV1) ListNetworkAcls(listNetworkAclsOptions *ListNetworkAclsOptions) (result *NetworkACLCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListNetworkAclsWithContext(context.Background(), listNetworkAclsOptions) +// DeleteSnapshots : Delete a filtered collection of snapshots +// This request deletes snapshots that match the specified filter. This operation cannot be reversed. +func (vpc *VpcV1) DeleteSnapshots(deleteSnapshotsOptions *DeleteSnapshotsOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteSnapshotsWithContext(context.Background(), deleteSnapshotsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListNetworkAclsWithContext is an alternate form of the ListNetworkAcls method which supports a Context parameter -func (vpc *VpcV1) ListNetworkAclsWithContext(ctx context.Context, listNetworkAclsOptions *ListNetworkAclsOptions) (result *NetworkACLCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listNetworkAclsOptions, "listNetworkAclsOptions") +// DeleteSnapshotsWithContext is an alternate form of the DeleteSnapshots method which supports a Context parameter +func (vpc *VpcV1) DeleteSnapshotsWithContext(ctx context.Context, deleteSnapshotsOptions *DeleteSnapshotsOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSnapshotsOptions, "deleteSnapshotsOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteSnapshotsOptions, "deleteSnapshotsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listNetworkAclsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSnapshots") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListNetworkAcls") + for headerName, headerValue := range deleteSnapshotsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + builder.AddQuery("source_volume.id", fmt.Sprint(*deleteSnapshotsOptions.SourceVolumeID)) + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "delete_snapshots", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// ListSnapshots : List snapshots +// This request lists snapshots in the region. A snapshot preserves the data of a volume at the time the snapshot is +// created. +func (vpc *VpcV1) ListSnapshots(listSnapshotsOptions *ListSnapshotsOptions) (result *SnapshotCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSnapshotsWithContext(context.Background(), listSnapshotsOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListSnapshotsWithContext is an alternate form of the ListSnapshots method which supports a Context parameter +func (vpc *VpcV1) ListSnapshotsWithContext(ctx context.Context, listSnapshotsOptions *ListSnapshotsOptions) (result *SnapshotCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listSnapshotsOptions, "listSnapshotsOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSnapshots") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range listSnapshotsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listNetworkAclsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listNetworkAclsOptions.Start)) + if listSnapshotsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listSnapshotsOptions.Start)) } - if listNetworkAclsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listNetworkAclsOptions.Limit)) + if listSnapshotsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listSnapshotsOptions.Limit)) } - if listNetworkAclsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listNetworkAclsOptions.ResourceGroupID)) + if listSnapshotsOptions.Tag != nil { + builder.AddQuery("tag", fmt.Sprint(*listSnapshotsOptions.Tag)) + } + if listSnapshotsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listSnapshotsOptions.ResourceGroupID)) + } + if listSnapshotsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listSnapshotsOptions.Name)) + } + if listSnapshotsOptions.SourceVolumeID != nil { + builder.AddQuery("source_volume.id", fmt.Sprint(*listSnapshotsOptions.SourceVolumeID)) + } + if listSnapshotsOptions.SourceVolumeCRN != nil { + builder.AddQuery("source_volume.crn", fmt.Sprint(*listSnapshotsOptions.SourceVolumeCRN)) + } + if listSnapshotsOptions.SourceImageID != nil { + builder.AddQuery("source_image.id", fmt.Sprint(*listSnapshotsOptions.SourceImageID)) + } + if listSnapshotsOptions.SourceImageCRN != nil { + builder.AddQuery("source_image.crn", fmt.Sprint(*listSnapshotsOptions.SourceImageCRN)) + } + if listSnapshotsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listSnapshotsOptions.Sort)) + } + if listSnapshotsOptions.BackupPolicyPlanID != nil { + builder.AddQuery("backup_policy_plan.id", fmt.Sprint(*listSnapshotsOptions.BackupPolicyPlanID)) + } + if listSnapshotsOptions.CopiesID != nil { + builder.AddQuery("copies[].id", fmt.Sprint(*listSnapshotsOptions.CopiesID)) + } + if listSnapshotsOptions.CopiesName != nil { + builder.AddQuery("copies[].name", fmt.Sprint(*listSnapshotsOptions.CopiesName)) + } + if listSnapshotsOptions.CopiesCRN != nil { + builder.AddQuery("copies[].crn", fmt.Sprint(*listSnapshotsOptions.CopiesCRN)) + } + if listSnapshotsOptions.CopiesRemoteRegionName != nil { + builder.AddQuery("copies[].remote.region.name", fmt.Sprint(*listSnapshotsOptions.CopiesRemoteRegionName)) + } + if listSnapshotsOptions.SourceSnapshotID != nil { + builder.AddQuery("source_snapshot.id", fmt.Sprint(*listSnapshotsOptions.SourceSnapshotID)) + } + if listSnapshotsOptions.SourceSnapshotRemoteRegionName != nil { + builder.AddQuery("source_snapshot.remote.region.name", fmt.Sprint(*listSnapshotsOptions.SourceSnapshotRemoteRegionName)) + } + if listSnapshotsOptions.SourceVolumeRemoteRegionName != nil { + builder.AddQuery("source_volume.remote.region.name", fmt.Sprint(*listSnapshotsOptions.SourceVolumeRemoteRegionName)) + } + if listSnapshotsOptions.SourceImageRemoteRegionName != nil { + builder.AddQuery("source_image.remote.region.name", fmt.Sprint(*listSnapshotsOptions.SourceImageRemoteRegionName)) + } + if listSnapshotsOptions.ClonesZoneName != nil { + builder.AddQuery("clones[].zone.name", fmt.Sprint(*listSnapshotsOptions.ClonesZoneName)) + } + if listSnapshotsOptions.SnapshotConsistencyGroupID != nil { + builder.AddQuery("snapshot_consistency_group.id", fmt.Sprint(*listSnapshotsOptions.SnapshotConsistencyGroupID)) + } + if listSnapshotsOptions.SnapshotConsistencyGroupCRN != nil { + builder.AddQuery("snapshot_consistency_group.crn", fmt.Sprint(*listSnapshotsOptions.SnapshotConsistencyGroupCRN)) } request, err := builder.Build() @@ -23887,12 +25156,12 @@ func (vpc *VpcV1) ListNetworkAclsWithContext(ctx context.Context, listNetworkAcl var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_network_acls", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_snapshots", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23903,24 +25172,23 @@ func (vpc *VpcV1) ListNetworkAclsWithContext(ctx context.Context, listNetworkAcl return } -// CreateNetworkACL : Create a network ACL -// This request creates a new stateless network ACL from a network ACL prototype object. The prototype object is -// structured in the same way as a retrieved network ACL, and contains the information necessary to create the new -// network ACL. -func (vpc *VpcV1) CreateNetworkACL(createNetworkACLOptions *CreateNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateNetworkACLWithContext(context.Background(), createNetworkACLOptions) +// CreateSnapshot : Create a snapshot +// This request creates a new snapshot from a snapshot prototype object. The prototype object is structured in the same +// way as a retrieved snapshot, and contains the information necessary to provision the new snapshot. +func (vpc *VpcV1) CreateSnapshot(createSnapshotOptions *CreateSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateSnapshotWithContext(context.Background(), createSnapshotOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateNetworkACLWithContext is an alternate form of the CreateNetworkACL method which supports a Context parameter -func (vpc *VpcV1) CreateNetworkACLWithContext(ctx context.Context, createNetworkACLOptions *CreateNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createNetworkACLOptions, "createNetworkACLOptions cannot be nil") +// CreateSnapshotWithContext is an alternate form of the CreateSnapshot method which supports a Context parameter +func (vpc *VpcV1) CreateSnapshotWithContext(ctx context.Context, createSnapshotOptions *CreateSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createSnapshotOptions, "createSnapshotOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createNetworkACLOptions, "createNetworkACLOptions") + err = core.ValidateStruct(createSnapshotOptions, "createSnapshotOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -23929,18 +25197,18 @@ func (vpc *VpcV1) CreateNetworkACLWithContext(ctx context.Context, createNetwork builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createNetworkACLOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSnapshot") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateNetworkACL") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createSnapshotOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -23949,7 +25217,7 @@ func (vpc *VpcV1) CreateNetworkACLWithContext(ctx context.Context, createNetwork builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createNetworkACLOptions.NetworkACLPrototype) + _, err = builder.SetBodyContentJSON(createSnapshotOptions.SnapshotPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -23964,12 +25232,12 @@ func (vpc *VpcV1) CreateNetworkACLWithContext(ctx context.Context, createNetwork var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_network_acl", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_snapshot", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshot) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -23980,49 +25248,51 @@ func (vpc *VpcV1) CreateNetworkACLWithContext(ctx context.Context, createNetwork return } -// DeleteNetworkACL : Delete a network ACL -// This request deletes a network ACL. This operation cannot be reversed. For this request to succeed, the network ACL -// must not be the default network ACL for any VPCs, and the network ACL must not be attached to any subnets. -func (vpc *VpcV1) DeleteNetworkACL(deleteNetworkACLOptions *DeleteNetworkACLOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteNetworkACLWithContext(context.Background(), deleteNetworkACLOptions) +// DeleteSnapshot : Delete a snapshot +// This request deletes a snapshot. This operation cannot be reversed. +func (vpc *VpcV1) DeleteSnapshot(deleteSnapshotOptions *DeleteSnapshotOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteSnapshotWithContext(context.Background(), deleteSnapshotOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteNetworkACLWithContext is an alternate form of the DeleteNetworkACL method which supports a Context parameter -func (vpc *VpcV1) DeleteNetworkACLWithContext(ctx context.Context, deleteNetworkACLOptions *DeleteNetworkACLOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteNetworkACLOptions, "deleteNetworkACLOptions cannot be nil") +// DeleteSnapshotWithContext is an alternate form of the DeleteSnapshot method which supports a Context parameter +func (vpc *VpcV1) DeleteSnapshotWithContext(ctx context.Context, deleteSnapshotOptions *DeleteSnapshotOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSnapshotOptions, "deleteSnapshotOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteNetworkACLOptions, "deleteNetworkACLOptions") + err = core.ValidateStruct(deleteSnapshotOptions, "deleteSnapshotOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteNetworkACLOptions.ID, + "id": *deleteSnapshotOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteNetworkACLOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSnapshot") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteNetworkACL") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteSnapshotOptions.Headers { builder.AddHeader(headerName, headerValue) } + if deleteSnapshotOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteSnapshotOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -24035,7 +25305,7 @@ func (vpc *VpcV1) DeleteNetworkACLWithContext(ctx context.Context, deleteNetwork response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_network_acl", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_snapshot", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -24043,46 +25313,46 @@ func (vpc *VpcV1) DeleteNetworkACLWithContext(ctx context.Context, deleteNetwork return } -// GetNetworkACL : Retrieve a network ACL -// This request retrieves a single network ACL specified by the identifier in the URL. -func (vpc *VpcV1) GetNetworkACL(getNetworkACLOptions *GetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetNetworkACLWithContext(context.Background(), getNetworkACLOptions) +// GetSnapshot : Retrieve a snapshot +// This request retrieves a single snapshot specified by the identifier in the URL. +func (vpc *VpcV1) GetSnapshot(getSnapshotOptions *GetSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSnapshotWithContext(context.Background(), getSnapshotOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetNetworkACLWithContext is an alternate form of the GetNetworkACL method which supports a Context parameter -func (vpc *VpcV1) GetNetworkACLWithContext(ctx context.Context, getNetworkACLOptions *GetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getNetworkACLOptions, "getNetworkACLOptions cannot be nil") +// GetSnapshotWithContext is an alternate form of the GetSnapshot method which supports a Context parameter +func (vpc *VpcV1) GetSnapshotWithContext(ctx context.Context, getSnapshotOptions *GetSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSnapshotOptions, "getSnapshotOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getNetworkACLOptions, "getNetworkACLOptions") + err = core.ValidateStruct(getSnapshotOptions, "getSnapshotOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getNetworkACLOptions.ID, + "id": *getSnapshotOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getNetworkACLOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSnapshot") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetNetworkACL") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSnapshotOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -24099,12 +25369,12 @@ func (vpc *VpcV1) GetNetworkACLWithContext(ctx context.Context, getNetworkACLOpt var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_network_acl", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_snapshot", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshot) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24115,55 +25385,59 @@ func (vpc *VpcV1) GetNetworkACLWithContext(ctx context.Context, getNetworkACLOpt return } -// UpdateNetworkACL : Update a network ACL -// This request updates a network ACL's name. -func (vpc *VpcV1) UpdateNetworkACL(updateNetworkACLOptions *UpdateNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateNetworkACLWithContext(context.Background(), updateNetworkACLOptions) +// UpdateSnapshot : Update a snapshot +// This request updates a snapshot with the information in a provided snapshot patch. The snapshot consistency group +// patch object is structured in the same way as a retrieved snapshot and contains only the information to be updated. +func (vpc *VpcV1) UpdateSnapshot(updateSnapshotOptions *UpdateSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateSnapshotWithContext(context.Background(), updateSnapshotOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateNetworkACLWithContext is an alternate form of the UpdateNetworkACL method which supports a Context parameter -func (vpc *VpcV1) UpdateNetworkACLWithContext(ctx context.Context, updateNetworkACLOptions *UpdateNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateNetworkACLOptions, "updateNetworkACLOptions cannot be nil") +// UpdateSnapshotWithContext is an alternate form of the UpdateSnapshot method which supports a Context parameter +func (vpc *VpcV1) UpdateSnapshotWithContext(ctx context.Context, updateSnapshotOptions *UpdateSnapshotOptions) (result *Snapshot, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateSnapshotOptions, "updateSnapshotOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateNetworkACLOptions, "updateNetworkACLOptions") + err = core.ValidateStruct(updateSnapshotOptions, "updateSnapshotOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateNetworkACLOptions.ID, + "id": *updateSnapshotOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateNetworkACLOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSnapshot") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateNetworkACL") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateSnapshotOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateSnapshotOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateSnapshotOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateNetworkACLOptions.NetworkACLPatch) + _, err = builder.SetBodyContentJSON(updateSnapshotOptions.SnapshotPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -24178,12 +25452,12 @@ func (vpc *VpcV1) UpdateNetworkACLWithContext(ctx context.Context, updateNetwork var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_network_acl", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_snapshot", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshot) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24194,62 +25468,52 @@ func (vpc *VpcV1) UpdateNetworkACLWithContext(ctx context.Context, updateNetwork return } -// ListNetworkACLRules : List rules for a network ACL -// This request lists rules for a network ACL. These rules can allow or deny traffic between a source CIDR block and a -// destination CIDR block over a particular protocol and port range. -func (vpc *VpcV1) ListNetworkACLRules(listNetworkACLRulesOptions *ListNetworkACLRulesOptions) (result *NetworkACLRuleCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListNetworkACLRulesWithContext(context.Background(), listNetworkACLRulesOptions) +// ListSnapshotClones : List clones for a snapshot +// This request lists clones for a snapshot. Use a clone to quickly restore a snapshot within the clone's zone. +func (vpc *VpcV1) ListSnapshotClones(listSnapshotClonesOptions *ListSnapshotClonesOptions) (result *SnapshotCloneCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSnapshotClonesWithContext(context.Background(), listSnapshotClonesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListNetworkACLRulesWithContext is an alternate form of the ListNetworkACLRules method which supports a Context parameter -func (vpc *VpcV1) ListNetworkACLRulesWithContext(ctx context.Context, listNetworkACLRulesOptions *ListNetworkACLRulesOptions) (result *NetworkACLRuleCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listNetworkACLRulesOptions, "listNetworkACLRulesOptions cannot be nil") +// ListSnapshotClonesWithContext is an alternate form of the ListSnapshotClones method which supports a Context parameter +func (vpc *VpcV1) ListSnapshotClonesWithContext(ctx context.Context, listSnapshotClonesOptions *ListSnapshotClonesOptions) (result *SnapshotCloneCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listSnapshotClonesOptions, "listSnapshotClonesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listNetworkACLRulesOptions, "listNetworkACLRulesOptions") + err = core.ValidateStruct(listSnapshotClonesOptions, "listSnapshotClonesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "network_acl_id": *listNetworkACLRulesOptions.NetworkACLID, + "id": *listSnapshotClonesOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/clones`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listNetworkACLRulesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSnapshotClones") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListNetworkACLRules") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listSnapshotClonesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listNetworkACLRulesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listNetworkACLRulesOptions.Start)) - } - if listNetworkACLRulesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listNetworkACLRulesOptions.Limit)) - } - if listNetworkACLRulesOptions.Direction != nil { - builder.AddQuery("direction", fmt.Sprint(*listNetworkACLRulesOptions.Direction)) - } request, err := builder.Build() if err != nil { @@ -24260,12 +25524,12 @@ func (vpc *VpcV1) ListNetworkACLRulesWithContext(ctx context.Context, listNetwor var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_network_acl_rules", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_snapshot_clones", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLRuleCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotCloneCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24276,129 +25540,114 @@ func (vpc *VpcV1) ListNetworkACLRulesWithContext(ctx context.Context, listNetwor return } -// CreateNetworkACLRule : Create a rule for a network ACL -// This request creates a new rule from a network ACL rule prototype object. The prototype object is structured in the -// same way as a retrieved rule, and contains the information necessary to create the new rule. -func (vpc *VpcV1) CreateNetworkACLRule(createNetworkACLRuleOptions *CreateNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateNetworkACLRuleWithContext(context.Background(), createNetworkACLRuleOptions) +// DeleteSnapshotClone : Delete a snapshot clone +// This request deletes a snapshot clone. This operation cannot be reversed, but an equivalent clone may be recreated +// from the snapshot. +func (vpc *VpcV1) DeleteSnapshotClone(deleteSnapshotCloneOptions *DeleteSnapshotCloneOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteSnapshotCloneWithContext(context.Background(), deleteSnapshotCloneOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateNetworkACLRuleWithContext is an alternate form of the CreateNetworkACLRule method which supports a Context parameter -func (vpc *VpcV1) CreateNetworkACLRuleWithContext(ctx context.Context, createNetworkACLRuleOptions *CreateNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createNetworkACLRuleOptions, "createNetworkACLRuleOptions cannot be nil") +// DeleteSnapshotCloneWithContext is an alternate form of the DeleteSnapshotClone method which supports a Context parameter +func (vpc *VpcV1) DeleteSnapshotCloneWithContext(ctx context.Context, deleteSnapshotCloneOptions *DeleteSnapshotCloneOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSnapshotCloneOptions, "deleteSnapshotCloneOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createNetworkACLRuleOptions, "createNetworkACLRuleOptions") + err = core.ValidateStruct(deleteSnapshotCloneOptions, "deleteSnapshotCloneOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "network_acl_id": *createNetworkACLRuleOptions.NetworkACLID, + "id": *deleteSnapshotCloneOptions.ID, + "zone_name": *deleteSnapshotCloneOptions.ZoneName, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/clones/{zone_name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createNetworkACLRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSnapshotClone") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateNetworkACLRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteSnapshotCloneOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createNetworkACLRuleOptions.NetworkACLRulePrototype) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "create_network_acl_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_snapshot_clone", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLRule) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// DeleteNetworkACLRule : Delete a network ACL rule -// This request deletes a rule. This operation cannot be reversed. -func (vpc *VpcV1) DeleteNetworkACLRule(deleteNetworkACLRuleOptions *DeleteNetworkACLRuleOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteNetworkACLRuleWithContext(context.Background(), deleteNetworkACLRuleOptions) +// GetSnapshotClone : Retrieve a snapshot clone +// This request retrieves a single clone specified by the snapshot identifier and zone name in the URL. +func (vpc *VpcV1) GetSnapshotClone(getSnapshotCloneOptions *GetSnapshotCloneOptions) (result *SnapshotClone, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSnapshotCloneWithContext(context.Background(), getSnapshotCloneOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteNetworkACLRuleWithContext is an alternate form of the DeleteNetworkACLRule method which supports a Context parameter -func (vpc *VpcV1) DeleteNetworkACLRuleWithContext(ctx context.Context, deleteNetworkACLRuleOptions *DeleteNetworkACLRuleOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteNetworkACLRuleOptions, "deleteNetworkACLRuleOptions cannot be nil") +// GetSnapshotCloneWithContext is an alternate form of the GetSnapshotClone method which supports a Context parameter +func (vpc *VpcV1) GetSnapshotCloneWithContext(ctx context.Context, getSnapshotCloneOptions *GetSnapshotCloneOptions) (result *SnapshotClone, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSnapshotCloneOptions, "getSnapshotCloneOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteNetworkACLRuleOptions, "deleteNetworkACLRuleOptions") + err = core.ValidateStruct(getSnapshotCloneOptions, "getSnapshotCloneOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "network_acl_id": *deleteNetworkACLRuleOptions.NetworkACLID, - "id": *deleteNetworkACLRuleOptions.ID, + "id": *getSnapshotCloneOptions.ID, + "zone_name": *getSnapshotCloneOptions.ZoneName, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/clones/{zone_name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteNetworkACLRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSnapshotClone") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteNetworkACLRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSnapshotCloneOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -24409,57 +25658,67 @@ func (vpc *VpcV1) DeleteNetworkACLRuleWithContext(ctx context.Context, deleteNet return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_network_acl_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_snapshot_clone", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotClone) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetNetworkACLRule : Retrieve a network ACL rule -// This request retrieves a single rule specified by the identifier in the URL. -func (vpc *VpcV1) GetNetworkACLRule(getNetworkACLRuleOptions *GetNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetNetworkACLRuleWithContext(context.Background(), getNetworkACLRuleOptions) +// CreateSnapshotClone : Create a clone for a snapshot +// This request creates a new clone for a snapshot in the specified zone. A request body is not required, and if +// provided, is ignored. If the snapshot already has a clone in the zone, it is returned. +func (vpc *VpcV1) CreateSnapshotClone(createSnapshotCloneOptions *CreateSnapshotCloneOptions) (result *SnapshotClone, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateSnapshotCloneWithContext(context.Background(), createSnapshotCloneOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetNetworkACLRuleWithContext is an alternate form of the GetNetworkACLRule method which supports a Context parameter -func (vpc *VpcV1) GetNetworkACLRuleWithContext(ctx context.Context, getNetworkACLRuleOptions *GetNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getNetworkACLRuleOptions, "getNetworkACLRuleOptions cannot be nil") +// CreateSnapshotCloneWithContext is an alternate form of the CreateSnapshotClone method which supports a Context parameter +func (vpc *VpcV1) CreateSnapshotCloneWithContext(ctx context.Context, createSnapshotCloneOptions *CreateSnapshotCloneOptions) (result *SnapshotClone, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createSnapshotCloneOptions, "createSnapshotCloneOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getNetworkACLRuleOptions, "getNetworkACLRuleOptions") + err = core.ValidateStruct(createSnapshotCloneOptions, "createSnapshotCloneOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "network_acl_id": *getNetworkACLRuleOptions.NetworkACLID, - "id": *getNetworkACLRuleOptions.ID, + "id": *createSnapshotCloneOptions.ID, + "zone_name": *createSnapshotCloneOptions.ZoneName, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/clones/{zone_name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getNetworkACLRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSnapshotClone") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetNetworkACLRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createSnapshotCloneOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -24476,12 +25735,12 @@ func (vpc *VpcV1) GetNetworkACLRuleWithContext(ctx context.Context, getNetworkAC var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_network_acl_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_snapshot_clone", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLRule) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotClone) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24492,61 +25751,60 @@ func (vpc *VpcV1) GetNetworkACLRuleWithContext(ctx context.Context, getNetworkAC return } -// UpdateNetworkACLRule : Update a network ACL rule -// This request updates a rule with the information in a provided rule patch. The rule patch object contains only the -// information to be updated. The request will fail if the provided patch includes properties that are not used by the -// rule's protocol. -func (vpc *VpcV1) UpdateNetworkACLRule(updateNetworkACLRuleOptions *UpdateNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateNetworkACLRuleWithContext(context.Background(), updateNetworkACLRuleOptions) +// ListSnapshotInstanceProfiles : List instance profiles compatible with a snapshot +// This request lists instance profiles compatible with a snapshot's +// `allowed_use.instance`, `operating_system.architecture` and +// `operating_system.user_data_format` properties, sorted by ascending `name` property values. The specified snapshot +// must be bootable. +func (vpc *VpcV1) ListSnapshotInstanceProfiles(listSnapshotInstanceProfilesOptions *ListSnapshotInstanceProfilesOptions) (result *SnapshotInstanceProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSnapshotInstanceProfilesWithContext(context.Background(), listSnapshotInstanceProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateNetworkACLRuleWithContext is an alternate form of the UpdateNetworkACLRule method which supports a Context parameter -func (vpc *VpcV1) UpdateNetworkACLRuleWithContext(ctx context.Context, updateNetworkACLRuleOptions *UpdateNetworkACLRuleOptions) (result NetworkACLRuleIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateNetworkACLRuleOptions, "updateNetworkACLRuleOptions cannot be nil") +// ListSnapshotInstanceProfilesWithContext is an alternate form of the ListSnapshotInstanceProfiles method which supports a Context parameter +func (vpc *VpcV1) ListSnapshotInstanceProfilesWithContext(ctx context.Context, listSnapshotInstanceProfilesOptions *ListSnapshotInstanceProfilesOptions) (result *SnapshotInstanceProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listSnapshotInstanceProfilesOptions, "listSnapshotInstanceProfilesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateNetworkACLRuleOptions, "updateNetworkACLRuleOptions") + err = core.ValidateStruct(listSnapshotInstanceProfilesOptions, "listSnapshotInstanceProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "network_acl_id": *updateNetworkACLRuleOptions.NetworkACLID, - "id": *updateNetworkACLRuleOptions.ID, + "id": *listSnapshotInstanceProfilesOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/network_acls/{network_acl_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/snapshots/{id}/instance_profiles`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateNetworkACLRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSnapshotInstanceProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateNetworkACLRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listSnapshotInstanceProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - _, err = builder.SetBodyContentJSON(updateNetworkACLRuleOptions.NetworkACLRulePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listSnapshotInstanceProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listSnapshotInstanceProfilesOptions.Start)) + } + if listSnapshotInstanceProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listSnapshotInstanceProfilesOptions.Limit)) } request, err := builder.Build() @@ -24558,12 +25816,12 @@ func (vpc *VpcV1) UpdateNetworkACLRuleWithContext(ctx context.Context, updateNet var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_network_acl_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_snapshot_instance_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACLRule) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSnapshotInstanceProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24574,19 +25832,18 @@ func (vpc *VpcV1) UpdateNetworkACLRuleWithContext(ctx context.Context, updateNet return } -// ListSecurityGroups : List security groups -// This request lists security groups in the region. A security group defines a set of packet filtering rules to allow -// traffic in and out of the resources targeted by the security group. No traffic is allowed by default. Security group -// rules are stateful so that reverse traffic in response to allowed traffic is automatically allowed. -func (vpc *VpcV1) ListSecurityGroups(listSecurityGroupsOptions *ListSecurityGroupsOptions) (result *SecurityGroupCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSecurityGroupsWithContext(context.Background(), listSecurityGroupsOptions) +// ListSubnets : List subnets +// This request lists subnets in the region. Subnets are contiguous ranges of IP addresses specified in CIDR block +// notation. Each subnet is within a particular zone and cannot span multiple zones or regions. +func (vpc *VpcV1) ListSubnets(listSubnetsOptions *ListSubnetsOptions) (result *SubnetCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSubnetsWithContext(context.Background(), listSubnetsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSecurityGroupsWithContext is an alternate form of the ListSecurityGroups method which supports a Context parameter -func (vpc *VpcV1) ListSecurityGroupsWithContext(ctx context.Context, listSecurityGroupsOptions *ListSecurityGroupsOptions) (result *SecurityGroupCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listSecurityGroupsOptions, "listSecurityGroupsOptions") +// ListSubnetsWithContext is an alternate form of the ListSubnets method which supports a Context parameter +func (vpc *VpcV1) ListSubnetsWithContext(ctx context.Context, listSubnetsOptions *ListSubnetsOptions) (result *SubnetCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listSubnetsOptions, "listSubnetsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -24595,41 +25852,50 @@ func (vpc *VpcV1) ListSecurityGroupsWithContext(ctx context.Context, listSecurit builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSecurityGroupsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSubnets") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSecurityGroups") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listSubnetsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listSecurityGroupsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listSecurityGroupsOptions.Start)) + if listSubnetsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listSubnetsOptions.Start)) } - if listSecurityGroupsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listSecurityGroupsOptions.Limit)) + if listSubnetsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listSubnetsOptions.Limit)) } - if listSecurityGroupsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listSecurityGroupsOptions.ResourceGroupID)) + if listSubnetsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listSubnetsOptions.ResourceGroupID)) } - if listSecurityGroupsOptions.VPCID != nil { - builder.AddQuery("vpc.id", fmt.Sprint(*listSecurityGroupsOptions.VPCID)) + if listSubnetsOptions.ZoneName != nil { + builder.AddQuery("zone.name", fmt.Sprint(*listSubnetsOptions.ZoneName)) } - if listSecurityGroupsOptions.VPCCRN != nil { - builder.AddQuery("vpc.crn", fmt.Sprint(*listSecurityGroupsOptions.VPCCRN)) + if listSubnetsOptions.VPCID != nil { + builder.AddQuery("vpc.id", fmt.Sprint(*listSubnetsOptions.VPCID)) } - if listSecurityGroupsOptions.VPCName != nil { - builder.AddQuery("vpc.name", fmt.Sprint(*listSecurityGroupsOptions.VPCName)) + if listSubnetsOptions.VPCCRN != nil { + builder.AddQuery("vpc.crn", fmt.Sprint(*listSubnetsOptions.VPCCRN)) + } + if listSubnetsOptions.VPCName != nil { + builder.AddQuery("vpc.name", fmt.Sprint(*listSubnetsOptions.VPCName)) + } + if listSubnetsOptions.RoutingTableID != nil { + builder.AddQuery("routing_table.id", fmt.Sprint(*listSubnetsOptions.RoutingTableID)) + } + if listSubnetsOptions.RoutingTableName != nil { + builder.AddQuery("routing_table.name", fmt.Sprint(*listSubnetsOptions.RoutingTableName)) } request, err := builder.Build() @@ -24641,12 +25907,12 @@ func (vpc *VpcV1) ListSecurityGroupsWithContext(ctx context.Context, listSecurit var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_security_groups", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_subnets", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSubnetCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24657,25 +25923,24 @@ func (vpc *VpcV1) ListSecurityGroupsWithContext(ctx context.Context, listSecurit return } -// CreateSecurityGroup : Create a security group -// This request creates a new security group from a security group prototype object. The prototype object is structured -// in the same way as a retrieved security group, and contains the information necessary to create the new security -// group. If security group rules are included in the prototype object, those rules will be added to the security group. -// Each security group is scoped to one VPC. Only resources in that VPC can be added to the security group. -func (vpc *VpcV1) CreateSecurityGroup(createSecurityGroupOptions *CreateSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateSecurityGroupWithContext(context.Background(), createSecurityGroupOptions) +// CreateSubnet : Create a subnet +// This request creates a new subnet from a subnet prototype object. The prototype object is structured in the same way +// as a retrieved subnet, and contains the information necessary to create the new subnet. For this request to succeed, +// the prototype's CIDR block must not overlap with an existing subnet in the VPC. +func (vpc *VpcV1) CreateSubnet(createSubnetOptions *CreateSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateSubnetWithContext(context.Background(), createSubnetOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateSecurityGroupWithContext is an alternate form of the CreateSecurityGroup method which supports a Context parameter -func (vpc *VpcV1) CreateSecurityGroupWithContext(ctx context.Context, createSecurityGroupOptions *CreateSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createSecurityGroupOptions, "createSecurityGroupOptions cannot be nil") +// CreateSubnetWithContext is an alternate form of the CreateSubnet method which supports a Context parameter +func (vpc *VpcV1) CreateSubnetWithContext(ctx context.Context, createSubnetOptions *CreateSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createSubnetOptions, "createSubnetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createSecurityGroupOptions, "createSecurityGroupOptions") + err = core.ValidateStruct(createSubnetOptions, "createSubnetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -24684,18 +25949,18 @@ func (vpc *VpcV1) CreateSecurityGroupWithContext(ctx context.Context, createSecu builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createSecurityGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSubnet") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSecurityGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createSubnetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -24704,20 +25969,7 @@ func (vpc *VpcV1) CreateSecurityGroupWithContext(ctx context.Context, createSecu builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createSecurityGroupOptions.VPC != nil { - body["vpc"] = createSecurityGroupOptions.VPC - } - if createSecurityGroupOptions.Name != nil { - body["name"] = createSecurityGroupOptions.Name - } - if createSecurityGroupOptions.ResourceGroup != nil { - body["resource_group"] = createSecurityGroupOptions.ResourceGroup - } - if createSecurityGroupOptions.Rules != nil { - body["rules"] = createSecurityGroupOptions.Rules - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(createSubnetOptions.SubnetPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -24732,12 +25984,12 @@ func (vpc *VpcV1) CreateSecurityGroupWithContext(ctx context.Context, createSecu var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_security_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_subnet", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSubnet) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24748,47 +26000,50 @@ func (vpc *VpcV1) CreateSecurityGroupWithContext(ctx context.Context, createSecu return } -// DeleteSecurityGroup : Delete a security group -// This request deletes a security group. A security group cannot be deleted if it is referenced by any security group -// targets or rules. Additionally, a VPC's default security group cannot be deleted. This operation cannot be reversed. -func (vpc *VpcV1) DeleteSecurityGroup(deleteSecurityGroupOptions *DeleteSecurityGroupOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteSecurityGroupWithContext(context.Background(), deleteSecurityGroupOptions) +// DeleteSubnet : Delete a subnet +// This request deletes a subnet. This operation cannot be reversed. For this request to succeed, the subnet must not be +// referenced by any bare metal server network interfaces, instance network interfaces, virtual network interfaces, VPN +// gateways, or load balancers. A delete operation automatically detaches the subnet from any network ACLs, public +// gateways, or endpoint gateways. All flow log collectors with `auto_delete` set to `true` targeting the subnet or any +// resource in the subnet are automatically deleted. +func (vpc *VpcV1) DeleteSubnet(deleteSubnetOptions *DeleteSubnetOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteSubnetWithContext(context.Background(), deleteSubnetOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSecurityGroupWithContext is an alternate form of the DeleteSecurityGroup method which supports a Context parameter -func (vpc *VpcV1) DeleteSecurityGroupWithContext(ctx context.Context, deleteSecurityGroupOptions *DeleteSecurityGroupOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSecurityGroupOptions, "deleteSecurityGroupOptions cannot be nil") +// DeleteSubnetWithContext is an alternate form of the DeleteSubnet method which supports a Context parameter +func (vpc *VpcV1) DeleteSubnetWithContext(ctx context.Context, deleteSubnetOptions *DeleteSubnetOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSubnetOptions, "deleteSubnetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSecurityGroupOptions, "deleteSecurityGroupOptions") + err = core.ValidateStruct(deleteSubnetOptions, "deleteSubnetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteSecurityGroupOptions.ID, + "id": *deleteSubnetOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSecurityGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSubnet") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSecurityGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteSubnetOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -24803,7 +26058,7 @@ func (vpc *VpcV1) DeleteSecurityGroupWithContext(ctx context.Context, deleteSecu response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_security_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_subnet", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -24811,46 +26066,46 @@ func (vpc *VpcV1) DeleteSecurityGroupWithContext(ctx context.Context, deleteSecu return } -// GetSecurityGroup : Retrieve a security group -// This request retrieves a single security group specified by the identifier in the URL path. -func (vpc *VpcV1) GetSecurityGroup(getSecurityGroupOptions *GetSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSecurityGroupWithContext(context.Background(), getSecurityGroupOptions) +// GetSubnet : Retrieve a subnet +// This request retrieves a single subnet specified by the identifier in the URL. +func (vpc *VpcV1) GetSubnet(getSubnetOptions *GetSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSubnetWithContext(context.Background(), getSubnetOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSecurityGroupWithContext is an alternate form of the GetSecurityGroup method which supports a Context parameter -func (vpc *VpcV1) GetSecurityGroupWithContext(ctx context.Context, getSecurityGroupOptions *GetSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSecurityGroupOptions, "getSecurityGroupOptions cannot be nil") +// GetSubnetWithContext is an alternate form of the GetSubnet method which supports a Context parameter +func (vpc *VpcV1) GetSubnetWithContext(ctx context.Context, getSubnetOptions *GetSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSubnetOptions, "getSubnetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSecurityGroupOptions, "getSecurityGroupOptions") + err = core.ValidateStruct(getSubnetOptions, "getSubnetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getSecurityGroupOptions.ID, + "id": *getSubnetOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSecurityGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnet") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSecurityGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSubnetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -24867,12 +26122,12 @@ func (vpc *VpcV1) GetSecurityGroupWithContext(ctx context.Context, getSecurityGr var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_security_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_subnet", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSubnet) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24883,48 +26138,47 @@ func (vpc *VpcV1) GetSecurityGroupWithContext(ctx context.Context, getSecurityGr return } -// UpdateSecurityGroup : Update a security group -// This request updates a security group with the information provided in a security group patch object. The security -// group patch object is structured in the same way as a retrieved security group and contains only the information to -// be updated. -func (vpc *VpcV1) UpdateSecurityGroup(updateSecurityGroupOptions *UpdateSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateSecurityGroupWithContext(context.Background(), updateSecurityGroupOptions) +// UpdateSubnet : Update a subnet +// This request updates a subnet with the information in a provided subnet patch. The subnet patch object is structured +// in the same way as a retrieved subnet and contains only the information to be updated. +func (vpc *VpcV1) UpdateSubnet(updateSubnetOptions *UpdateSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateSubnetWithContext(context.Background(), updateSubnetOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateSecurityGroupWithContext is an alternate form of the UpdateSecurityGroup method which supports a Context parameter -func (vpc *VpcV1) UpdateSecurityGroupWithContext(ctx context.Context, updateSecurityGroupOptions *UpdateSecurityGroupOptions) (result *SecurityGroup, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateSecurityGroupOptions, "updateSecurityGroupOptions cannot be nil") +// UpdateSubnetWithContext is an alternate form of the UpdateSubnet method which supports a Context parameter +func (vpc *VpcV1) UpdateSubnetWithContext(ctx context.Context, updateSubnetOptions *UpdateSubnetOptions) (result *Subnet, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateSubnetOptions, "updateSubnetOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateSecurityGroupOptions, "updateSecurityGroupOptions") + err = core.ValidateStruct(updateSubnetOptions, "updateSubnetOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateSecurityGroupOptions.ID, + "id": *updateSubnetOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateSecurityGroupOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSubnet") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSecurityGroup") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateSubnetOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -24933,7 +26187,7 @@ func (vpc *VpcV1) UpdateSecurityGroupWithContext(ctx context.Context, updateSecu builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateSecurityGroupOptions.SecurityGroupPatch) + _, err = builder.SetBodyContentJSON(updateSubnetOptions.SubnetPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -24948,12 +26202,12 @@ func (vpc *VpcV1) UpdateSecurityGroupWithContext(ctx context.Context, updateSecu var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_security_group", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_subnet", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroup) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSubnet) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -24964,47 +26218,46 @@ func (vpc *VpcV1) UpdateSecurityGroupWithContext(ctx context.Context, updateSecu return } -// ListSecurityGroupRules : List rules in a security group -// This request lists rules in a security group. These rules define what traffic the security group permits. Security -// group rules are stateful, such that reverse traffic in response to allowed traffic is automatically permitted. -func (vpc *VpcV1) ListSecurityGroupRules(listSecurityGroupRulesOptions *ListSecurityGroupRulesOptions) (result *SecurityGroupRuleCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSecurityGroupRulesWithContext(context.Background(), listSecurityGroupRulesOptions) +// GetSubnetNetworkACL : Retrieve a subnet's attached network ACL +// This request retrieves the network ACL attached to the subnet specified by the identifier in the URL. +func (vpc *VpcV1) GetSubnetNetworkACL(getSubnetNetworkACLOptions *GetSubnetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSubnetNetworkACLWithContext(context.Background(), getSubnetNetworkACLOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSecurityGroupRulesWithContext is an alternate form of the ListSecurityGroupRules method which supports a Context parameter -func (vpc *VpcV1) ListSecurityGroupRulesWithContext(ctx context.Context, listSecurityGroupRulesOptions *ListSecurityGroupRulesOptions) (result *SecurityGroupRuleCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listSecurityGroupRulesOptions, "listSecurityGroupRulesOptions cannot be nil") +// GetSubnetNetworkACLWithContext is an alternate form of the GetSubnetNetworkACL method which supports a Context parameter +func (vpc *VpcV1) GetSubnetNetworkACLWithContext(ctx context.Context, getSubnetNetworkACLOptions *GetSubnetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSubnetNetworkACLOptions, "getSubnetNetworkACLOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listSecurityGroupRulesOptions, "listSecurityGroupRulesOptions") + err = core.ValidateStruct(getSubnetNetworkACLOptions, "getSubnetNetworkACLOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *listSecurityGroupRulesOptions.SecurityGroupID, + "id": *getSubnetNetworkACLOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/network_acl`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSecurityGroupRulesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnetNetworkACL") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSecurityGroupRules") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSubnetNetworkACLOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -25021,12 +26274,12 @@ func (vpc *VpcV1) ListSecurityGroupRulesWithContext(ctx context.Context, listSec var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_security_group_rules", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_subnet_network_acl", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupRuleCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25037,51 +26290,46 @@ func (vpc *VpcV1) ListSecurityGroupRulesWithContext(ctx context.Context, listSec return } -// CreateSecurityGroupRule : Create a rule for a security group -// This request creates a new security group rule from a security group rule prototype object. The prototype object is -// structured in the same way as a retrieved security group rule and contains the information necessary to create the -// rule. As part of creating a new rule in a security group, the rule is applied to all the networking interfaces in the -// security group. Rules specify which IP traffic a security group will allow. Security group rules are stateful, such -// that reverse traffic in response to allowed traffic is automatically permitted. A rule allowing inbound TCP traffic -// on port 80 also allows outbound TCP traffic on port 80 without the need for an additional rule. -func (vpc *VpcV1) CreateSecurityGroupRule(createSecurityGroupRuleOptions *CreateSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateSecurityGroupRuleWithContext(context.Background(), createSecurityGroupRuleOptions) +// ReplaceSubnetNetworkACL : Replace the network ACL for a subnet +// This request replaces the existing network ACL for a subnet with the network ACL specified in the request body. +func (vpc *VpcV1) ReplaceSubnetNetworkACL(replaceSubnetNetworkACLOptions *ReplaceSubnetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + result, response, err = vpc.ReplaceSubnetNetworkACLWithContext(context.Background(), replaceSubnetNetworkACLOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateSecurityGroupRuleWithContext is an alternate form of the CreateSecurityGroupRule method which supports a Context parameter -func (vpc *VpcV1) CreateSecurityGroupRuleWithContext(ctx context.Context, createSecurityGroupRuleOptions *CreateSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createSecurityGroupRuleOptions, "createSecurityGroupRuleOptions cannot be nil") +// ReplaceSubnetNetworkACLWithContext is an alternate form of the ReplaceSubnetNetworkACL method which supports a Context parameter +func (vpc *VpcV1) ReplaceSubnetNetworkACLWithContext(ctx context.Context, replaceSubnetNetworkACLOptions *ReplaceSubnetNetworkACLOptions) (result *NetworkACL, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(replaceSubnetNetworkACLOptions, "replaceSubnetNetworkACLOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createSecurityGroupRuleOptions, "createSecurityGroupRuleOptions") + err = core.ValidateStruct(replaceSubnetNetworkACLOptions, "replaceSubnetNetworkACLOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *createSecurityGroupRuleOptions.SecurityGroupID, + "id": *replaceSubnetNetworkACLOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/network_acl`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createSecurityGroupRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ReplaceSubnetNetworkACL") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSecurityGroupRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range replaceSubnetNetworkACLOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -25090,7 +26338,7 @@ func (vpc *VpcV1) CreateSecurityGroupRuleWithContext(ctx context.Context, create builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createSecurityGroupRuleOptions.SecurityGroupRulePrototype) + _, err = builder.SetBodyContentJSON(replaceSubnetNetworkACLOptions.NetworkACLIdentity) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -25105,12 +26353,12 @@ func (vpc *VpcV1) CreateSecurityGroupRuleWithContext(ctx context.Context, create var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_security_group_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "replace_subnet_network_acl", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupRule) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalNetworkACL) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25121,48 +26369,46 @@ func (vpc *VpcV1) CreateSecurityGroupRuleWithContext(ctx context.Context, create return } -// DeleteSecurityGroupRule : Delete a security group rule -// This request deletes a security group rule. This operation cannot be reversed. Removing a security group rule will -// not end existing connections allowed by that rule. -func (vpc *VpcV1) DeleteSecurityGroupRule(deleteSecurityGroupRuleOptions *DeleteSecurityGroupRuleOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteSecurityGroupRuleWithContext(context.Background(), deleteSecurityGroupRuleOptions) +// UnsetSubnetPublicGateway : Detach a public gateway from a subnet +// This request detaches the public gateway from the subnet specified by the subnet identifier in the URL. +func (vpc *VpcV1) UnsetSubnetPublicGateway(unsetSubnetPublicGatewayOptions *UnsetSubnetPublicGatewayOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.UnsetSubnetPublicGatewayWithContext(context.Background(), unsetSubnetPublicGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSecurityGroupRuleWithContext is an alternate form of the DeleteSecurityGroupRule method which supports a Context parameter -func (vpc *VpcV1) DeleteSecurityGroupRuleWithContext(ctx context.Context, deleteSecurityGroupRuleOptions *DeleteSecurityGroupRuleOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSecurityGroupRuleOptions, "deleteSecurityGroupRuleOptions cannot be nil") +// UnsetSubnetPublicGatewayWithContext is an alternate form of the UnsetSubnetPublicGateway method which supports a Context parameter +func (vpc *VpcV1) UnsetSubnetPublicGatewayWithContext(ctx context.Context, unsetSubnetPublicGatewayOptions *UnsetSubnetPublicGatewayOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(unsetSubnetPublicGatewayOptions, "unsetSubnetPublicGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSecurityGroupRuleOptions, "deleteSecurityGroupRuleOptions") + err = core.ValidateStruct(unsetSubnetPublicGatewayOptions, "unsetSubnetPublicGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *deleteSecurityGroupRuleOptions.SecurityGroupID, - "id": *deleteSecurityGroupRuleOptions.ID, + "id": *unsetSubnetPublicGatewayOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/public_gateway`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSecurityGroupRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UnsetSubnetPublicGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSecurityGroupRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range unsetSubnetPublicGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -25177,7 +26423,7 @@ func (vpc *VpcV1) DeleteSecurityGroupRuleWithContext(ctx context.Context, delete response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_security_group_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "unset_subnet_public_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -25185,47 +26431,46 @@ func (vpc *VpcV1) DeleteSecurityGroupRuleWithContext(ctx context.Context, delete return } -// GetSecurityGroupRule : Retrieve a security group rule -// This request retrieves a single security group rule specified by the identifier in the URL path. -func (vpc *VpcV1) GetSecurityGroupRule(getSecurityGroupRuleOptions *GetSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSecurityGroupRuleWithContext(context.Background(), getSecurityGroupRuleOptions) +// GetSubnetPublicGateway : Retrieve a subnet's attached public gateway +// This request retrieves the public gateway attached to the subnet specified by the identifier in the URL. +func (vpc *VpcV1) GetSubnetPublicGateway(getSubnetPublicGatewayOptions *GetSubnetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSubnetPublicGatewayWithContext(context.Background(), getSubnetPublicGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSecurityGroupRuleWithContext is an alternate form of the GetSecurityGroupRule method which supports a Context parameter -func (vpc *VpcV1) GetSecurityGroupRuleWithContext(ctx context.Context, getSecurityGroupRuleOptions *GetSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSecurityGroupRuleOptions, "getSecurityGroupRuleOptions cannot be nil") +// GetSubnetPublicGatewayWithContext is an alternate form of the GetSubnetPublicGateway method which supports a Context parameter +func (vpc *VpcV1) GetSubnetPublicGatewayWithContext(ctx context.Context, getSubnetPublicGatewayOptions *GetSubnetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSubnetPublicGatewayOptions, "getSubnetPublicGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSecurityGroupRuleOptions, "getSecurityGroupRuleOptions") + err = core.ValidateStruct(getSubnetPublicGatewayOptions, "getSubnetPublicGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *getSecurityGroupRuleOptions.SecurityGroupID, - "id": *getSecurityGroupRuleOptions.ID, + "id": *getSubnetPublicGatewayOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/public_gateway`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSecurityGroupRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnetPublicGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSecurityGroupRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSubnetPublicGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -25242,12 +26487,12 @@ func (vpc *VpcV1) GetSecurityGroupRuleWithContext(ctx context.Context, getSecuri var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_security_group_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_subnet_public_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupRule) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25258,58 +26503,56 @@ func (vpc *VpcV1) GetSecurityGroupRuleWithContext(ctx context.Context, getSecuri return } -// UpdateSecurityGroupRule : Update a security group rule -// This request updates a security group rule with the information in a provided rule patch object. The rule patch -// object contains only the information to be updated. The request will fail if the provided patch includes properties -// that are not used by the rule's protocol. -func (vpc *VpcV1) UpdateSecurityGroupRule(updateSecurityGroupRuleOptions *UpdateSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateSecurityGroupRuleWithContext(context.Background(), updateSecurityGroupRuleOptions) +// SetSubnetPublicGateway : Attach a public gateway to a subnet +// This request attaches the public gateway, specified in the request body, to the subnet specified by the subnet +// identifier in the URL. The public gateway must have the same VPC and zone as the subnet. +func (vpc *VpcV1) SetSubnetPublicGateway(setSubnetPublicGatewayOptions *SetSubnetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + result, response, err = vpc.SetSubnetPublicGatewayWithContext(context.Background(), setSubnetPublicGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateSecurityGroupRuleWithContext is an alternate form of the UpdateSecurityGroupRule method which supports a Context parameter -func (vpc *VpcV1) UpdateSecurityGroupRuleWithContext(ctx context.Context, updateSecurityGroupRuleOptions *UpdateSecurityGroupRuleOptions) (result SecurityGroupRuleIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateSecurityGroupRuleOptions, "updateSecurityGroupRuleOptions cannot be nil") +// SetSubnetPublicGatewayWithContext is an alternate form of the SetSubnetPublicGateway method which supports a Context parameter +func (vpc *VpcV1) SetSubnetPublicGatewayWithContext(ctx context.Context, setSubnetPublicGatewayOptions *SetSubnetPublicGatewayOptions) (result *PublicGateway, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(setSubnetPublicGatewayOptions, "setSubnetPublicGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateSecurityGroupRuleOptions, "updateSecurityGroupRuleOptions") + err = core.ValidateStruct(setSubnetPublicGatewayOptions, "setSubnetPublicGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *updateSecurityGroupRuleOptions.SecurityGroupID, - "id": *updateSecurityGroupRuleOptions.ID, + "id": *setSubnetPublicGatewayOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/public_gateway`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateSecurityGroupRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "SetSubnetPublicGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSecurityGroupRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range setSubnetPublicGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateSecurityGroupRuleOptions.SecurityGroupRulePatch) + _, err = builder.SetBodyContentJSON(setSubnetPublicGatewayOptions.PublicGatewayIdentity) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -25324,12 +26567,12 @@ func (vpc *VpcV1) UpdateSecurityGroupRuleWithContext(ctx context.Context, update var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_security_group_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "set_subnet_public_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupRule) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPublicGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25340,58 +26583,52 @@ func (vpc *VpcV1) UpdateSecurityGroupRuleWithContext(ctx context.Context, update return } -// ListSecurityGroupTargets : List targets associated with a security group -// This request lists targets associated with a security group, to which the rules in the security group are applied. -func (vpc *VpcV1) ListSecurityGroupTargets(listSecurityGroupTargetsOptions *ListSecurityGroupTargetsOptions) (result *SecurityGroupTargetCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListSecurityGroupTargetsWithContext(context.Background(), listSecurityGroupTargetsOptions) +// GetSubnetRoutingTable : Retrieve a subnet's attached routing table +// This request retrieves the routing table attached to the subnet specified by the identifier in the URL. +func (vpc *VpcV1) GetSubnetRoutingTable(getSubnetRoutingTableOptions *GetSubnetRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSubnetRoutingTableWithContext(context.Background(), getSubnetRoutingTableOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListSecurityGroupTargetsWithContext is an alternate form of the ListSecurityGroupTargets method which supports a Context parameter -func (vpc *VpcV1) ListSecurityGroupTargetsWithContext(ctx context.Context, listSecurityGroupTargetsOptions *ListSecurityGroupTargetsOptions) (result *SecurityGroupTargetCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listSecurityGroupTargetsOptions, "listSecurityGroupTargetsOptions cannot be nil") +// GetSubnetRoutingTableWithContext is an alternate form of the GetSubnetRoutingTable method which supports a Context parameter +func (vpc *VpcV1) GetSubnetRoutingTableWithContext(ctx context.Context, getSubnetRoutingTableOptions *GetSubnetRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSubnetRoutingTableOptions, "getSubnetRoutingTableOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listSecurityGroupTargetsOptions, "listSecurityGroupTargetsOptions") + err = core.ValidateStruct(getSubnetRoutingTableOptions, "getSubnetRoutingTableOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *listSecurityGroupTargetsOptions.SecurityGroupID, + "id": *getSubnetRoutingTableOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/targets`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/routing_table`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listSecurityGroupTargetsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnetRoutingTable") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSecurityGroupTargets") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSubnetRoutingTableOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listSecurityGroupTargetsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listSecurityGroupTargetsOptions.Start)) - } - if listSecurityGroupTargetsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listSecurityGroupTargetsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -25402,12 +26639,12 @@ func (vpc *VpcV1) ListSecurityGroupTargetsWithContext(ctx context.Context, listS var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_security_group_targets", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_subnet_routing_table", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupTargetCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25418,128 +26655,156 @@ func (vpc *VpcV1) ListSecurityGroupTargetsWithContext(ctx context.Context, listS return } -// DeleteSecurityGroupTargetBinding : Remove a target from a security group -// This request removes a target from a security group. For this request to succeed, the target must be attached to at -// least one other security group. The specified target identifier can be: -// -// - A bare metal server network interface identifier -// - A virtual network interface identifier -// - A VPN server identifier -// - A load balancer identifier -// - An endpoint gateway identifier -// - An instance network interface identifier +// ReplaceSubnetRoutingTable : Replace the routing table for a subnet +// This request replaces the existing routing table for a subnet with the routing table specified in the request body. // -// Security groups are stateful, so any changes to a target's security groups are applied to new connections. Existing -// connections are not affected. -func (vpc *VpcV1) DeleteSecurityGroupTargetBinding(deleteSecurityGroupTargetBindingOptions *DeleteSecurityGroupTargetBindingOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteSecurityGroupTargetBindingWithContext(context.Background(), deleteSecurityGroupTargetBindingOptions) +// For this request to succeed, the routing table `route_direct_link_ingress`, +// `route_internet_ingress`, `route_transit_gateway_ingress`, and `route_vpc_zone_ingress` properties must be `false`. +func (vpc *VpcV1) ReplaceSubnetRoutingTable(replaceSubnetRoutingTableOptions *ReplaceSubnetRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + result, response, err = vpc.ReplaceSubnetRoutingTableWithContext(context.Background(), replaceSubnetRoutingTableOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteSecurityGroupTargetBindingWithContext is an alternate form of the DeleteSecurityGroupTargetBinding method which supports a Context parameter -func (vpc *VpcV1) DeleteSecurityGroupTargetBindingWithContext(ctx context.Context, deleteSecurityGroupTargetBindingOptions *DeleteSecurityGroupTargetBindingOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteSecurityGroupTargetBindingOptions, "deleteSecurityGroupTargetBindingOptions cannot be nil") +// ReplaceSubnetRoutingTableWithContext is an alternate form of the ReplaceSubnetRoutingTable method which supports a Context parameter +func (vpc *VpcV1) ReplaceSubnetRoutingTableWithContext(ctx context.Context, replaceSubnetRoutingTableOptions *ReplaceSubnetRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(replaceSubnetRoutingTableOptions, "replaceSubnetRoutingTableOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteSecurityGroupTargetBindingOptions, "deleteSecurityGroupTargetBindingOptions") + err = core.ValidateStruct(replaceSubnetRoutingTableOptions, "replaceSubnetRoutingTableOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *deleteSecurityGroupTargetBindingOptions.SecurityGroupID, - "id": *deleteSecurityGroupTargetBindingOptions.ID, + "id": *replaceSubnetRoutingTableOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/targets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{id}/routing_table`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteSecurityGroupTargetBindingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ReplaceSubnetRoutingTable") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSecurityGroupTargetBinding") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range replaceSubnetRoutingTableOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(replaceSubnetRoutingTableOptions.RoutingTableIdentity) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_security_group_target_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "replace_subnet_routing_table", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetSecurityGroupTarget : Retrieve a security group target -// This request retrieves a single target specified by the identifier in the URL path. The target must be an existing -// target of the security group. -func (vpc *VpcV1) GetSecurityGroupTarget(getSecurityGroupTargetOptions *GetSecurityGroupTargetOptions) (result SecurityGroupTargetReferenceIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetSecurityGroupTargetWithContext(context.Background(), getSecurityGroupTargetOptions) +// ListSubnetReservedIps : List reserved IPs in a subnet +// This request lists reserved IPs in a subnet. A reserved IP resource will exist for every address in the subnet which +// is not available for use. +func (vpc *VpcV1) ListSubnetReservedIps(listSubnetReservedIpsOptions *ListSubnetReservedIpsOptions) (result *ReservedIPCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListSubnetReservedIpsWithContext(context.Background(), listSubnetReservedIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetSecurityGroupTargetWithContext is an alternate form of the GetSecurityGroupTarget method which supports a Context parameter -func (vpc *VpcV1) GetSecurityGroupTargetWithContext(ctx context.Context, getSecurityGroupTargetOptions *GetSecurityGroupTargetOptions) (result SecurityGroupTargetReferenceIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getSecurityGroupTargetOptions, "getSecurityGroupTargetOptions cannot be nil") +// ListSubnetReservedIpsWithContext is an alternate form of the ListSubnetReservedIps method which supports a Context parameter +func (vpc *VpcV1) ListSubnetReservedIpsWithContext(ctx context.Context, listSubnetReservedIpsOptions *ListSubnetReservedIpsOptions) (result *ReservedIPCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listSubnetReservedIpsOptions, "listSubnetReservedIpsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getSecurityGroupTargetOptions, "getSecurityGroupTargetOptions") + err = core.ValidateStruct(listSubnetReservedIpsOptions, "listSubnetReservedIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *getSecurityGroupTargetOptions.SecurityGroupID, - "id": *getSecurityGroupTargetOptions.ID, + "subnet_id": *listSubnetReservedIpsOptions.SubnetID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/targets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getSecurityGroupTargetOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListSubnetReservedIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSecurityGroupTarget") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listSubnetReservedIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listSubnetReservedIpsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listSubnetReservedIpsOptions.Start)) + } + if listSubnetReservedIpsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listSubnetReservedIpsOptions.Limit)) + } + if listSubnetReservedIpsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listSubnetReservedIpsOptions.Sort)) + } + if listSubnetReservedIpsOptions.TargetID != nil { + builder.AddQuery("target.id", fmt.Sprint(*listSubnetReservedIpsOptions.TargetID)) + } + if listSubnetReservedIpsOptions.TargetCRN != nil { + builder.AddQuery("target.crn", fmt.Sprint(*listSubnetReservedIpsOptions.TargetCRN)) + } + if listSubnetReservedIpsOptions.TargetName != nil { + builder.AddQuery("target.name", fmt.Sprint(*listSubnetReservedIpsOptions.TargetName)) + } + if listSubnetReservedIpsOptions.TargetResourceType != nil { + builder.AddQuery("target.resource_type", fmt.Sprint(*listSubnetReservedIpsOptions.TargetResourceType)) + } request, err := builder.Build() if err != nil { @@ -25550,12 +26815,12 @@ func (vpc *VpcV1) GetSecurityGroupTargetWithContext(ctx context.Context, getSecu var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_security_group_target", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_subnet_reserved_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupTargetReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25566,64 +26831,74 @@ func (vpc *VpcV1) GetSecurityGroupTargetWithContext(ctx context.Context, getSecu return } -// CreateSecurityGroupTargetBinding : Add a target to a security group -// This request adds a resource to an existing security group. The specified target identifier can be: -// -// - A bare metal server network interface identifier -// - A virtual network interface identifier -// - A VPN server identifier -// - A load balancer identifier -// - An endpoint gateway identifier -// - An instance network interface identifier -// -// When a target is added to a security group, the security group rules are applied to the target. A request body is not -// required, and if provided, is ignored. -func (vpc *VpcV1) CreateSecurityGroupTargetBinding(createSecurityGroupTargetBindingOptions *CreateSecurityGroupTargetBindingOptions) (result SecurityGroupTargetReferenceIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateSecurityGroupTargetBindingWithContext(context.Background(), createSecurityGroupTargetBindingOptions) +// CreateSubnetReservedIP : Reserve an IP in a subnet +// This request reserves an IP address in a subnet. If the provided prototype object includes an `address`, the address +// must not already be reserved. +func (vpc *VpcV1) CreateSubnetReservedIP(createSubnetReservedIPOptions *CreateSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateSubnetReservedIPWithContext(context.Background(), createSubnetReservedIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateSecurityGroupTargetBindingWithContext is an alternate form of the CreateSecurityGroupTargetBinding method which supports a Context parameter -func (vpc *VpcV1) CreateSecurityGroupTargetBindingWithContext(ctx context.Context, createSecurityGroupTargetBindingOptions *CreateSecurityGroupTargetBindingOptions) (result SecurityGroupTargetReferenceIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createSecurityGroupTargetBindingOptions, "createSecurityGroupTargetBindingOptions cannot be nil") +// CreateSubnetReservedIPWithContext is an alternate form of the CreateSubnetReservedIP method which supports a Context parameter +func (vpc *VpcV1) CreateSubnetReservedIPWithContext(ctx context.Context, createSubnetReservedIPOptions *CreateSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createSubnetReservedIPOptions, "createSubnetReservedIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createSecurityGroupTargetBindingOptions, "createSecurityGroupTargetBindingOptions") + err = core.ValidateStruct(createSubnetReservedIPOptions, "createSubnetReservedIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "security_group_id": *createSecurityGroupTargetBindingOptions.SecurityGroupID, - "id": *createSecurityGroupTargetBindingOptions.ID, + "subnet_id": *createSubnetReservedIPOptions.SubnetID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/security_groups/{security_group_id}/targets/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createSecurityGroupTargetBindingOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSubnetReservedIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateSecurityGroupTargetBinding") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createSubnetReservedIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createSubnetReservedIPOptions.Address != nil { + body["address"] = createSubnetReservedIPOptions.Address + } + if createSubnetReservedIPOptions.AutoDelete != nil { + body["auto_delete"] = createSubnetReservedIPOptions.AutoDelete + } + if createSubnetReservedIPOptions.Name != nil { + body["name"] = createSubnetReservedIPOptions.Name + } + if createSubnetReservedIPOptions.Target != nil { + body["target"] = createSubnetReservedIPOptions.Target + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -25633,12 +26908,12 @@ func (vpc *VpcV1) CreateSecurityGroupTargetBindingWithContext(ctx context.Contex var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_security_group_target_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_subnet_reserved_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSecurityGroupTargetReference) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25649,49 +26924,56 @@ func (vpc *VpcV1) CreateSecurityGroupTargetBindingWithContext(ctx context.Contex return } -// ListIkePolicies : List IKE policies -// This request lists IKE policies in the region. -func (vpc *VpcV1) ListIkePolicies(listIkePoliciesOptions *ListIkePoliciesOptions) (result *IkePolicyCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListIkePoliciesWithContext(context.Background(), listIkePoliciesOptions) +// DeleteSubnetReservedIP : Delete a reserved IP +// This request releases a reserved IP. This operation cannot be reversed. +// +// For this request to succeed, the reserved IP must not be required by another resource, such as a bare metal server +// network interface, instance network interface or virtual network interface for which it is the primary IP. A +// provider-owned reserved IP is not allowed to be deleted. +func (vpc *VpcV1) DeleteSubnetReservedIP(deleteSubnetReservedIPOptions *DeleteSubnetReservedIPOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteSubnetReservedIPWithContext(context.Background(), deleteSubnetReservedIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListIkePoliciesWithContext is an alternate form of the ListIkePolicies method which supports a Context parameter -func (vpc *VpcV1) ListIkePoliciesWithContext(ctx context.Context, listIkePoliciesOptions *ListIkePoliciesOptions) (result *IkePolicyCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listIkePoliciesOptions, "listIkePoliciesOptions") +// DeleteSubnetReservedIPWithContext is an alternate form of the DeleteSubnetReservedIP method which supports a Context parameter +func (vpc *VpcV1) DeleteSubnetReservedIPWithContext(ctx context.Context, deleteSubnetReservedIPOptions *DeleteSubnetReservedIPOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteSubnetReservedIPOptions, "deleteSubnetReservedIPOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(deleteSubnetReservedIPOptions, "deleteSubnetReservedIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.GET) + pathParamsMap := map[string]string{ + "subnet_id": *deleteSubnetReservedIPOptions.SubnetID, + "id": *deleteSubnetReservedIPOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listIkePoliciesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteSubnetReservedIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListIkePolicies") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteSubnetReservedIPOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listIkePoliciesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listIkePoliciesOptions.Start)) - } - if listIkePoliciesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listIkePoliciesOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -25699,97 +26981,64 @@ func (vpc *VpcV1) ListIkePoliciesWithContext(ctx context.Context, listIkePolicie return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_ike_policies", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_subnet_reserved_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicyCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreateIkePolicy : Create an IKE policy -// This request creates a new IKE policy. -func (vpc *VpcV1) CreateIkePolicy(createIkePolicyOptions *CreateIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateIkePolicyWithContext(context.Background(), createIkePolicyOptions) +// GetSubnetReservedIP : Retrieve a reserved IP +// This request retrieves a single reserved IP specified by the identifier in the URL. +func (vpc *VpcV1) GetSubnetReservedIP(getSubnetReservedIPOptions *GetSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetSubnetReservedIPWithContext(context.Background(), getSubnetReservedIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateIkePolicyWithContext is an alternate form of the CreateIkePolicy method which supports a Context parameter -func (vpc *VpcV1) CreateIkePolicyWithContext(ctx context.Context, createIkePolicyOptions *CreateIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createIkePolicyOptions, "createIkePolicyOptions cannot be nil") +// GetSubnetReservedIPWithContext is an alternate form of the GetSubnetReservedIP method which supports a Context parameter +func (vpc *VpcV1) GetSubnetReservedIPWithContext(ctx context.Context, getSubnetReservedIPOptions *GetSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getSubnetReservedIPOptions, "getSubnetReservedIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createIkePolicyOptions, "createIkePolicyOptions") + err = core.ValidateStruct(getSubnetReservedIPOptions, "getSubnetReservedIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "subnet_id": *getSubnetReservedIPOptions.SubnetID, + "id": *getSubnetReservedIPOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createIkePolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetSubnetReservedIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateIkePolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getSubnetReservedIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createIkePolicyOptions.AuthenticationAlgorithm != nil { - body["authentication_algorithm"] = createIkePolicyOptions.AuthenticationAlgorithm - } - if createIkePolicyOptions.DhGroup != nil { - body["dh_group"] = createIkePolicyOptions.DhGroup - } - if createIkePolicyOptions.EncryptionAlgorithm != nil { - body["encryption_algorithm"] = createIkePolicyOptions.EncryptionAlgorithm - } - if createIkePolicyOptions.IkeVersion != nil { - body["ike_version"] = createIkePolicyOptions.IkeVersion - } - if createIkePolicyOptions.KeyLifetime != nil { - body["key_lifetime"] = createIkePolicyOptions.KeyLifetime - } - if createIkePolicyOptions.Name != nil { - body["name"] = createIkePolicyOptions.Name - } - if createIkePolicyOptions.ResourceGroup != nil { - body["resource_group"] = createIkePolicyOptions.ResourceGroup - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -25799,12 +27048,12 @@ func (vpc *VpcV1) CreateIkePolicyWithContext(ctx context.Context, createIkePolic var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_ike_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_subnet_reserved_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25815,115 +27064,140 @@ func (vpc *VpcV1) CreateIkePolicyWithContext(ctx context.Context, createIkePolic return } -// DeleteIkePolicy : Delete an IKE policy -// This request deletes an IKE policy. This operation cannot be reversed. For this request to succeed, there must not be -// any VPN gateway connections using this policy. -func (vpc *VpcV1) DeleteIkePolicy(deleteIkePolicyOptions *DeleteIkePolicyOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteIkePolicyWithContext(context.Background(), deleteIkePolicyOptions) +// UpdateSubnetReservedIP : Update a reserved IP +// This request updates a reserved IP with the information in a provided reserved IP patch. The reserved IP patch object +// is structured in the same way as a retrieved reserved IP and contains only the information to be updated. +// +// A provider-owned reserved IP is not allowed to be updated. +func (vpc *VpcV1) UpdateSubnetReservedIP(updateSubnetReservedIPOptions *UpdateSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateSubnetReservedIPWithContext(context.Background(), updateSubnetReservedIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteIkePolicyWithContext is an alternate form of the DeleteIkePolicy method which supports a Context parameter -func (vpc *VpcV1) DeleteIkePolicyWithContext(ctx context.Context, deleteIkePolicyOptions *DeleteIkePolicyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteIkePolicyOptions, "deleteIkePolicyOptions cannot be nil") +// UpdateSubnetReservedIPWithContext is an alternate form of the UpdateSubnetReservedIP method which supports a Context parameter +func (vpc *VpcV1) UpdateSubnetReservedIPWithContext(ctx context.Context, updateSubnetReservedIPOptions *UpdateSubnetReservedIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateSubnetReservedIPOptions, "updateSubnetReservedIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteIkePolicyOptions, "deleteIkePolicyOptions") + err = core.ValidateStruct(updateSubnetReservedIPOptions, "updateSubnetReservedIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteIkePolicyOptions.ID, + "subnet_id": *updateSubnetReservedIPOptions.SubnetID, + "id": *updateSubnetReservedIPOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/subnets/{subnet_id}/reserved_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteIkePolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateSubnetReservedIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteIkePolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateSubnetReservedIPOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateSubnetReservedIPOptions.ReservedIPPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_ike_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_subnet_reserved_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetIkePolicy : Retrieve an IKE policy -// This request retrieves a single IKE policy specified by the identifier in the URL. -func (vpc *VpcV1) GetIkePolicy(getIkePolicyOptions *GetIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetIkePolicyWithContext(context.Background(), getIkePolicyOptions) +// ListVirtualNetworkInterfaces : List virtual network interfaces +// This request lists virtual network interfaces in the region. A virtual network interface is a logical abstraction of +// a virtual network interface in a subnet, and may be attached to a target resource. +// +// The virtual network interfaces will be sorted by their `created_at` property values, with newest virtual network +// interfaces first. Virtual network interfaces with identical +// `created_at` property values will in turn be sorted by ascending `name` property values. +func (vpc *VpcV1) ListVirtualNetworkInterfaces(listVirtualNetworkInterfacesOptions *ListVirtualNetworkInterfacesOptions) (result *VirtualNetworkInterfaceCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVirtualNetworkInterfacesWithContext(context.Background(), listVirtualNetworkInterfacesOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetIkePolicyWithContext is an alternate form of the GetIkePolicy method which supports a Context parameter -func (vpc *VpcV1) GetIkePolicyWithContext(ctx context.Context, getIkePolicyOptions *GetIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getIkePolicyOptions, "getIkePolicyOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getIkePolicyOptions, "getIkePolicyOptions") +// ListVirtualNetworkInterfacesWithContext is an alternate form of the ListVirtualNetworkInterfaces method which supports a Context parameter +func (vpc *VpcV1) ListVirtualNetworkInterfacesWithContext(ctx context.Context, listVirtualNetworkInterfacesOptions *ListVirtualNetworkInterfacesOptions) (result *VirtualNetworkInterfaceCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listVirtualNetworkInterfacesOptions, "listVirtualNetworkInterfacesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *getIkePolicyOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getIkePolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVirtualNetworkInterfaces") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetIkePolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVirtualNetworkInterfacesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listVirtualNetworkInterfacesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVirtualNetworkInterfacesOptions.Start)) + } + if listVirtualNetworkInterfacesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVirtualNetworkInterfacesOptions.Limit)) + } + if listVirtualNetworkInterfacesOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listVirtualNetworkInterfacesOptions.ResourceGroupID)) + } request, err := builder.Build() if err != nil { @@ -25934,12 +27208,12 @@ func (vpc *VpcV1) GetIkePolicyWithContext(ctx context.Context, getIkePolicyOptio var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_ike_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_virtual_network_interfaces", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterfaceCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -25950,55 +27224,84 @@ func (vpc *VpcV1) GetIkePolicyWithContext(ctx context.Context, getIkePolicyOptio return } -// UpdateIkePolicy : Update an IKE policy -// This request updates the properties of an existing IKE policy. -func (vpc *VpcV1) UpdateIkePolicy(updateIkePolicyOptions *UpdateIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateIkePolicyWithContext(context.Background(), updateIkePolicyOptions) +// CreateVirtualNetworkInterface : Create a virtual network interface +// This request creates a new virtual network interface from a virtual network interface prototype object. The prototype +// object is structured in the same way as a retrieved virtual network interface, and contains the information necessary +// to create the new virtual network interface. +func (vpc *VpcV1) CreateVirtualNetworkInterface(createVirtualNetworkInterfaceOptions *CreateVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVirtualNetworkInterfaceWithContext(context.Background(), createVirtualNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateIkePolicyWithContext is an alternate form of the UpdateIkePolicy method which supports a Context parameter -func (vpc *VpcV1) UpdateIkePolicyWithContext(ctx context.Context, updateIkePolicyOptions *UpdateIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateIkePolicyOptions, "updateIkePolicyOptions cannot be nil") +// CreateVirtualNetworkInterfaceWithContext is an alternate form of the CreateVirtualNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) CreateVirtualNetworkInterfaceWithContext(ctx context.Context, createVirtualNetworkInterfaceOptions *CreateVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVirtualNetworkInterfaceOptions, "createVirtualNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateIkePolicyOptions, "updateIkePolicyOptions") + err = core.ValidateStruct(createVirtualNetworkInterfaceOptions, "createVirtualNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *updateIkePolicyOptions.ID, - } - - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateIkePolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVirtualNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateIkePolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVirtualNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateIkePolicyOptions.IkePolicyPatch) + body := make(map[string]interface{}) + if createVirtualNetworkInterfaceOptions.AllowIPSpoofing != nil { + body["allow_ip_spoofing"] = createVirtualNetworkInterfaceOptions.AllowIPSpoofing + } + if createVirtualNetworkInterfaceOptions.AutoDelete != nil { + body["auto_delete"] = createVirtualNetworkInterfaceOptions.AutoDelete + } + if createVirtualNetworkInterfaceOptions.EnableInfrastructureNat != nil { + body["enable_infrastructure_nat"] = createVirtualNetworkInterfaceOptions.EnableInfrastructureNat + } + if createVirtualNetworkInterfaceOptions.Ips != nil { + body["ips"] = createVirtualNetworkInterfaceOptions.Ips + } + if createVirtualNetworkInterfaceOptions.Name != nil { + body["name"] = createVirtualNetworkInterfaceOptions.Name + } + if createVirtualNetworkInterfaceOptions.PrimaryIP != nil { + body["primary_ip"] = createVirtualNetworkInterfaceOptions.PrimaryIP + } + if createVirtualNetworkInterfaceOptions.ProtocolStateFilteringMode != nil { + body["protocol_state_filtering_mode"] = createVirtualNetworkInterfaceOptions.ProtocolStateFilteringMode + } + if createVirtualNetworkInterfaceOptions.ResourceGroup != nil { + body["resource_group"] = createVirtualNetworkInterfaceOptions.ResourceGroup + } + if createVirtualNetworkInterfaceOptions.SecurityGroups != nil { + body["security_groups"] = createVirtualNetworkInterfaceOptions.SecurityGroups + } + if createVirtualNetworkInterfaceOptions.Subnet != nil { + body["subnet"] = createVirtualNetworkInterfaceOptions.Subnet + } + _, err = builder.SetBodyContentJSON(body) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -26013,12 +27316,12 @@ func (vpc *VpcV1) UpdateIkePolicyWithContext(ctx context.Context, updateIkePolic var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_ike_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_virtual_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26029,58 +27332,54 @@ func (vpc *VpcV1) UpdateIkePolicyWithContext(ctx context.Context, updateIkePolic return } -// ListIkePolicyConnections : List VPN gateway connections that use a specified IKE policy -// This request lists VPN gateway connections that use an IKE policy. -func (vpc *VpcV1) ListIkePolicyConnections(listIkePolicyConnectionsOptions *ListIkePolicyConnectionsOptions) (result *IkePolicyConnectionCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListIkePolicyConnectionsWithContext(context.Background(), listIkePolicyConnectionsOptions) +// DeleteVirtualNetworkInterfaces : Delete a virtual network interface +// This request deletes a virtual network interface. This operation cannot be reversed. For this request to succeed, the +// virtual network interface must not be required by another resource, such as the primary network attachment for an +// instance. +func (vpc *VpcV1) DeleteVirtualNetworkInterfaces(deleteVirtualNetworkInterfacesOptions *DeleteVirtualNetworkInterfacesOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteVirtualNetworkInterfacesWithContext(context.Background(), deleteVirtualNetworkInterfacesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListIkePolicyConnectionsWithContext is an alternate form of the ListIkePolicyConnections method which supports a Context parameter -func (vpc *VpcV1) ListIkePolicyConnectionsWithContext(ctx context.Context, listIkePolicyConnectionsOptions *ListIkePolicyConnectionsOptions) (result *IkePolicyConnectionCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listIkePolicyConnectionsOptions, "listIkePolicyConnectionsOptions cannot be nil") +// DeleteVirtualNetworkInterfacesWithContext is an alternate form of the DeleteVirtualNetworkInterfaces method which supports a Context parameter +func (vpc *VpcV1) DeleteVirtualNetworkInterfacesWithContext(ctx context.Context, deleteVirtualNetworkInterfacesOptions *DeleteVirtualNetworkInterfacesOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVirtualNetworkInterfacesOptions, "deleteVirtualNetworkInterfacesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listIkePolicyConnectionsOptions, "listIkePolicyConnectionsOptions") + err = core.ValidateStruct(deleteVirtualNetworkInterfacesOptions, "deleteVirtualNetworkInterfacesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *listIkePolicyConnectionsOptions.ID, + "id": *deleteVirtualNetworkInterfacesOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies/{id}/connections`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listIkePolicyConnectionsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVirtualNetworkInterfaces") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListIkePolicyConnections") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVirtualNetworkInterfacesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listIkePolicyConnectionsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listIkePolicyConnectionsOptions.Start)) - } - if listIkePolicyConnectionsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listIkePolicyConnectionsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -26091,12 +27390,12 @@ func (vpc *VpcV1) ListIkePolicyConnectionsWithContext(ctx context.Context, listI var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_ike_policy_connections", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_virtual_network_interfaces", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicyConnectionCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26107,49 +27406,52 @@ func (vpc *VpcV1) ListIkePolicyConnectionsWithContext(ctx context.Context, listI return } -// ListIpsecPolicies : List IPsec policies -// This request lists IPsec policies in the region. -func (vpc *VpcV1) ListIpsecPolicies(listIpsecPoliciesOptions *ListIpsecPoliciesOptions) (result *IPsecPolicyCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListIpsecPoliciesWithContext(context.Background(), listIpsecPoliciesOptions) +// GetVirtualNetworkInterface : Retrieve a virtual network interface +// This request retrieves a single virtual network interface specified by the identifier in the URL. +func (vpc *VpcV1) GetVirtualNetworkInterface(getVirtualNetworkInterfaceOptions *GetVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVirtualNetworkInterfaceWithContext(context.Background(), getVirtualNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListIpsecPoliciesWithContext is an alternate form of the ListIpsecPolicies method which supports a Context parameter -func (vpc *VpcV1) ListIpsecPoliciesWithContext(ctx context.Context, listIpsecPoliciesOptions *ListIpsecPoliciesOptions) (result *IPsecPolicyCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listIpsecPoliciesOptions, "listIpsecPoliciesOptions") +// GetVirtualNetworkInterfaceWithContext is an alternate form of the GetVirtualNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) GetVirtualNetworkInterfaceWithContext(ctx context.Context, getVirtualNetworkInterfaceOptions *GetVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVirtualNetworkInterfaceOptions, "getVirtualNetworkInterfaceOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getVirtualNetworkInterfaceOptions, "getVirtualNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "id": *getVirtualNetworkInterfaceOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listIpsecPoliciesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVirtualNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListIpsecPolicies") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVirtualNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listIpsecPoliciesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listIpsecPoliciesOptions.Start)) - } - if listIpsecPoliciesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listIpsecPoliciesOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -26160,12 +27462,12 @@ func (vpc *VpcV1) ListIpsecPoliciesWithContext(ctx context.Context, listIpsecPol var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_ipsec_policies", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_virtual_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicyCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26176,70 +27478,57 @@ func (vpc *VpcV1) ListIpsecPoliciesWithContext(ctx context.Context, listIpsecPol return } -// CreateIpsecPolicy : Create an IPsec policy -// This request creates a new IPsec policy. -func (vpc *VpcV1) CreateIpsecPolicy(createIpsecPolicyOptions *CreateIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateIpsecPolicyWithContext(context.Background(), createIpsecPolicyOptions) +// UpdateVirtualNetworkInterface : Update a virtual network interface +// This request updates a virtual network interface with the information in a provided virtual network interface patch. +// The virtual network interface patch object is structured in the same way as a retrieved virtual network interface and +// contains only the information to be updated. +func (vpc *VpcV1) UpdateVirtualNetworkInterface(updateVirtualNetworkInterfaceOptions *UpdateVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVirtualNetworkInterfaceWithContext(context.Background(), updateVirtualNetworkInterfaceOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateIpsecPolicyWithContext is an alternate form of the CreateIpsecPolicy method which supports a Context parameter -func (vpc *VpcV1) CreateIpsecPolicyWithContext(ctx context.Context, createIpsecPolicyOptions *CreateIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createIpsecPolicyOptions, "createIpsecPolicyOptions cannot be nil") +// UpdateVirtualNetworkInterfaceWithContext is an alternate form of the UpdateVirtualNetworkInterface method which supports a Context parameter +func (vpc *VpcV1) UpdateVirtualNetworkInterfaceWithContext(ctx context.Context, updateVirtualNetworkInterfaceOptions *UpdateVirtualNetworkInterfaceOptions) (result *VirtualNetworkInterface, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVirtualNetworkInterfaceOptions, "updateVirtualNetworkInterfaceOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createIpsecPolicyOptions, "createIpsecPolicyOptions") + err = core.ValidateStruct(updateVirtualNetworkInterfaceOptions, "updateVirtualNetworkInterfaceOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "id": *updateVirtualNetworkInterfaceOptions.ID, + } + + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createIpsecPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVirtualNetworkInterface") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateIpsecPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVirtualNetworkInterfaceOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createIpsecPolicyOptions.AuthenticationAlgorithm != nil { - body["authentication_algorithm"] = createIpsecPolicyOptions.AuthenticationAlgorithm - } - if createIpsecPolicyOptions.EncryptionAlgorithm != nil { - body["encryption_algorithm"] = createIpsecPolicyOptions.EncryptionAlgorithm - } - if createIpsecPolicyOptions.Pfs != nil { - body["pfs"] = createIpsecPolicyOptions.Pfs - } - if createIpsecPolicyOptions.KeyLifetime != nil { - body["key_lifetime"] = createIpsecPolicyOptions.KeyLifetime - } - if createIpsecPolicyOptions.Name != nil { - body["name"] = createIpsecPolicyOptions.Name - } - if createIpsecPolicyOptions.ResourceGroup != nil { - body["resource_group"] = createIpsecPolicyOptions.ResourceGroup - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(updateVirtualNetworkInterfaceOptions.VirtualNetworkInterfacePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -26254,12 +27543,12 @@ func (vpc *VpcV1) CreateIpsecPolicyWithContext(ctx context.Context, createIpsecP var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_ipsec_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_virtual_network_interface", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVirtualNetworkInterface) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26270,52 +27559,61 @@ func (vpc *VpcV1) CreateIpsecPolicyWithContext(ctx context.Context, createIpsecP return } -// DeleteIpsecPolicy : Delete an IPsec policy -// This request deletes an IPsec policy. This operation cannot be reversed. For this request to succeed, there must not -// be any VPN gateway connections using this policy. -func (vpc *VpcV1) DeleteIpsecPolicy(deleteIpsecPolicyOptions *DeleteIpsecPolicyOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteIpsecPolicyWithContext(context.Background(), deleteIpsecPolicyOptions) +// ListNetworkInterfaceFloatingIps : List floating IPs associated with a virtual network interface +// This request lists floating IPs associated with a virtual network interface. +func (vpc *VpcV1) ListNetworkInterfaceFloatingIps(listNetworkInterfaceFloatingIpsOptions *ListNetworkInterfaceFloatingIpsOptions) (result *FloatingIPCollectionVirtualNetworkInterfaceContext, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListNetworkInterfaceFloatingIpsWithContext(context.Background(), listNetworkInterfaceFloatingIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteIpsecPolicyWithContext is an alternate form of the DeleteIpsecPolicy method which supports a Context parameter -func (vpc *VpcV1) DeleteIpsecPolicyWithContext(ctx context.Context, deleteIpsecPolicyOptions *DeleteIpsecPolicyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteIpsecPolicyOptions, "deleteIpsecPolicyOptions cannot be nil") +// ListNetworkInterfaceFloatingIpsWithContext is an alternate form of the ListNetworkInterfaceFloatingIps method which supports a Context parameter +func (vpc *VpcV1) ListNetworkInterfaceFloatingIpsWithContext(ctx context.Context, listNetworkInterfaceFloatingIpsOptions *ListNetworkInterfaceFloatingIpsOptions) (result *FloatingIPCollectionVirtualNetworkInterfaceContext, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listNetworkInterfaceFloatingIpsOptions, "listNetworkInterfaceFloatingIpsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteIpsecPolicyOptions, "deleteIpsecPolicyOptions") + err = core.ValidateStruct(listNetworkInterfaceFloatingIpsOptions, "listNetworkInterfaceFloatingIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteIpsecPolicyOptions.ID, + "virtual_network_interface_id": *listNetworkInterfaceFloatingIpsOptions.VirtualNetworkInterfaceID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/floating_ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteIpsecPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListNetworkInterfaceFloatingIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteIpsecPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listNetworkInterfaceFloatingIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listNetworkInterfaceFloatingIpsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listNetworkInterfaceFloatingIpsOptions.Start)) + } + if listNetworkInterfaceFloatingIpsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listNetworkInterfaceFloatingIpsOptions.Limit)) + } + if listNetworkInterfaceFloatingIpsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listNetworkInterfaceFloatingIpsOptions.Sort)) + } request, err := builder.Build() if err != nil { @@ -26323,59 +27621,68 @@ func (vpc *VpcV1) DeleteIpsecPolicyWithContext(ctx context.Context, deleteIpsecP return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_ipsec_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_network_interface_floating_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPCollectionVirtualNetworkInterfaceContext) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetIpsecPolicy : Retrieve an IPsec policy -// This request retrieves a single IPsec policy specified by the identifier in the URL. -func (vpc *VpcV1) GetIpsecPolicy(getIpsecPolicyOptions *GetIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetIpsecPolicyWithContext(context.Background(), getIpsecPolicyOptions) +// RemoveNetworkInterfaceFloatingIP : Disassociate a floating IP from a virtual network interface +// This request disassociates the specified floating IP from the specified virtual network interface. +func (vpc *VpcV1) RemoveNetworkInterfaceFloatingIP(removeNetworkInterfaceFloatingIPOptions *RemoveNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RemoveNetworkInterfaceFloatingIPWithContext(context.Background(), removeNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetIpsecPolicyWithContext is an alternate form of the GetIpsecPolicy method which supports a Context parameter -func (vpc *VpcV1) GetIpsecPolicyWithContext(ctx context.Context, getIpsecPolicyOptions *GetIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getIpsecPolicyOptions, "getIpsecPolicyOptions cannot be nil") +// RemoveNetworkInterfaceFloatingIPWithContext is an alternate form of the RemoveNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) RemoveNetworkInterfaceFloatingIPWithContext(ctx context.Context, removeNetworkInterfaceFloatingIPOptions *RemoveNetworkInterfaceFloatingIPOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(removeNetworkInterfaceFloatingIPOptions, "removeNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getIpsecPolicyOptions, "getIpsecPolicyOptions") + err = core.ValidateStruct(removeNetworkInterfaceFloatingIPOptions, "removeNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getIpsecPolicyOptions.ID, + "virtual_network_interface_id": *removeNetworkInterfaceFloatingIPOptions.VirtualNetworkInterfaceID, + "id": *removeNetworkInterfaceFloatingIPOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getIpsecPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetIpsecPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range removeNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -26386,79 +27693,65 @@ func (vpc *VpcV1) GetIpsecPolicyWithContext(ctx context.Context, getIpsecPolicyO return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_ipsec_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "remove_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicy) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// UpdateIpsecPolicy : Update an IPsec policy -// This request updates the properties of an existing IPsec policy. -func (vpc *VpcV1) UpdateIpsecPolicy(updateIpsecPolicyOptions *UpdateIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateIpsecPolicyWithContext(context.Background(), updateIpsecPolicyOptions) +// GetNetworkInterfaceFloatingIP : Retrieve associated floating IP +// This request retrieves a specified floating IP if it is associated with the virtual network interface specified in +// the URL. +func (vpc *VpcV1) GetNetworkInterfaceFloatingIP(getNetworkInterfaceFloatingIPOptions *GetNetworkInterfaceFloatingIPOptions) (result *FloatingIPReference, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetNetworkInterfaceFloatingIPWithContext(context.Background(), getNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateIpsecPolicyWithContext is an alternate form of the UpdateIpsecPolicy method which supports a Context parameter -func (vpc *VpcV1) UpdateIpsecPolicyWithContext(ctx context.Context, updateIpsecPolicyOptions *UpdateIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateIpsecPolicyOptions, "updateIpsecPolicyOptions cannot be nil") +// GetNetworkInterfaceFloatingIPWithContext is an alternate form of the GetNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) GetNetworkInterfaceFloatingIPWithContext(ctx context.Context, getNetworkInterfaceFloatingIPOptions *GetNetworkInterfaceFloatingIPOptions) (result *FloatingIPReference, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getNetworkInterfaceFloatingIPOptions, "getNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateIpsecPolicyOptions, "updateIpsecPolicyOptions") + err = core.ValidateStruct(getNetworkInterfaceFloatingIPOptions, "getNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateIpsecPolicyOptions.ID, + "virtual_network_interface_id": *getNetworkInterfaceFloatingIPOptions.VirtualNetworkInterfaceID, + "id": *getNetworkInterfaceFloatingIPOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateIpsecPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateIpsecPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateIpsecPolicyOptions.IPsecPolicyPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -26468,12 +27761,12 @@ func (vpc *VpcV1) UpdateIpsecPolicyWithContext(ctx context.Context, updateIpsecP var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_ipsec_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPReference) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26484,58 +27777,68 @@ func (vpc *VpcV1) UpdateIpsecPolicyWithContext(ctx context.Context, updateIpsecP return } -// ListIpsecPolicyConnections : List VPN gateway connections that use a specified IPsec policy -// This request lists VPN gateway connections that use an IPsec policy. -func (vpc *VpcV1) ListIpsecPolicyConnections(listIpsecPolicyConnectionsOptions *ListIpsecPolicyConnectionsOptions) (result *IPsecPolicyConnectionCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListIpsecPolicyConnectionsWithContext(context.Background(), listIpsecPolicyConnectionsOptions) +// AddNetworkInterfaceFloatingIP : Add an association between a floating IP and a virtual network interface +// This request adds an association between the specified floating IP and the specified virtual network interface. +// +// If the virtual network interface has `enable_infrastructure_nat` set to `true`, no more than one floating IP can be +// associated, and network address translation is performed between the floating IP address and the virtual network +// interface's `primary_ip` address. +// +// If the virtual network interface has `enable_infrastructure_nat` set to `false`, packets are passed unchanged to/from +// the virtual network interface. +// +// The floating IP must: +// - be in the same `zone` as the virtual network interface +// - not currently be associated with another resource +// +// The virtual network interface's `target` must not currently be a file share mount target. +// +// A request body is not required, and if provided, is ignored. +func (vpc *VpcV1) AddNetworkInterfaceFloatingIP(addNetworkInterfaceFloatingIPOptions *AddNetworkInterfaceFloatingIPOptions) (result *FloatingIPReference, response *core.DetailedResponse, err error) { + result, response, err = vpc.AddNetworkInterfaceFloatingIPWithContext(context.Background(), addNetworkInterfaceFloatingIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListIpsecPolicyConnectionsWithContext is an alternate form of the ListIpsecPolicyConnections method which supports a Context parameter -func (vpc *VpcV1) ListIpsecPolicyConnectionsWithContext(ctx context.Context, listIpsecPolicyConnectionsOptions *ListIpsecPolicyConnectionsOptions) (result *IPsecPolicyConnectionCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listIpsecPolicyConnectionsOptions, "listIpsecPolicyConnectionsOptions cannot be nil") +// AddNetworkInterfaceFloatingIPWithContext is an alternate form of the AddNetworkInterfaceFloatingIP method which supports a Context parameter +func (vpc *VpcV1) AddNetworkInterfaceFloatingIPWithContext(ctx context.Context, addNetworkInterfaceFloatingIPOptions *AddNetworkInterfaceFloatingIPOptions) (result *FloatingIPReference, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(addNetworkInterfaceFloatingIPOptions, "addNetworkInterfaceFloatingIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listIpsecPolicyConnectionsOptions, "listIpsecPolicyConnectionsOptions") + err = core.ValidateStruct(addNetworkInterfaceFloatingIPOptions, "addNetworkInterfaceFloatingIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *listIpsecPolicyConnectionsOptions.ID, + "virtual_network_interface_id": *addNetworkInterfaceFloatingIPOptions.VirtualNetworkInterfaceID, + "id": *addNetworkInterfaceFloatingIPOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies/{id}/connections`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/floating_ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listIpsecPolicyConnectionsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddNetworkInterfaceFloatingIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListIpsecPolicyConnections") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range addNetworkInterfaceFloatingIPOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listIpsecPolicyConnectionsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listIpsecPolicyConnectionsOptions.Start)) - } - if listIpsecPolicyConnectionsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listIpsecPolicyConnectionsOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -26546,12 +27849,12 @@ func (vpc *VpcV1) ListIpsecPolicyConnectionsWithContext(ctx context.Context, lis var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_ipsec_policy_connections", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "add_network_interface_floating_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicyConnectionCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFloatingIPReference) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26562,57 +27865,60 @@ func (vpc *VpcV1) ListIpsecPolicyConnectionsWithContext(ctx context.Context, lis return } -// ListVPNGateways : List VPN gateways -// This request lists VPN gateways in the region. -func (vpc *VpcV1) ListVPNGateways(listVPNGatewaysOptions *ListVPNGatewaysOptions) (result *VPNGatewayCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPNGatewaysWithContext(context.Background(), listVPNGatewaysOptions) +// ListVirtualNetworkInterfaceIps : List reserved IPs bound to a virtual network interface +// This request lists reserved IPs bound to a virtual network interface. +func (vpc *VpcV1) ListVirtualNetworkInterfaceIps(listVirtualNetworkInterfaceIpsOptions *ListVirtualNetworkInterfaceIpsOptions) (result *ReservedIPCollectionVirtualNetworkInterfaceContext, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVirtualNetworkInterfaceIpsWithContext(context.Background(), listVirtualNetworkInterfaceIpsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPNGatewaysWithContext is an alternate form of the ListVPNGateways method which supports a Context parameter -func (vpc *VpcV1) ListVPNGatewaysWithContext(ctx context.Context, listVPNGatewaysOptions *ListVPNGatewaysOptions) (result *VPNGatewayCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listVPNGatewaysOptions, "listVPNGatewaysOptions") +// ListVirtualNetworkInterfaceIpsWithContext is an alternate form of the ListVirtualNetworkInterfaceIps method which supports a Context parameter +func (vpc *VpcV1) ListVirtualNetworkInterfaceIpsWithContext(ctx context.Context, listVirtualNetworkInterfaceIpsOptions *ListVirtualNetworkInterfaceIpsOptions) (result *ReservedIPCollectionVirtualNetworkInterfaceContext, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVirtualNetworkInterfaceIpsOptions, "listVirtualNetworkInterfaceIpsOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listVirtualNetworkInterfaceIpsOptions, "listVirtualNetworkInterfaceIpsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "virtual_network_interface_id": *listVirtualNetworkInterfaceIpsOptions.VirtualNetworkInterfaceID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/ips`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPNGatewaysOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVirtualNetworkInterfaceIps") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNGateways") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVirtualNetworkInterfaceIpsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPNGatewaysOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPNGatewaysOptions.Start)) + if listVirtualNetworkInterfaceIpsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVirtualNetworkInterfaceIpsOptions.Start)) } - if listVPNGatewaysOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPNGatewaysOptions.Limit)) + if listVirtualNetworkInterfaceIpsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVirtualNetworkInterfaceIpsOptions.Limit)) } - if listVPNGatewaysOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listVPNGatewaysOptions.ResourceGroupID)) - } - if listVPNGatewaysOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listVPNGatewaysOptions.Sort)) - } - if listVPNGatewaysOptions.Mode != nil { - builder.AddQuery("mode", fmt.Sprint(*listVPNGatewaysOptions.Mode)) + if listVirtualNetworkInterfaceIpsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listVirtualNetworkInterfaceIpsOptions.Sort)) } request, err := builder.Build() @@ -26624,12 +27930,12 @@ func (vpc *VpcV1) ListVPNGatewaysWithContext(ctx context.Context, listVPNGateway var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpn_gateways", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_virtual_network_interface_ips", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollectionVirtualNetworkInterfaceContext) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26640,56 +27946,121 @@ func (vpc *VpcV1) ListVPNGatewaysWithContext(ctx context.Context, listVPNGateway return } -// CreateVPNGateway : Create a VPN gateway -// This request creates a new VPN gateway. -func (vpc *VpcV1) CreateVPNGateway(createVPNGatewayOptions *CreateVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPNGatewayWithContext(context.Background(), createVPNGatewayOptions) +// RemoveVirtualNetworkInterfaceIP : Unbind a reserved IP from a virtual network interface +// This request unbinds the specified reserved IP from the specified virtual network interface. If the reserved IP has +// `auto_delete` set to `true`, the reserved IP will be deleted. +// +// The reserved IP for the `primary_ip` cannot be unbound. +func (vpc *VpcV1) RemoveVirtualNetworkInterfaceIP(removeVirtualNetworkInterfaceIPOptions *RemoveVirtualNetworkInterfaceIPOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RemoveVirtualNetworkInterfaceIPWithContext(context.Background(), removeVirtualNetworkInterfaceIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPNGatewayWithContext is an alternate form of the CreateVPNGateway method which supports a Context parameter -func (vpc *VpcV1) CreateVPNGatewayWithContext(ctx context.Context, createVPNGatewayOptions *CreateVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVPNGatewayOptions, "createVPNGatewayOptions cannot be nil") +// RemoveVirtualNetworkInterfaceIPWithContext is an alternate form of the RemoveVirtualNetworkInterfaceIP method which supports a Context parameter +func (vpc *VpcV1) RemoveVirtualNetworkInterfaceIPWithContext(ctx context.Context, removeVirtualNetworkInterfaceIPOptions *RemoveVirtualNetworkInterfaceIPOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(removeVirtualNetworkInterfaceIPOptions, "removeVirtualNetworkInterfaceIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVPNGatewayOptions, "createVPNGatewayOptions") + err = core.ValidateStruct(removeVirtualNetworkInterfaceIPOptions, "removeVirtualNetworkInterfaceIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "virtual_network_interface_id": *removeVirtualNetworkInterfaceIPOptions.VirtualNetworkInterfaceID, + "id": *removeVirtualNetworkInterfaceIPOptions.ID, + } + + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPNGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveVirtualNetworkInterfaceIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPNGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range removeVirtualNetworkInterfaceIPOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createVPNGatewayOptions.VPNGatewayPrototype) + request, err := builder.Build() if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + response, err = vpc.Service.Request(request, nil) + if err != nil { + core.EnrichHTTPProblem(err, "remove_virtual_network_interface_ip", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + + return +} + +// GetVirtualNetworkInterfaceIP : Retrieve bound reserved IP +// This request retrieves the specified reserved IP address if it is bound to the virtual network interface specified in +// the URL. +func (vpc *VpcV1) GetVirtualNetworkInterfaceIP(getVirtualNetworkInterfaceIPOptions *GetVirtualNetworkInterfaceIPOptions) (result *ReservedIPReference, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVirtualNetworkInterfaceIPWithContext(context.Background(), getVirtualNetworkInterfaceIPOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetVirtualNetworkInterfaceIPWithContext is an alternate form of the GetVirtualNetworkInterfaceIP method which supports a Context parameter +func (vpc *VpcV1) GetVirtualNetworkInterfaceIPWithContext(ctx context.Context, getVirtualNetworkInterfaceIPOptions *GetVirtualNetworkInterfaceIPOptions) (result *ReservedIPReference, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVirtualNetworkInterfaceIPOptions, "getVirtualNetworkInterfaceIPOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getVirtualNetworkInterfaceIPOptions, "getVirtualNetworkInterfaceIPOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + pathParamsMap := map[string]string{ + "virtual_network_interface_id": *getVirtualNetworkInterfaceIPOptions.VirtualNetworkInterfaceID, + "id": *getVirtualNetworkInterfaceIPOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/ips/{id}`, pathParamsMap) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVirtualNetworkInterfaceIP") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + + for headerName, headerValue := range getVirtualNetworkInterfaceIPOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -26699,12 +28070,12 @@ func (vpc *VpcV1) CreateVPNGatewayWithContext(ctx context.Context, createVPNGate var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpn_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_virtual_network_interface_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPReference) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26715,50 +28086,53 @@ func (vpc *VpcV1) CreateVPNGatewayWithContext(ctx context.Context, createVPNGate return } -// DeleteVPNGateway : Delete a VPN gateway -// This request deletes a VPN gateway. This operation cannot be reversed. For this request to succeed, the VPN gateway -// must not have a `status` of `pending`, and there must not be any VPC routes using the VPN gateway's connections as a -// next hop. -func (vpc *VpcV1) DeleteVPNGateway(deleteVPNGatewayOptions *DeleteVPNGatewayOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPNGatewayWithContext(context.Background(), deleteVPNGatewayOptions) +// AddVirtualNetworkInterfaceIP : Bind a reserved IP to a virtual network interface +// This request binds the specified reserved IP to the specified virtual network interface. +// +// The reserved IP must currently be unbound and in the primary IP's subnet. The virtual network interface's `target` +// must not currently be a file share mount target. +func (vpc *VpcV1) AddVirtualNetworkInterfaceIP(addVirtualNetworkInterfaceIPOptions *AddVirtualNetworkInterfaceIPOptions) (result *ReservedIPReference, response *core.DetailedResponse, err error) { + result, response, err = vpc.AddVirtualNetworkInterfaceIPWithContext(context.Background(), addVirtualNetworkInterfaceIPOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPNGatewayWithContext is an alternate form of the DeleteVPNGateway method which supports a Context parameter -func (vpc *VpcV1) DeleteVPNGatewayWithContext(ctx context.Context, deleteVPNGatewayOptions *DeleteVPNGatewayOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPNGatewayOptions, "deleteVPNGatewayOptions cannot be nil") +// AddVirtualNetworkInterfaceIPWithContext is an alternate form of the AddVirtualNetworkInterfaceIP method which supports a Context parameter +func (vpc *VpcV1) AddVirtualNetworkInterfaceIPWithContext(ctx context.Context, addVirtualNetworkInterfaceIPOptions *AddVirtualNetworkInterfaceIPOptions) (result *ReservedIPReference, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(addVirtualNetworkInterfaceIPOptions, "addVirtualNetworkInterfaceIPOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPNGatewayOptions, "deleteVPNGatewayOptions") + err = core.ValidateStruct(addVirtualNetworkInterfaceIPOptions, "addVirtualNetworkInterfaceIPOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteVPNGatewayOptions.ID, + "virtual_network_interface_id": *addVirtualNetworkInterfaceIPOptions.VirtualNetworkInterfaceID, + "id": *addVirtualNetworkInterfaceIPOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/virtual_network_interfaces/{virtual_network_interface_id}/ips/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPNGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddVirtualNetworkInterfaceIP") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range addVirtualNetworkInterfaceIPOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -26769,62 +28143,69 @@ func (vpc *VpcV1) DeleteVPNGatewayWithContext(ctx context.Context, deleteVPNGate return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpn_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "add_virtual_network_interface_ip", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPReference) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetVPNGateway : Retrieve a VPN gateway -// This request retrieves a single VPN gateway specified by the identifier in the URL. -func (vpc *VpcV1) GetVPNGateway(getVPNGatewayOptions *GetVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPNGatewayWithContext(context.Background(), getVPNGatewayOptions) +// ListVolumeProfiles : List volume profiles +// This request lists [volume profiles](https://cloud.ibm.com/docs/vpc?topic=vpc-block-storage-profiles) available in +// the region. A volume profile specifies the performance characteristics and pricing model for a volume. +func (vpc *VpcV1) ListVolumeProfiles(listVolumeProfilesOptions *ListVolumeProfilesOptions) (result *VolumeProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVolumeProfilesWithContext(context.Background(), listVolumeProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPNGatewayWithContext is an alternate form of the GetVPNGateway method which supports a Context parameter -func (vpc *VpcV1) GetVPNGatewayWithContext(ctx context.Context, getVPNGatewayOptions *GetVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPNGatewayOptions, "getVPNGatewayOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getVPNGatewayOptions, "getVPNGatewayOptions") +// ListVolumeProfilesWithContext is an alternate form of the ListVolumeProfiles method which supports a Context parameter +func (vpc *VpcV1) ListVolumeProfilesWithContext(ctx context.Context, listVolumeProfilesOptions *ListVolumeProfilesOptions) (result *VolumeProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listVolumeProfilesOptions, "listVolumeProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "id": *getVPNGatewayOptions.ID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volume/profiles`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPNGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVolumeProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVolumeProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listVolumeProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVolumeProfilesOptions.Start)) + } + if listVolumeProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVolumeProfilesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -26835,12 +28216,12 @@ func (vpc *VpcV1) GetVPNGatewayWithContext(ctx context.Context, getVPNGatewayOpt var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpn_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_volume_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26851,60 +28232,53 @@ func (vpc *VpcV1) GetVPNGatewayWithContext(ctx context.Context, getVPNGatewayOpt return } -// UpdateVPNGateway : Update a VPN gateway -// This request updates the properties of an existing VPN gateway. -func (vpc *VpcV1) UpdateVPNGateway(updateVPNGatewayOptions *UpdateVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPNGatewayWithContext(context.Background(), updateVPNGatewayOptions) +// GetVolumeProfile : Retrieve a volume profile +// This request retrieves a single volume profile specified by the name in the URL. +func (vpc *VpcV1) GetVolumeProfile(getVolumeProfileOptions *GetVolumeProfileOptions) (result *VolumeProfile, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVolumeProfileWithContext(context.Background(), getVolumeProfileOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPNGatewayWithContext is an alternate form of the UpdateVPNGateway method which supports a Context parameter -func (vpc *VpcV1) UpdateVPNGatewayWithContext(ctx context.Context, updateVPNGatewayOptions *UpdateVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPNGatewayOptions, "updateVPNGatewayOptions cannot be nil") +// GetVolumeProfileWithContext is an alternate form of the GetVolumeProfile method which supports a Context parameter +func (vpc *VpcV1) GetVolumeProfileWithContext(ctx context.Context, getVolumeProfileOptions *GetVolumeProfileOptions) (result *VolumeProfile, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVolumeProfileOptions, "getVolumeProfileOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPNGatewayOptions, "updateVPNGatewayOptions") + err = core.ValidateStruct(getVolumeProfileOptions, "getVolumeProfileOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateVPNGatewayOptions.ID, + "name": *getVolumeProfileOptions.Name, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volume/profiles/{name}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPNGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVolumeProfile") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPNGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVolumeProfileOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVPNGatewayOptions.VPNGatewayPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -26914,12 +28288,12 @@ func (vpc *VpcV1) UpdateVPNGatewayWithContext(ctx context.Context, updateVPNGate var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_vpn_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_volume_profile", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeProfile) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -26930,60 +28304,70 @@ func (vpc *VpcV1) UpdateVPNGatewayWithContext(ctx context.Context, updateVPNGate return } -// ListVPNGatewayConnections : List connections of a VPN gateway -// This request lists connections of a VPN gateway. -func (vpc *VpcV1) ListVPNGatewayConnections(listVPNGatewayConnectionsOptions *ListVPNGatewayConnectionsOptions) (result *VPNGatewayConnectionCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPNGatewayConnectionsWithContext(context.Background(), listVPNGatewayConnectionsOptions) +// ListVolumes : List volumes +// This request lists volumes in the region. Volumes are network-connected block storage devices that may be attached to +// one or more instances in the same region. +func (vpc *VpcV1) ListVolumes(listVolumesOptions *ListVolumesOptions) (result *VolumeCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVolumesWithContext(context.Background(), listVolumesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPNGatewayConnectionsWithContext is an alternate form of the ListVPNGatewayConnections method which supports a Context parameter -func (vpc *VpcV1) ListVPNGatewayConnectionsWithContext(ctx context.Context, listVPNGatewayConnectionsOptions *ListVPNGatewayConnectionsOptions) (result *VPNGatewayConnectionCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPNGatewayConnectionsOptions, "listVPNGatewayConnectionsOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(listVPNGatewayConnectionsOptions, "listVPNGatewayConnectionsOptions") +// ListVolumesWithContext is an alternate form of the ListVolumes method which supports a Context parameter +func (vpc *VpcV1) ListVolumesWithContext(ctx context.Context, listVolumesOptions *ListVolumesOptions) (result *VolumeCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listVolumesOptions, "listVolumesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "vpn_gateway_id": *listVPNGatewayConnectionsOptions.VPNGatewayID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPNGatewayConnectionsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVolumes") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNGatewayConnections") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVolumesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPNGatewayConnectionsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPNGatewayConnectionsOptions.Start)) + if listVolumesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVolumesOptions.Start)) } - if listVPNGatewayConnectionsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPNGatewayConnectionsOptions.Limit)) + if listVolumesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVolumesOptions.Limit)) } - if listVPNGatewayConnectionsOptions.Status != nil { - builder.AddQuery("status", fmt.Sprint(*listVPNGatewayConnectionsOptions.Status)) + if listVolumesOptions.AttachmentState != nil { + builder.AddQuery("attachment_state", fmt.Sprint(*listVolumesOptions.AttachmentState)) + } + if listVolumesOptions.Encryption != nil { + builder.AddQuery("encryption", fmt.Sprint(*listVolumesOptions.Encryption)) + } + if listVolumesOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listVolumesOptions.Name)) + } + if listVolumesOptions.OperatingSystemFamily != nil { + builder.AddQuery("operating_system.family", fmt.Sprint(*listVolumesOptions.OperatingSystemFamily)) + } + if listVolumesOptions.OperatingSystemArchitecture != nil { + builder.AddQuery("operating_system.architecture", fmt.Sprint(*listVolumesOptions.OperatingSystemArchitecture)) + } + if listVolumesOptions.Tag != nil { + builder.AddQuery("tag", fmt.Sprint(*listVolumesOptions.Tag)) + } + if listVolumesOptions.ZoneName != nil { + builder.AddQuery("zone.name", fmt.Sprint(*listVolumesOptions.ZoneName)) } request, err := builder.Build() @@ -26995,12 +28379,12 @@ func (vpc *VpcV1) ListVPNGatewayConnectionsWithContext(ctx context.Context, list var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpn_gateway_connections", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_volumes", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnectionCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -27011,46 +28395,43 @@ func (vpc *VpcV1) ListVPNGatewayConnectionsWithContext(ctx context.Context, list return } -// CreateVPNGatewayConnection : Create a connection for a VPN gateway -// This request creates a new VPN gateway connection. -func (vpc *VpcV1) CreateVPNGatewayConnection(createVPNGatewayConnectionOptions *CreateVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPNGatewayConnectionWithContext(context.Background(), createVPNGatewayConnectionOptions) +// CreateVolume : Create a volume +// This request creates a new volume from a volume prototype object. The prototype object is structured in the same way +// as a retrieved volume, and contains the information necessary to create the new volume. +func (vpc *VpcV1) CreateVolume(createVolumeOptions *CreateVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVolumeWithContext(context.Background(), createVolumeOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPNGatewayConnectionWithContext is an alternate form of the CreateVPNGatewayConnection method which supports a Context parameter -func (vpc *VpcV1) CreateVPNGatewayConnectionWithContext(ctx context.Context, createVPNGatewayConnectionOptions *CreateVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVPNGatewayConnectionOptions, "createVPNGatewayConnectionOptions cannot be nil") +// CreateVolumeWithContext is an alternate form of the CreateVolume method which supports a Context parameter +func (vpc *VpcV1) CreateVolumeWithContext(ctx context.Context, createVolumeOptions *CreateVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVolumeOptions, "createVolumeOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVPNGatewayConnectionOptions, "createVPNGatewayConnectionOptions") + err = core.ValidateStruct(createVolumeOptions, "createVolumeOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "vpn_gateway_id": *createVPNGatewayConnectionOptions.VPNGatewayID, - } - builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPNGatewayConnectionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVolume") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPNGatewayConnection") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVolumeOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -27059,7 +28440,7 @@ func (vpc *VpcV1) CreateVPNGatewayConnectionWithContext(ctx context.Context, cre builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(createVPNGatewayConnectionOptions.VPNGatewayConnectionPrototype) + _, err = builder.SetBodyContentJSON(createVolumeOptions.VolumePrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -27074,12 +28455,12 @@ func (vpc *VpcV1) CreateVPNGatewayConnectionWithContext(ctx context.Context, cre var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpn_gateway_connection", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_volume", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolume) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -27090,50 +28471,52 @@ func (vpc *VpcV1) CreateVPNGatewayConnectionWithContext(ctx context.Context, cre return } -// DeleteVPNGatewayConnection : Delete a VPN gateway connection -// This request deletes a VPN gateway connection. This operation cannot be reversed. For this request to succeed, there -// must not be VPC routes using this VPN connection as a next hop. -func (vpc *VpcV1) DeleteVPNGatewayConnection(deleteVPNGatewayConnectionOptions *DeleteVPNGatewayConnectionOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPNGatewayConnectionWithContext(context.Background(), deleteVPNGatewayConnectionOptions) +// DeleteVolume : Delete a volume +// This request deletes a volume. This operation cannot be reversed. For this request to succeed, the volume must not be +// attached to any instances. +func (vpc *VpcV1) DeleteVolume(deleteVolumeOptions *DeleteVolumeOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVolumeWithContext(context.Background(), deleteVolumeOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPNGatewayConnectionWithContext is an alternate form of the DeleteVPNGatewayConnection method which supports a Context parameter -func (vpc *VpcV1) DeleteVPNGatewayConnectionWithContext(ctx context.Context, deleteVPNGatewayConnectionOptions *DeleteVPNGatewayConnectionOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPNGatewayConnectionOptions, "deleteVPNGatewayConnectionOptions cannot be nil") +// DeleteVolumeWithContext is an alternate form of the DeleteVolume method which supports a Context parameter +func (vpc *VpcV1) DeleteVolumeWithContext(ctx context.Context, deleteVolumeOptions *DeleteVolumeOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVolumeOptions, "deleteVolumeOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPNGatewayConnectionOptions, "deleteVPNGatewayConnectionOptions") + err = core.ValidateStruct(deleteVolumeOptions, "deleteVolumeOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *deleteVPNGatewayConnectionOptions.VPNGatewayID, - "id": *deleteVPNGatewayConnectionOptions.ID, + "id": *deleteVolumeOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPNGatewayConnectionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVolume") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNGatewayConnection") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVolumeOptions.Headers { builder.AddHeader(headerName, headerValue) } + if deleteVolumeOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteVolumeOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -27146,7 +28529,7 @@ func (vpc *VpcV1) DeleteVPNGatewayConnectionWithContext(ctx context.Context, del response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpn_gateway_connection", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_volume", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -27154,47 +28537,46 @@ func (vpc *VpcV1) DeleteVPNGatewayConnectionWithContext(ctx context.Context, del return } -// GetVPNGatewayConnection : Retrieve a VPN gateway connection -// This request retrieves a single VPN gateway connection specified by the identifier in the URL. -func (vpc *VpcV1) GetVPNGatewayConnection(getVPNGatewayConnectionOptions *GetVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPNGatewayConnectionWithContext(context.Background(), getVPNGatewayConnectionOptions) +// GetVolume : Retrieve a volume +// This request retrieves a single volume specified by the identifier in the URL. +func (vpc *VpcV1) GetVolume(getVolumeOptions *GetVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVolumeWithContext(context.Background(), getVolumeOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPNGatewayConnectionWithContext is an alternate form of the GetVPNGatewayConnection method which supports a Context parameter -func (vpc *VpcV1) GetVPNGatewayConnectionWithContext(ctx context.Context, getVPNGatewayConnectionOptions *GetVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPNGatewayConnectionOptions, "getVPNGatewayConnectionOptions cannot be nil") +// GetVolumeWithContext is an alternate form of the GetVolume method which supports a Context parameter +func (vpc *VpcV1) GetVolumeWithContext(ctx context.Context, getVolumeOptions *GetVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVolumeOptions, "getVolumeOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPNGatewayConnectionOptions, "getVPNGatewayConnectionOptions") + err = core.ValidateStruct(getVolumeOptions, "getVolumeOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *getVPNGatewayConnectionOptions.VPNGatewayID, - "id": *getVPNGatewayConnectionOptions.ID, + "id": *getVolumeOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPNGatewayConnectionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVolume") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNGatewayConnection") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVolumeOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -27211,12 +28593,12 @@ func (vpc *VpcV1) GetVPNGatewayConnectionWithContext(ctx context.Context, getVPN var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpn_gateway_connection", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_volume", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolume) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -27227,56 +28609,59 @@ func (vpc *VpcV1) GetVPNGatewayConnectionWithContext(ctx context.Context, getVPN return } -// UpdateVPNGatewayConnection : Update a VPN gateway connection -// This request updates the properties of an existing VPN gateway connection. -func (vpc *VpcV1) UpdateVPNGatewayConnection(updateVPNGatewayConnectionOptions *UpdateVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPNGatewayConnectionWithContext(context.Background(), updateVPNGatewayConnectionOptions) +// UpdateVolume : Update a volume +// This request updates a volume with the information in a provided volume patch. The volume patch object is structured +// in the same way as a retrieved volume and contains only the information to be updated. +func (vpc *VpcV1) UpdateVolume(updateVolumeOptions *UpdateVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVolumeWithContext(context.Background(), updateVolumeOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPNGatewayConnectionWithContext is an alternate form of the UpdateVPNGatewayConnection method which supports a Context parameter -func (vpc *VpcV1) UpdateVPNGatewayConnectionWithContext(ctx context.Context, updateVPNGatewayConnectionOptions *UpdateVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPNGatewayConnectionOptions, "updateVPNGatewayConnectionOptions cannot be nil") +// UpdateVolumeWithContext is an alternate form of the UpdateVolume method which supports a Context parameter +func (vpc *VpcV1) UpdateVolumeWithContext(ctx context.Context, updateVolumeOptions *UpdateVolumeOptions) (result *Volume, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVolumeOptions, "updateVolumeOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPNGatewayConnectionOptions, "updateVPNGatewayConnectionOptions") + err = core.ValidateStruct(updateVolumeOptions, "updateVolumeOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *updateVPNGatewayConnectionOptions.VPNGatewayID, - "id": *updateVPNGatewayConnectionOptions.ID, + "id": *updateVolumeOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPNGatewayConnectionOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVolume") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPNGatewayConnection") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVolumeOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateVolumeOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateVolumeOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVPNGatewayConnectionOptions.VPNGatewayConnectionPatch) + _, err = builder.SetBodyContentJSON(updateVolumeOptions.VolumePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -27291,12 +28676,12 @@ func (vpc *VpcV1) UpdateVPNGatewayConnectionWithContext(ctx context.Context, upd var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_vpn_gateway_connection", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_volume", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolume) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -27307,55 +28692,61 @@ func (vpc *VpcV1) UpdateVPNGatewayConnectionWithContext(ctx context.Context, upd return } -// ListVPNGatewayConnectionsLocalCIDRs : List local CIDRs for a VPN gateway connection -// This request lists local CIDRs for a VPN gateway connection. -// -// This request is only supported for policy mode VPN gateways. -func (vpc *VpcV1) ListVPNGatewayConnectionsLocalCIDRs(listVPNGatewayConnectionsLocalCIDRsOptions *ListVPNGatewayConnectionsLocalCIDRsOptions) (result *VPNGatewayConnectionCIDRs, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPNGatewayConnectionsLocalCIDRsWithContext(context.Background(), listVPNGatewayConnectionsLocalCIDRsOptions) +// ListVolumeInstanceProfiles : List instance profiles compatible with a volume +// This request lists instance profiles compatible with a volume's +// `allowed_use.instance`, `operating_system.architecture` and +// `operating_system.user_data_format` properties, sorted by ascending `name` property values. The specified volume must +// be bootable (have an `operating_system` property). +func (vpc *VpcV1) ListVolumeInstanceProfiles(listVolumeInstanceProfilesOptions *ListVolumeInstanceProfilesOptions) (result *VolumeInstanceProfileCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVolumeInstanceProfilesWithContext(context.Background(), listVolumeInstanceProfilesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPNGatewayConnectionsLocalCIDRsWithContext is an alternate form of the ListVPNGatewayConnectionsLocalCIDRs method which supports a Context parameter -func (vpc *VpcV1) ListVPNGatewayConnectionsLocalCIDRsWithContext(ctx context.Context, listVPNGatewayConnectionsLocalCIDRsOptions *ListVPNGatewayConnectionsLocalCIDRsOptions) (result *VPNGatewayConnectionCIDRs, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPNGatewayConnectionsLocalCIDRsOptions, "listVPNGatewayConnectionsLocalCIDRsOptions cannot be nil") +// ListVolumeInstanceProfilesWithContext is an alternate form of the ListVolumeInstanceProfiles method which supports a Context parameter +func (vpc *VpcV1) ListVolumeInstanceProfilesWithContext(ctx context.Context, listVolumeInstanceProfilesOptions *ListVolumeInstanceProfilesOptions) (result *VolumeInstanceProfileCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVolumeInstanceProfilesOptions, "listVolumeInstanceProfilesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPNGatewayConnectionsLocalCIDRsOptions, "listVPNGatewayConnectionsLocalCIDRsOptions") + err = core.ValidateStruct(listVolumeInstanceProfilesOptions, "listVolumeInstanceProfilesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *listVPNGatewayConnectionsLocalCIDRsOptions.VPNGatewayID, - "id": *listVPNGatewayConnectionsLocalCIDRsOptions.ID, + "id": *listVolumeInstanceProfilesOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/local/cidrs`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/volumes/{id}/instance_profiles`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPNGatewayConnectionsLocalCIDRsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVolumeInstanceProfiles") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNGatewayConnectionsLocalCIDRs") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVolumeInstanceProfilesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listVolumeInstanceProfilesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVolumeInstanceProfilesOptions.Start)) + } + if listVolumeInstanceProfilesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVolumeInstanceProfilesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -27366,12 +28757,12 @@ func (vpc *VpcV1) ListVPNGatewayConnectionsLocalCIDRsWithContext(ctx context.Con var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpn_gateway_connections_local_cidrs", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_volume_instance_profiles", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnectionCIDRs) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVolumeInstanceProfileCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -27382,55 +28773,57 @@ func (vpc *VpcV1) ListVPNGatewayConnectionsLocalCIDRsWithContext(ctx context.Con return } -// RemoveVPNGatewayConnectionsLocalCIDR : Remove a local CIDR from a VPN gateway connection -// This request removes a CIDR from a VPN gateway connection. -// -// This request is only supported for policy mode VPN gateways. -func (vpc *VpcV1) RemoveVPNGatewayConnectionsLocalCIDR(removeVPNGatewayConnectionsLocalCIDROptions *RemoveVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RemoveVPNGatewayConnectionsLocalCIDRWithContext(context.Background(), removeVPNGatewayConnectionsLocalCIDROptions) +// ListVpcs : List VPCs +// This request lists VPCs in the region. A VPC is a virtual network that belongs to an account and provides logical +// isolation from other networks. A VPC is made up of resources in one or more zones. VPCs are regional, and each VPC +// can contain resources in multiple zones in a region. +func (vpc *VpcV1) ListVpcs(listVpcsOptions *ListVpcsOptions) (result *VPCCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVpcsWithContext(context.Background(), listVpcsOptions) err = core.RepurposeSDKProblem(err, "") return } -// RemoveVPNGatewayConnectionsLocalCIDRWithContext is an alternate form of the RemoveVPNGatewayConnectionsLocalCIDR method which supports a Context parameter -func (vpc *VpcV1) RemoveVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Context, removeVPNGatewayConnectionsLocalCIDROptions *RemoveVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(removeVPNGatewayConnectionsLocalCIDROptions, "removeVPNGatewayConnectionsLocalCIDROptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(removeVPNGatewayConnectionsLocalCIDROptions, "removeVPNGatewayConnectionsLocalCIDROptions") +// ListVpcsWithContext is an alternate form of the ListVpcs method which supports a Context parameter +func (vpc *VpcV1) ListVpcsWithContext(ctx context.Context, listVpcsOptions *ListVpcsOptions) (result *VPCCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listVpcsOptions, "listVpcsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "vpn_gateway_id": *removeVPNGatewayConnectionsLocalCIDROptions.VPNGatewayID, - "id": *removeVPNGatewayConnectionsLocalCIDROptions.ID, - "cidr": *removeVPNGatewayConnectionsLocalCIDROptions.CIDR, - } - - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/local/cidrs/{cidr}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range removeVPNGatewayConnectionsLocalCIDROptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVpcs") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveVPNGatewayConnectionsLocalCIDR") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVpcsOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listVpcsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVpcsOptions.Start)) + } + if listVpcsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVpcsOptions.Limit)) + } + if listVpcsOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listVpcsOptions.ResourceGroupID)) + } + if listVpcsOptions.ClassicAccess != nil { + builder.AddQuery("classic_access", fmt.Sprint(*listVpcsOptions.ClassicAccess)) + } request, err := builder.Build() if err != nil { @@ -27438,129 +28831,177 @@ func (vpc *VpcV1) RemoveVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Co return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "remove_vpn_gateway_connections_local_cidr", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpcs", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPCCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// CheckVPNGatewayConnectionsLocalCIDR : Check if the specified local CIDR exists on a VPN gateway connection -// This request succeeds if a CIDR exists on the specified VPN gateway connection, and fails otherwise. +// CreateVPC : Create a VPC +// This request creates a new VPC from a VPC prototype object. The prototype object is structured in the same way as a +// retrieved VPC, and contains the information necessary to create the new VPC. // -// This request is only supported for policy mode VPN gateways. -func (vpc *VpcV1) CheckVPNGatewayConnectionsLocalCIDR(checkVPNGatewayConnectionsLocalCIDROptions *CheckVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { - response, err = vpc.CheckVPNGatewayConnectionsLocalCIDRWithContext(context.Background(), checkVPNGatewayConnectionsLocalCIDROptions) +// The system will automatically create the following additional resources for the VPC: +// - Unless `address_prefix_management` is `manual`, a [default address +// prefix](https://cloud.ibm.com/apidocs/vpc/latest#get-vpc-address-prefix) for each zone +// - A [default network +// ACL](https://cloud.ibm.com/apidocs/vpc/latest#get-vpc-default-network-acl) +// - A [default routing +// table](https://cloud.ibm.com/apidocs/vpc/latest#get-vpc-default-routing-table) +// - A [default security +// group](https://cloud.ibm.com/apidocs/vpc/latest#get-vpc-default-security-group). +func (vpc *VpcV1) CreateVPC(createVPCOptions *CreateVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPCWithContext(context.Background(), createVPCOptions) err = core.RepurposeSDKProblem(err, "") return } -// CheckVPNGatewayConnectionsLocalCIDRWithContext is an alternate form of the CheckVPNGatewayConnectionsLocalCIDR method which supports a Context parameter -func (vpc *VpcV1) CheckVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Context, checkVPNGatewayConnectionsLocalCIDROptions *CheckVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(checkVPNGatewayConnectionsLocalCIDROptions, "checkVPNGatewayConnectionsLocalCIDROptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(checkVPNGatewayConnectionsLocalCIDROptions, "checkVPNGatewayConnectionsLocalCIDROptions") +// CreateVPCWithContext is an alternate form of the CreateVPC method which supports a Context parameter +func (vpc *VpcV1) CreateVPCWithContext(ctx context.Context, createVPCOptions *CreateVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(createVPCOptions, "createVPCOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "vpn_gateway_id": *checkVPNGatewayConnectionsLocalCIDROptions.VPNGatewayID, - "id": *checkVPNGatewayConnectionsLocalCIDROptions.ID, - "cidr": *checkVPNGatewayConnectionsLocalCIDROptions.CIDR, - } - - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/local/cidrs/{cidr}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range checkVPNGatewayConnectionsLocalCIDROptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPC") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CheckVPNGatewayConnectionsLocalCIDR") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPCOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createVPCOptions.AddressPrefixManagement != nil { + body["address_prefix_management"] = createVPCOptions.AddressPrefixManagement + } + if createVPCOptions.ClassicAccess != nil { + body["classic_access"] = createVPCOptions.ClassicAccess + } + if createVPCOptions.Dns != nil { + body["dns"] = createVPCOptions.Dns + } + if createVPCOptions.Name != nil { + body["name"] = createVPCOptions.Name + } + if createVPCOptions.ResourceGroup != nil { + body["resource_group"] = createVPCOptions.ResourceGroup + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "check_vpn_gateway_connections_local_cidr", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpc", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPC) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// AddVPNGatewayConnectionsLocalCIDR : Set a local CIDR on a VPN gateway connection -// This request adds the specified CIDR to the specified VPN gateway connection. This request succeeds if the specified -// CIDR already exists. A request body is not required, and if provided, is ignored. +// DeleteVPC : Delete a VPC +// This request deletes a VPC. This operation cannot be reversed. // -// This request is only supported for policy mode VPN gateways. -func (vpc *VpcV1) AddVPNGatewayConnectionsLocalCIDR(addVPNGatewayConnectionsLocalCIDROptions *AddVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { - response, err = vpc.AddVPNGatewayConnectionsLocalCIDRWithContext(context.Background(), addVPNGatewayConnectionsLocalCIDROptions) +// For this request to succeed: +// - Instances, subnets, public gateways, endpoint gateways, and private path service +// gateways must not reside in this VPC +// - The VPC must not be providing DNS resolution for any other VPCs +// - If `dns.enable_hub` is `true`, `dns.resolution_binding_count` must be zero +// +// All security groups and network ACLs associated with the VPC are automatically deleted. All flow log collectors with +// `auto_delete` set to `true` targeting the VPC or any resource in the VPC are automatically deleted. All public +// address ranges attached to the VPC are automatically detached. +func (vpc *VpcV1) DeleteVPC(deleteVPCOptions *DeleteVPCOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPCWithContext(context.Background(), deleteVPCOptions) err = core.RepurposeSDKProblem(err, "") return } -// AddVPNGatewayConnectionsLocalCIDRWithContext is an alternate form of the AddVPNGatewayConnectionsLocalCIDR method which supports a Context parameter -func (vpc *VpcV1) AddVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Context, addVPNGatewayConnectionsLocalCIDROptions *AddVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(addVPNGatewayConnectionsLocalCIDROptions, "addVPNGatewayConnectionsLocalCIDROptions cannot be nil") +// DeleteVPCWithContext is an alternate form of the DeleteVPC method which supports a Context parameter +func (vpc *VpcV1) DeleteVPCWithContext(ctx context.Context, deleteVPCOptions *DeleteVPCOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPCOptions, "deleteVPCOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(addVPNGatewayConnectionsLocalCIDROptions, "addVPNGatewayConnectionsLocalCIDROptions") + err = core.ValidateStruct(deleteVPCOptions, "deleteVPCOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *addVPNGatewayConnectionsLocalCIDROptions.VPNGatewayID, - "id": *addVPNGatewayConnectionsLocalCIDROptions.ID, - "cidr": *addVPNGatewayConnectionsLocalCIDROptions.CIDR, + "id": *deleteVPCOptions.ID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/local/cidrs/{cidr}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range addVPNGatewayConnectionsLocalCIDROptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPC") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddVPNGatewayConnectionsLocalCIDR") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPCOptions.Headers { builder.AddHeader(headerName, headerValue) } + if deleteVPCOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteVPCOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -27573,7 +29014,7 @@ func (vpc *VpcV1) AddVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Conte response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "add_vpn_gateway_connections_local_cidr", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpc", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -27581,49 +29022,46 @@ func (vpc *VpcV1) AddVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Conte return } -// ListVPNGatewayConnectionsPeerCIDRs : List peer CIDRs for a VPN gateway connection -// This request lists peer CIDRs for a VPN gateway connection. -// -// This request is only supported for policy mode VPN gateways. -func (vpc *VpcV1) ListVPNGatewayConnectionsPeerCIDRs(listVPNGatewayConnectionsPeerCIDRsOptions *ListVPNGatewayConnectionsPeerCIDRsOptions) (result *VPNGatewayConnectionCIDRs, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPNGatewayConnectionsPeerCIDRsWithContext(context.Background(), listVPNGatewayConnectionsPeerCIDRsOptions) +// GetVPC : Retrieve a VPC +// This request retrieves a single VPC specified by the identifier in the URL. +func (vpc *VpcV1) GetVPC(getVPCOptions *GetVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCWithContext(context.Background(), getVPCOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPNGatewayConnectionsPeerCIDRsWithContext is an alternate form of the ListVPNGatewayConnectionsPeerCIDRs method which supports a Context parameter -func (vpc *VpcV1) ListVPNGatewayConnectionsPeerCIDRsWithContext(ctx context.Context, listVPNGatewayConnectionsPeerCIDRsOptions *ListVPNGatewayConnectionsPeerCIDRsOptions) (result *VPNGatewayConnectionCIDRs, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPNGatewayConnectionsPeerCIDRsOptions, "listVPNGatewayConnectionsPeerCIDRsOptions cannot be nil") +// GetVPCWithContext is an alternate form of the GetVPC method which supports a Context parameter +func (vpc *VpcV1) GetVPCWithContext(ctx context.Context, getVPCOptions *GetVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPCOptions, "getVPCOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPNGatewayConnectionsPeerCIDRsOptions, "listVPNGatewayConnectionsPeerCIDRsOptions") + err = core.ValidateStruct(getVPCOptions, "getVPCOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *listVPNGatewayConnectionsPeerCIDRsOptions.VPNGatewayID, - "id": *listVPNGatewayConnectionsPeerCIDRsOptions.ID, + "id": *getVPCOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/peer/cidrs`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPNGatewayConnectionsPeerCIDRsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPC") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNGatewayConnectionsPeerCIDRs") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -27640,12 +29078,12 @@ func (vpc *VpcV1) ListVPNGatewayConnectionsPeerCIDRsWithContext(ctx context.Cont var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpn_gateway_connections_peer_cidrs", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnectionCIDRs) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPC) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -27656,118 +29094,133 @@ func (vpc *VpcV1) ListVPNGatewayConnectionsPeerCIDRsWithContext(ctx context.Cont return } -// RemoveVPNGatewayConnectionsPeerCIDR : Remove a peer CIDR from a VPN gateway connection -// This request removes a CIDR from a VPN gateway connection. -// -// This request is only supported for policy mode VPN gateways. -func (vpc *VpcV1) RemoveVPNGatewayConnectionsPeerCIDR(removeVPNGatewayConnectionsPeerCIDROptions *RemoveVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RemoveVPNGatewayConnectionsPeerCIDRWithContext(context.Background(), removeVPNGatewayConnectionsPeerCIDROptions) +// UpdateVPC : Update a VPC +// This request updates a VPC with the information provided in a VPC patch object. The patch object is structured in the +// same way as a retrieved VPC and needs to contain only the information to be updated. +func (vpc *VpcV1) UpdateVPC(updateVPCOptions *UpdateVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPCWithContext(context.Background(), updateVPCOptions) err = core.RepurposeSDKProblem(err, "") return } -// RemoveVPNGatewayConnectionsPeerCIDRWithContext is an alternate form of the RemoveVPNGatewayConnectionsPeerCIDR method which supports a Context parameter -func (vpc *VpcV1) RemoveVPNGatewayConnectionsPeerCIDRWithContext(ctx context.Context, removeVPNGatewayConnectionsPeerCIDROptions *RemoveVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(removeVPNGatewayConnectionsPeerCIDROptions, "removeVPNGatewayConnectionsPeerCIDROptions cannot be nil") +// UpdateVPCWithContext is an alternate form of the UpdateVPC method which supports a Context parameter +func (vpc *VpcV1) UpdateVPCWithContext(ctx context.Context, updateVPCOptions *UpdateVPCOptions) (result *VPC, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPCOptions, "updateVPCOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(removeVPNGatewayConnectionsPeerCIDROptions, "removeVPNGatewayConnectionsPeerCIDROptions") + err = core.ValidateStruct(updateVPCOptions, "updateVPCOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *removeVPNGatewayConnectionsPeerCIDROptions.VPNGatewayID, - "id": *removeVPNGatewayConnectionsPeerCIDROptions.ID, - "cidr": *removeVPNGatewayConnectionsPeerCIDROptions.CIDR, + "id": *updateVPCOptions.ID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/peer/cidrs/{cidr}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range removeVPNGatewayConnectionsPeerCIDROptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPC") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveVPNGatewayConnectionsPeerCIDR") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPCOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateVPCOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateVPCOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateVPCOptions.VPCPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "remove_vpn_gateway_connections_peer_cidr", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpc", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPC) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// CheckVPNGatewayConnectionsPeerCIDR : Check if the specified peer CIDR exists on a VPN gateway connection -// This request succeeds if a CIDR exists on the specified VPN gateway connection, and fails otherwise. -// -// This request is only supported for policy mode VPN gateways. -func (vpc *VpcV1) CheckVPNGatewayConnectionsPeerCIDR(checkVPNGatewayConnectionsPeerCIDROptions *CheckVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { - response, err = vpc.CheckVPNGatewayConnectionsPeerCIDRWithContext(context.Background(), checkVPNGatewayConnectionsPeerCIDROptions) +// GetVPCDefaultNetworkACL : Retrieve a VPC's default network ACL +// This request retrieves the default network ACL for the VPC specified by the identifier in the URL. The default +// network ACL is applied to any new subnets in the VPC which do not specify a network ACL. +func (vpc *VpcV1) GetVPCDefaultNetworkACL(getVPCDefaultNetworkACLOptions *GetVPCDefaultNetworkACLOptions) (result *DefaultNetworkACL, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCDefaultNetworkACLWithContext(context.Background(), getVPCDefaultNetworkACLOptions) err = core.RepurposeSDKProblem(err, "") return } -// CheckVPNGatewayConnectionsPeerCIDRWithContext is an alternate form of the CheckVPNGatewayConnectionsPeerCIDR method which supports a Context parameter -func (vpc *VpcV1) CheckVPNGatewayConnectionsPeerCIDRWithContext(ctx context.Context, checkVPNGatewayConnectionsPeerCIDROptions *CheckVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(checkVPNGatewayConnectionsPeerCIDROptions, "checkVPNGatewayConnectionsPeerCIDROptions cannot be nil") +// GetVPCDefaultNetworkACLWithContext is an alternate form of the GetVPCDefaultNetworkACL method which supports a Context parameter +func (vpc *VpcV1) GetVPCDefaultNetworkACLWithContext(ctx context.Context, getVPCDefaultNetworkACLOptions *GetVPCDefaultNetworkACLOptions) (result *DefaultNetworkACL, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPCDefaultNetworkACLOptions, "getVPCDefaultNetworkACLOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(checkVPNGatewayConnectionsPeerCIDROptions, "checkVPNGatewayConnectionsPeerCIDROptions") + err = core.ValidateStruct(getVPCDefaultNetworkACLOptions, "getVPCDefaultNetworkACLOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *checkVPNGatewayConnectionsPeerCIDROptions.VPNGatewayID, - "id": *checkVPNGatewayConnectionsPeerCIDROptions.ID, - "cidr": *checkVPNGatewayConnectionsPeerCIDROptions.CIDR, + "id": *getVPCDefaultNetworkACLOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/peer/cidrs/{cidr}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}/default_network_acl`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range checkVPNGatewayConnectionsPeerCIDROptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCDefaultNetworkACL") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CheckVPNGatewayConnectionsPeerCIDR") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCDefaultNetworkACLOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -27778,63 +29231,70 @@ func (vpc *VpcV1) CheckVPNGatewayConnectionsPeerCIDRWithContext(ctx context.Cont return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "check_vpn_gateway_connections_peer_cidr", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc_default_network_acl", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDefaultNetworkACL) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// AddVPNGatewayConnectionsPeerCIDR : Set a peer CIDR on a VPN gateway connection -// This request adds the specified CIDR to the specified VPN gateway connection. This request succeeds if the specified -// CIDR already exists. A request body is not required, and if provided, is ignored. -// -// This request is only supported for policy mode VPN gateways. -func (vpc *VpcV1) AddVPNGatewayConnectionsPeerCIDR(addVPNGatewayConnectionsPeerCIDROptions *AddVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { - response, err = vpc.AddVPNGatewayConnectionsPeerCIDRWithContext(context.Background(), addVPNGatewayConnectionsPeerCIDROptions) +// GetVPCDefaultRoutingTable : Retrieve a VPC's default routing table +// This request retrieves the default routing table for the VPC specified by the identifier in the URL. The default +// routing table is associated with any subnets in the VPC which have not been explicitly associated with another +// routing table. +func (vpc *VpcV1) GetVPCDefaultRoutingTable(getVPCDefaultRoutingTableOptions *GetVPCDefaultRoutingTableOptions) (result *DefaultRoutingTable, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCDefaultRoutingTableWithContext(context.Background(), getVPCDefaultRoutingTableOptions) err = core.RepurposeSDKProblem(err, "") return } -// AddVPNGatewayConnectionsPeerCIDRWithContext is an alternate form of the AddVPNGatewayConnectionsPeerCIDR method which supports a Context parameter -func (vpc *VpcV1) AddVPNGatewayConnectionsPeerCIDRWithContext(ctx context.Context, addVPNGatewayConnectionsPeerCIDROptions *AddVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(addVPNGatewayConnectionsPeerCIDROptions, "addVPNGatewayConnectionsPeerCIDROptions cannot be nil") +// GetVPCDefaultRoutingTableWithContext is an alternate form of the GetVPCDefaultRoutingTable method which supports a Context parameter +func (vpc *VpcV1) GetVPCDefaultRoutingTableWithContext(ctx context.Context, getVPCDefaultRoutingTableOptions *GetVPCDefaultRoutingTableOptions) (result *DefaultRoutingTable, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPCDefaultRoutingTableOptions, "getVPCDefaultRoutingTableOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(addVPNGatewayConnectionsPeerCIDROptions, "addVPNGatewayConnectionsPeerCIDROptions") + err = core.ValidateStruct(getVPCDefaultRoutingTableOptions, "getVPCDefaultRoutingTableOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_gateway_id": *addVPNGatewayConnectionsPeerCIDROptions.VPNGatewayID, - "id": *addVPNGatewayConnectionsPeerCIDROptions.ID, - "cidr": *addVPNGatewayConnectionsPeerCIDROptions.CIDR, + "id": *getVPCDefaultRoutingTableOptions.ID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/peer/cidrs/{cidr}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}/default_routing_table`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range addVPNGatewayConnectionsPeerCIDROptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCDefaultRoutingTable") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddVPNGatewayConnectionsPeerCIDR") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCDefaultRoutingTableOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -27845,68 +29305,72 @@ func (vpc *VpcV1) AddVPNGatewayConnectionsPeerCIDRWithContext(ctx context.Contex return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "add_vpn_gateway_connections_peer_cidr", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc_default_routing_table", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDefaultRoutingTable) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListVPNServers : List VPN servers -// This request lists VPN servers. -func (vpc *VpcV1) ListVPNServers(listVPNServersOptions *ListVPNServersOptions) (result *VPNServerCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPNServersWithContext(context.Background(), listVPNServersOptions) +// GetVPCDefaultSecurityGroup : Retrieve a VPC's default security group +// This request retrieves the default security group for the VPC specified by the identifier in the URL. Resources +// created in this VPC that allow a security group to be optionally specified will use this security group by default. +func (vpc *VpcV1) GetVPCDefaultSecurityGroup(getVPCDefaultSecurityGroupOptions *GetVPCDefaultSecurityGroupOptions) (result *DefaultSecurityGroup, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCDefaultSecurityGroupWithContext(context.Background(), getVPCDefaultSecurityGroupOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPNServersWithContext is an alternate form of the ListVPNServers method which supports a Context parameter -func (vpc *VpcV1) ListVPNServersWithContext(ctx context.Context, listVPNServersOptions *ListVPNServersOptions) (result *VPNServerCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listVPNServersOptions, "listVPNServersOptions") +// GetVPCDefaultSecurityGroupWithContext is an alternate form of the GetVPCDefaultSecurityGroup method which supports a Context parameter +func (vpc *VpcV1) GetVPCDefaultSecurityGroupWithContext(ctx context.Context, getVPCDefaultSecurityGroupOptions *GetVPCDefaultSecurityGroupOptions) (result *DefaultSecurityGroup, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPCDefaultSecurityGroupOptions, "getVPCDefaultSecurityGroupOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getVPCDefaultSecurityGroupOptions, "getVPCDefaultSecurityGroupOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "id": *getVPCDefaultSecurityGroupOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{id}/default_security_group`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPNServersOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCDefaultSecurityGroup") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNServers") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCDefaultSecurityGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPNServersOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listVPNServersOptions.Name)) - } - if listVPNServersOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPNServersOptions.Start)) - } - if listVPNServersOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPNServersOptions.Limit)) - } - if listVPNServersOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listVPNServersOptions.ResourceGroupID)) - } - if listVPNServersOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listVPNServersOptions.Sort)) - } request, err := builder.Build() if err != nil { @@ -27917,12 +29381,12 @@ func (vpc *VpcV1) ListVPNServersWithContext(ctx context.Context, listVPNServersO var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpn_servers", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc_default_security_group", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDefaultSecurityGroup) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -27933,91 +29397,57 @@ func (vpc *VpcV1) ListVPNServersWithContext(ctx context.Context, listVPNServersO return } -// CreateVPNServer : Create a VPN server -// This request creates a new VPN server. -func (vpc *VpcV1) CreateVPNServer(createVPNServerOptions *CreateVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPNServerWithContext(context.Background(), createVPNServerOptions) +// ListVPCAddressPrefixes : List address prefixes for a VPC +// This request lists address pool prefixes for a VPC. +func (vpc *VpcV1) ListVPCAddressPrefixes(listVPCAddressPrefixesOptions *ListVPCAddressPrefixesOptions) (result *AddressPrefixCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPCAddressPrefixesWithContext(context.Background(), listVPCAddressPrefixesOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPNServerWithContext is an alternate form of the CreateVPNServer method which supports a Context parameter -func (vpc *VpcV1) CreateVPNServerWithContext(ctx context.Context, createVPNServerOptions *CreateVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVPNServerOptions, "createVPNServerOptions cannot be nil") +// ListVPCAddressPrefixesWithContext is an alternate form of the ListVPCAddressPrefixes method which supports a Context parameter +func (vpc *VpcV1) ListVPCAddressPrefixesWithContext(ctx context.Context, listVPCAddressPrefixesOptions *ListVPCAddressPrefixesOptions) (result *AddressPrefixCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPCAddressPrefixesOptions, "listVPCAddressPrefixesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVPNServerOptions, "createVPNServerOptions") + err = core.ValidateStruct(listVPCAddressPrefixesOptions, "listVPCAddressPrefixesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "vpc_id": *listVPCAddressPrefixesOptions.VPCID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPNServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCAddressPrefixes") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPNServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPCAddressPrefixesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if createVPNServerOptions.Certificate != nil { - body["certificate"] = createVPNServerOptions.Certificate - } - if createVPNServerOptions.ClientAuthentication != nil { - body["client_authentication"] = createVPNServerOptions.ClientAuthentication - } - if createVPNServerOptions.ClientIPPool != nil { - body["client_ip_pool"] = createVPNServerOptions.ClientIPPool - } - if createVPNServerOptions.Subnets != nil { - body["subnets"] = createVPNServerOptions.Subnets - } - if createVPNServerOptions.ClientDnsServerIps != nil { - body["client_dns_server_ips"] = createVPNServerOptions.ClientDnsServerIps - } - if createVPNServerOptions.ClientIdleTimeout != nil { - body["client_idle_timeout"] = createVPNServerOptions.ClientIdleTimeout - } - if createVPNServerOptions.EnableSplitTunneling != nil { - body["enable_split_tunneling"] = createVPNServerOptions.EnableSplitTunneling - } - if createVPNServerOptions.Name != nil { - body["name"] = createVPNServerOptions.Name - } - if createVPNServerOptions.Port != nil { - body["port"] = createVPNServerOptions.Port - } - if createVPNServerOptions.Protocol != nil { - body["protocol"] = createVPNServerOptions.Protocol - } - if createVPNServerOptions.ResourceGroup != nil { - body["resource_group"] = createVPNServerOptions.ResourceGroup - } - if createVPNServerOptions.SecurityGroups != nil { - body["security_groups"] = createVPNServerOptions.SecurityGroups + if listVPCAddressPrefixesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPCAddressPrefixesOptions.Start)) } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listVPCAddressPrefixesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPCAddressPrefixesOptions.Limit)) } request, err := builder.Build() @@ -28029,12 +29459,12 @@ func (vpc *VpcV1) CreateVPNServerWithContext(ctx context.Context, createVPNServe var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpn_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpc_address_prefixes", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServer) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddressPrefixCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -28045,114 +29475,143 @@ func (vpc *VpcV1) CreateVPNServerWithContext(ctx context.Context, createVPNServe return } -// DeleteVPNServer : Delete a VPN server -// This request deletes a VPN server. This operation cannot be reversed. -func (vpc *VpcV1) DeleteVPNServer(deleteVPNServerOptions *DeleteVPNServerOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPNServerWithContext(context.Background(), deleteVPNServerOptions) +// CreateVPCAddressPrefix : Create an address prefix for a VPC +// This request creates a new prefix from a prefix prototype object. The prototype object is structured in the same way +// as a retrieved prefix, and contains the information necessary to create the new prefix. +func (vpc *VpcV1) CreateVPCAddressPrefix(createVPCAddressPrefixOptions *CreateVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPCAddressPrefixWithContext(context.Background(), createVPCAddressPrefixOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPNServerWithContext is an alternate form of the DeleteVPNServer method which supports a Context parameter -func (vpc *VpcV1) DeleteVPNServerWithContext(ctx context.Context, deleteVPNServerOptions *DeleteVPNServerOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPNServerOptions, "deleteVPNServerOptions cannot be nil") +// CreateVPCAddressPrefixWithContext is an alternate form of the CreateVPCAddressPrefix method which supports a Context parameter +func (vpc *VpcV1) CreateVPCAddressPrefixWithContext(ctx context.Context, createVPCAddressPrefixOptions *CreateVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVPCAddressPrefixOptions, "createVPCAddressPrefixOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPNServerOptions, "deleteVPNServerOptions") + err = core.ValidateStruct(createVPCAddressPrefixOptions, "createVPCAddressPrefixOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteVPNServerOptions.ID, + "vpc_id": *createVPCAddressPrefixOptions.VPCID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPNServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCAddressPrefix") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPCAddressPrefixOptions.Headers { builder.AddHeader(headerName, headerValue) } - if deleteVPNServerOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteVPNServerOptions.IfMatch)) - } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - request, err := builder.Build() + body := make(map[string]interface{}) + if createVPCAddressPrefixOptions.CIDR != nil { + body["cidr"] = createVPCAddressPrefixOptions.CIDR + } + if createVPCAddressPrefixOptions.Zone != nil { + body["zone"] = createVPCAddressPrefixOptions.Zone + } + if createVPCAddressPrefixOptions.IsDefault != nil { + body["is_default"] = createVPCAddressPrefixOptions.IsDefault + } + if createVPCAddressPrefixOptions.Name != nil { + body["name"] = createVPCAddressPrefixOptions.Name + } + _, err = builder.SetBodyContentJSON(body) if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + request, err := builder.Build() if err != nil { - core.EnrichHTTPProblem(err, "delete_vpn_server", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - return + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "create_vpc_address_prefix", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddressPrefix) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return } -// GetVPNServer : Retrieve a VPN server -// This request retrieves a single VPN server specified by the identifier in the URL. -func (vpc *VpcV1) GetVPNServer(getVPNServerOptions *GetVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPNServerWithContext(context.Background(), getVPNServerOptions) +// DeleteVPCAddressPrefix : Delete an address prefix +// This request deletes a prefix. This operation cannot be reversed. The request will fail if any subnets use addresses +// from this prefix. +func (vpc *VpcV1) DeleteVPCAddressPrefix(deleteVPCAddressPrefixOptions *DeleteVPCAddressPrefixOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPCAddressPrefixWithContext(context.Background(), deleteVPCAddressPrefixOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPNServerWithContext is an alternate form of the GetVPNServer method which supports a Context parameter -func (vpc *VpcV1) GetVPNServerWithContext(ctx context.Context, getVPNServerOptions *GetVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPNServerOptions, "getVPNServerOptions cannot be nil") +// DeleteVPCAddressPrefixWithContext is an alternate form of the DeleteVPCAddressPrefix method which supports a Context parameter +func (vpc *VpcV1) DeleteVPCAddressPrefixWithContext(ctx context.Context, deleteVPCAddressPrefixOptions *DeleteVPCAddressPrefixOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPCAddressPrefixOptions, "deleteVPCAddressPrefixOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPNServerOptions, "getVPNServerOptions") + err = core.ValidateStruct(deleteVPCAddressPrefixOptions, "deleteVPCAddressPrefixOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getVPNServerOptions.ID, + "vpc_id": *deleteVPCAddressPrefixOptions.VPCID, + "id": *deleteVPCAddressPrefixOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPNServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCAddressPrefix") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPCAddressPrefixOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -28163,83 +29622,64 @@ func (vpc *VpcV1) GetVPNServerWithContext(ctx context.Context, getVPNServerOptio return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_vpn_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpc_address_prefix", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServer) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// UpdateVPNServer : Update a VPN server -// This request updates the properties of an existing VPN server. Any updates other than to `name` will cause all -// connected VPN clients to be disconnected. -func (vpc *VpcV1) UpdateVPNServer(updateVPNServerOptions *UpdateVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPNServerWithContext(context.Background(), updateVPNServerOptions) +// GetVPCAddressPrefix : Retrieve an address prefix +// This request retrieves a single prefix specified by the identifier in the URL. +func (vpc *VpcV1) GetVPCAddressPrefix(getVPCAddressPrefixOptions *GetVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCAddressPrefixWithContext(context.Background(), getVPCAddressPrefixOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPNServerWithContext is an alternate form of the UpdateVPNServer method which supports a Context parameter -func (vpc *VpcV1) UpdateVPNServerWithContext(ctx context.Context, updateVPNServerOptions *UpdateVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPNServerOptions, "updateVPNServerOptions cannot be nil") +// GetVPCAddressPrefixWithContext is an alternate form of the GetVPCAddressPrefix method which supports a Context parameter +func (vpc *VpcV1) GetVPCAddressPrefixWithContext(ctx context.Context, getVPCAddressPrefixOptions *GetVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPCAddressPrefixOptions, "getVPCAddressPrefixOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPNServerOptions, "updateVPNServerOptions") + err = core.ValidateStruct(getVPCAddressPrefixOptions, "getVPCAddressPrefixOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateVPNServerOptions.ID, + "vpc_id": *getVPCAddressPrefixOptions.VPCID, + "id": *getVPCAddressPrefixOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPNServerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCAddressPrefix") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPNServer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCAddressPrefixOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateVPNServerOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateVPNServerOptions.IfMatch)) - } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVPNServerOptions.VPNServerPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -28249,12 +29689,12 @@ func (vpc *VpcV1) UpdateVPNServerWithContext(ctx context.Context, updateVPNServe var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_vpn_server", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc_address_prefix", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServer) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddressPrefix) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -28265,125 +29705,168 @@ func (vpc *VpcV1) UpdateVPNServerWithContext(ctx context.Context, updateVPNServe return } -// GetVPNServerClientConfiguration : Retrieve client configuration -// This request retrieves OpenVPN client configuration on a single VPN server specified by the identifier in the URL. -// This configuration includes directives compatible with OpenVPN releases 2.4 and 2.5. -func (vpc *VpcV1) GetVPNServerClientConfiguration(getVPNServerClientConfigurationOptions *GetVPNServerClientConfigurationOptions) (result *string, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPNServerClientConfigurationWithContext(context.Background(), getVPNServerClientConfigurationOptions) +// UpdateVPCAddressPrefix : Update an address prefix +// This request updates a prefix with the information in a provided prefix patch. The prefix patch object is structured +// in the same way as a retrieved prefix and contains only the information to be updated. +func (vpc *VpcV1) UpdateVPCAddressPrefix(updateVPCAddressPrefixOptions *UpdateVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPCAddressPrefixWithContext(context.Background(), updateVPCAddressPrefixOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPNServerClientConfigurationWithContext is an alternate form of the GetVPNServerClientConfiguration method which supports a Context parameter -func (vpc *VpcV1) GetVPNServerClientConfigurationWithContext(ctx context.Context, getVPNServerClientConfigurationOptions *GetVPNServerClientConfigurationOptions) (result *string, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPNServerClientConfigurationOptions, "getVPNServerClientConfigurationOptions cannot be nil") +// UpdateVPCAddressPrefixWithContext is an alternate form of the UpdateVPCAddressPrefix method which supports a Context parameter +func (vpc *VpcV1) UpdateVPCAddressPrefixWithContext(ctx context.Context, updateVPCAddressPrefixOptions *UpdateVPCAddressPrefixOptions) (result *AddressPrefix, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPCAddressPrefixOptions, "updateVPCAddressPrefixOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPNServerClientConfigurationOptions, "getVPNServerClientConfigurationOptions") + err = core.ValidateStruct(updateVPCAddressPrefixOptions, "updateVPCAddressPrefixOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getVPNServerClientConfigurationOptions.ID, + "vpc_id": *updateVPCAddressPrefixOptions.VPCID, + "id": *updateVPCAddressPrefixOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{id}/client_configuration`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/address_prefixes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPNServerClientConfigurationOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCAddressPrefix") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNServerClientConfiguration") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPCAddressPrefixOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "text/plain") + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateVPCAddressPrefixOptions.AddressPrefixPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, &result) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpn_server_client_configuration", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpc_address_prefix", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddressPrefix) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListVPNServerClients : List VPN clients for a VPN server -// This request retrieves connected VPN clients, and any disconnected VPN clients that the VPN server has not yet -// deleted based on its auto-deletion policy. -func (vpc *VpcV1) ListVPNServerClients(listVPNServerClientsOptions *ListVPNServerClientsOptions) (result *VPNServerClientCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPNServerClientsWithContext(context.Background(), listVPNServerClientsOptions) +// ListVPCDnsResolutionBindings : List DNS resolution bindings for a VPC +// This request lists DNS resolution bindings for a VPC. A DNS resolution binding represents an association with another +// VPC for centralizing DNS name resolution. +// +// If the VPC specified by the identifier in the URL is a DNS hub VPC (has `dns.enable_hub` set to `true`) then there is +// one binding for each VPC bound to the hub VPC. The endpoint gateways in the bound VPCs can allow (using +// `allow_dns_resolution_binding`) the hub VPC to centralize resolution of their DNS names. +// +// If the VPC specified by the identifier in the URL is not a DNS hub VPC, then there is at most one binding (to a hub +// VPC). The endpoint gateways in the VPC specified by the identifier in the URL can allow (using +// `allow_dns_resolution_binding`) its hub VPC to centralize resolution of their DNS names. +// +// To make use of centralized DNS resolution, a VPC bound to a DNS hub VPC must delegate DNS resolution to its hub VPC +// by setting `dns.resolver.type` to `delegate`. +// +// The bindings will be sorted by their `created_at` property values, with newest bindings first. Bindings with +// identical `created_at` property values will in turn be sorted by ascending `name` property values. +func (vpc *VpcV1) ListVPCDnsResolutionBindings(listVPCDnsResolutionBindingsOptions *ListVPCDnsResolutionBindingsOptions) (result *VpcdnsResolutionBindingCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPCDnsResolutionBindingsWithContext(context.Background(), listVPCDnsResolutionBindingsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPNServerClientsWithContext is an alternate form of the ListVPNServerClients method which supports a Context parameter -func (vpc *VpcV1) ListVPNServerClientsWithContext(ctx context.Context, listVPNServerClientsOptions *ListVPNServerClientsOptions) (result *VPNServerClientCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPNServerClientsOptions, "listVPNServerClientsOptions cannot be nil") +// ListVPCDnsResolutionBindingsWithContext is an alternate form of the ListVPCDnsResolutionBindings method which supports a Context parameter +func (vpc *VpcV1) ListVPCDnsResolutionBindingsWithContext(ctx context.Context, listVPCDnsResolutionBindingsOptions *ListVPCDnsResolutionBindingsOptions) (result *VpcdnsResolutionBindingCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPCDnsResolutionBindingsOptions, "listVPCDnsResolutionBindingsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPNServerClientsOptions, "listVPNServerClientsOptions") + err = core.ValidateStruct(listVPCDnsResolutionBindingsOptions, "listVPCDnsResolutionBindingsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_server_id": *listVPNServerClientsOptions.VPNServerID, + "vpc_id": *listVPCDnsResolutionBindingsOptions.VPCID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/clients`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPNServerClientsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCDnsResolutionBindings") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNServerClients") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPCDnsResolutionBindingsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPNServerClientsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPNServerClientsOptions.Start)) + if listVPCDnsResolutionBindingsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.Sort)) } - if listVPNServerClientsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPNServerClientsOptions.Limit)) + if listVPCDnsResolutionBindingsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.Start)) } - if listVPNServerClientsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listVPNServerClientsOptions.Sort)) + if listVPCDnsResolutionBindingsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.Limit)) + } + if listVPCDnsResolutionBindingsOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.Name)) + } + if listVPCDnsResolutionBindingsOptions.VPCCRN != nil { + builder.AddQuery("vpc.crn", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.VPCCRN)) + } + if listVPCDnsResolutionBindingsOptions.VPCName != nil { + builder.AddQuery("vpc.name", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.VPCName)) + } + if listVPCDnsResolutionBindingsOptions.AccountID != nil { + builder.AddQuery("account.id", fmt.Sprint(*listVPCDnsResolutionBindingsOptions.AccountID)) } request, err := builder.Build() @@ -28395,12 +29878,12 @@ func (vpc *VpcV1) ListVPNServerClientsWithContext(ctx context.Context, listVPNSe var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpn_server_clients", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpc_dns_resolution_bindings", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerClientCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBindingCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -28411,112 +29894,148 @@ func (vpc *VpcV1) ListVPNServerClientsWithContext(ctx context.Context, listVPNSe return } -// DeleteVPNServerClient : Delete a VPN client -// This request disconnects and deletes the VPN client from the VPN server. The VPN client may reconnect unless its -// authentication permissions for the configured authentication methods (such as its client certificate) have been -// revoked. -func (vpc *VpcV1) DeleteVPNServerClient(deleteVPNServerClientOptions *DeleteVPNServerClientOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPNServerClientWithContext(context.Background(), deleteVPNServerClientOptions) +// CreateVPCDnsResolutionBinding : Create a DNS resolution binding +// This request creates a new DNS resolution binding from a DNS resolution binding prototype object. The prototype +// object is structured in the same way as a retrieved DNS resolution binding, and contains the information necessary to +// create the new DNS resolution binding. +// +// For this request to succeed: +// - The VPC specified by the identifier in the URL must not already have a DNS resolution +// binding +// - The VPC specified by the identifier in the URL must have `dns.enable_hub` set to +// `false` +// - The updated DNS sharing connected topology must not contain more than one endpoint +// gateway with `allow_dns_resolution_binding` set to `true` targeting the same service. +// +// See [About DNS sharing for VPE gateways](/docs/vpc?topic=vpc-vpe-dns-sharing) for more information. +func (vpc *VpcV1) CreateVPCDnsResolutionBinding(createVPCDnsResolutionBindingOptions *CreateVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPCDnsResolutionBindingWithContext(context.Background(), createVPCDnsResolutionBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPNServerClientWithContext is an alternate form of the DeleteVPNServerClient method which supports a Context parameter -func (vpc *VpcV1) DeleteVPNServerClientWithContext(ctx context.Context, deleteVPNServerClientOptions *DeleteVPNServerClientOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPNServerClientOptions, "deleteVPNServerClientOptions cannot be nil") +// CreateVPCDnsResolutionBindingWithContext is an alternate form of the CreateVPCDnsResolutionBinding method which supports a Context parameter +func (vpc *VpcV1) CreateVPCDnsResolutionBindingWithContext(ctx context.Context, createVPCDnsResolutionBindingOptions *CreateVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVPCDnsResolutionBindingOptions, "createVPCDnsResolutionBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPNServerClientOptions, "deleteVPNServerClientOptions") + err = core.ValidateStruct(createVPCDnsResolutionBindingOptions, "createVPCDnsResolutionBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_server_id": *deleteVPNServerClientOptions.VPNServerID, - "id": *deleteVPNServerClientOptions.ID, + "vpc_id": *createVPCDnsResolutionBindingOptions.VPCID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/clients/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPNServerClientOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCDnsResolutionBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNServerClient") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPCDnsResolutionBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + body := make(map[string]interface{}) + if createVPCDnsResolutionBindingOptions.VPC != nil { + body["vpc"] = createVPCDnsResolutionBindingOptions.VPC + } + if createVPCDnsResolutionBindingOptions.Name != nil { + body["name"] = createVPCDnsResolutionBindingOptions.Name + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "delete_vpn_server_client", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpc_dns_resolution_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBinding) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// GetVPNServerClient : Retrieve a VPN client -// This request retrieves a single VPN client specified by the identifier in the URL. -func (vpc *VpcV1) GetVPNServerClient(getVPNServerClientOptions *GetVPNServerClientOptions) (result *VPNServerClient, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPNServerClientWithContext(context.Background(), getVPNServerClientOptions) +// DeleteVPCDnsResolutionBinding : Delete a DNS resolution binding +// This request deletes a DNS resolution binding. This operation cannot be reversed. +// +// For this request to succeed, the VPC specified by the identifier in the URL must not have +// `dns.resolver.type` set to `delegated`. +func (vpc *VpcV1) DeleteVPCDnsResolutionBinding(deleteVPCDnsResolutionBindingOptions *DeleteVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { + result, response, err = vpc.DeleteVPCDnsResolutionBindingWithContext(context.Background(), deleteVPCDnsResolutionBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetVPNServerClientWithContext is an alternate form of the GetVPNServerClient method which supports a Context parameter -func (vpc *VpcV1) GetVPNServerClientWithContext(ctx context.Context, getVPNServerClientOptions *GetVPNServerClientOptions) (result *VPNServerClient, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPNServerClientOptions, "getVPNServerClientOptions cannot be nil") +// DeleteVPCDnsResolutionBindingWithContext is an alternate form of the DeleteVPCDnsResolutionBinding method which supports a Context parameter +func (vpc *VpcV1) DeleteVPCDnsResolutionBindingWithContext(ctx context.Context, deleteVPCDnsResolutionBindingOptions *DeleteVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPCDnsResolutionBindingOptions, "deleteVPCDnsResolutionBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getVPNServerClientOptions, "getVPNServerClientOptions") + err = core.ValidateStruct(deleteVPCDnsResolutionBindingOptions, "deleteVPCDnsResolutionBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_server_id": *getVPNServerClientOptions.VPNServerID, - "id": *getVPNServerClientOptions.ID, + "vpc_id": *deleteVPCDnsResolutionBindingOptions.VPCID, + "id": *deleteVPCDnsResolutionBindingOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/clients/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getVPNServerClientOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCDnsResolutionBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNServerClient") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPCDnsResolutionBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -28533,12 +30052,12 @@ func (vpc *VpcV1) GetVPNServerClientWithContext(ctx context.Context, getVPNServe var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpn_server_client", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpc_dns_resolution_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerClient) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBinding) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -28549,51 +30068,50 @@ func (vpc *VpcV1) GetVPNServerClientWithContext(ctx context.Context, getVPNServe return } -// DisconnectVPNClient : Disconnect a VPN client -// This request disconnects the specified VPN client, and deletes the client according to the VPN server's auto-deletion -// policy. The VPN client may reconnect unless its authentication permissions for the configured authentication methods -// (such as its client certificate) have been revoked. -func (vpc *VpcV1) DisconnectVPNClient(disconnectVPNClientOptions *DisconnectVPNClientOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DisconnectVPNClientWithContext(context.Background(), disconnectVPNClientOptions) +// GetVPCDnsResolutionBinding : Retrieve a DNS resolution binding +// This request retrieves a single DNS resolution binding specified by the identifier in the URL. +func (vpc *VpcV1) GetVPCDnsResolutionBinding(getVPCDnsResolutionBindingOptions *GetVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCDnsResolutionBindingWithContext(context.Background(), getVPCDnsResolutionBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// DisconnectVPNClientWithContext is an alternate form of the DisconnectVPNClient method which supports a Context parameter -func (vpc *VpcV1) DisconnectVPNClientWithContext(ctx context.Context, disconnectVPNClientOptions *DisconnectVPNClientOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(disconnectVPNClientOptions, "disconnectVPNClientOptions cannot be nil") +// GetVPCDnsResolutionBindingWithContext is an alternate form of the GetVPCDnsResolutionBinding method which supports a Context parameter +func (vpc *VpcV1) GetVPCDnsResolutionBindingWithContext(ctx context.Context, getVPCDnsResolutionBindingOptions *GetVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPCDnsResolutionBindingOptions, "getVPCDnsResolutionBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(disconnectVPNClientOptions, "disconnectVPNClientOptions") + err = core.ValidateStruct(getVPCDnsResolutionBindingOptions, "getVPCDnsResolutionBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_server_id": *disconnectVPNClientOptions.VPNServerID, - "id": *disconnectVPNClientOptions.ID, + "vpc_id": *getVPCDnsResolutionBindingOptions.VPCID, + "id": *getVPCDnsResolutionBindingOptions.ID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/clients/{id}/disconnect`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range disconnectVPNClientOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCDnsResolutionBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DisconnectVPNClient") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCDnsResolutionBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -28604,72 +30122,80 @@ func (vpc *VpcV1) DisconnectVPNClientWithContext(ctx context.Context, disconnect return } - response, err = vpc.Service.Request(request, nil) + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "disconnect_vpn_client", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc_dns_resolution_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBinding) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } return } -// ListVPNServerRoutes : List VPN routes for a VPN server -// This request lists VPN routes in a VPN server. All VPN routes are provided to the VPN client when the connection is -// established. Packets received from the VPN client will be dropped by the VPN server if there is no VPN route -// matching their specified destinations. All VPN routes must be unique within the VPN server. -func (vpc *VpcV1) ListVPNServerRoutes(listVPNServerRoutesOptions *ListVPNServerRoutesOptions) (result *VPNServerRouteCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListVPNServerRoutesWithContext(context.Background(), listVPNServerRoutesOptions) +// UpdateVPCDnsResolutionBinding : Update a DNS resolution binding +// This request updates a DNS resolution binding with the information in a provided DNS resolution binding patch. The +// DNS resolution binding patch object is structured in the same way as a retrieved DNS resolution binding and contains +// only the information to be updated. +func (vpc *VpcV1) UpdateVPCDnsResolutionBinding(updateVPCDnsResolutionBindingOptions *UpdateVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPCDnsResolutionBindingWithContext(context.Background(), updateVPCDnsResolutionBindingOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListVPNServerRoutesWithContext is an alternate form of the ListVPNServerRoutes method which supports a Context parameter -func (vpc *VpcV1) ListVPNServerRoutesWithContext(ctx context.Context, listVPNServerRoutesOptions *ListVPNServerRoutesOptions) (result *VPNServerRouteCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listVPNServerRoutesOptions, "listVPNServerRoutesOptions cannot be nil") +// UpdateVPCDnsResolutionBindingWithContext is an alternate form of the UpdateVPCDnsResolutionBinding method which supports a Context parameter +func (vpc *VpcV1) UpdateVPCDnsResolutionBindingWithContext(ctx context.Context, updateVPCDnsResolutionBindingOptions *UpdateVPCDnsResolutionBindingOptions) (result *VpcdnsResolutionBinding, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPCDnsResolutionBindingOptions, "updateVPCDnsResolutionBindingOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listVPNServerRoutesOptions, "listVPNServerRoutesOptions") + err = core.ValidateStruct(updateVPCDnsResolutionBindingOptions, "updateVPCDnsResolutionBindingOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_server_id": *listVPNServerRoutesOptions.VPNServerID, + "vpc_id": *updateVPCDnsResolutionBindingOptions.VPCID, + "id": *updateVPCDnsResolutionBindingOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/dns_resolution_bindings/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listVPNServerRoutesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCDnsResolutionBinding") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNServerRoutes") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPCDnsResolutionBindingOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listVPNServerRoutesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listVPNServerRoutesOptions.Start)) - } - if listVPNServerRoutesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listVPNServerRoutesOptions.Limit)) - } - if listVPNServerRoutesOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listVPNServerRoutesOptions.Sort)) + + _, err = builder.SetBodyContentJSON(updateVPCDnsResolutionBindingOptions.VpcdnsResolutionBindingPatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } request, err := builder.Build() @@ -28681,12 +30207,12 @@ func (vpc *VpcV1) ListVPNServerRoutesWithContext(ctx context.Context, listVPNSer var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_vpn_server_routes", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpc_dns_resolution_binding", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerRouteCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVpcdnsResolutionBinding) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -28697,70 +30223,65 @@ func (vpc *VpcV1) ListVPNServerRoutesWithContext(ctx context.Context, listVPNSer return } -// CreateVPNServerRoute : Create a VPN route for a VPN server -// This request creates a new VPN route in the VPN server. All VPN routes are provided to the VPN client when the -// connection is established. Packets received from the VPN client will be dropped by the VPN server if there is no VPN -// route matching their specified destinations. All VPN routes must be unique within the VPN server. -func (vpc *VpcV1) CreateVPNServerRoute(createVPNServerRouteOptions *CreateVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateVPNServerRouteWithContext(context.Background(), createVPNServerRouteOptions) +// ListVPCRoutes : List routes in a VPC's default routing table +// This request lists routes in the VPC's default routing table. Each route is zone-specific and directs any packets +// matching its destination CIDR block to a `next_hop` IP address. The most specific route matching a packet's +// destination will be used. If multiple equally-specific routes exist, traffic will be distributed across them. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) ListVPCRoutes(listVPCRoutesOptions *ListVPCRoutesOptions) (result *RouteCollectionVPCContext, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPCRoutesWithContext(context.Background(), listVPCRoutesOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateVPNServerRouteWithContext is an alternate form of the CreateVPNServerRoute method which supports a Context parameter -func (vpc *VpcV1) CreateVPNServerRouteWithContext(ctx context.Context, createVPNServerRouteOptions *CreateVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createVPNServerRouteOptions, "createVPNServerRouteOptions cannot be nil") +// ListVPCRoutesWithContext is an alternate form of the ListVPCRoutes method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) ListVPCRoutesWithContext(ctx context.Context, listVPCRoutesOptions *ListVPCRoutesOptions) (result *RouteCollectionVPCContext, response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: ListVPCRoutes") + err = core.ValidateNotNil(listVPCRoutesOptions, "listVPCRoutesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createVPNServerRouteOptions, "createVPNServerRouteOptions") + err = core.ValidateStruct(listVPCRoutesOptions, "listVPCRoutesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_server_id": *createVPNServerRouteOptions.VPNServerID, + "vpc_id": *listVPCRoutesOptions.VPCID, } - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createVPNServerRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCRoutes") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPNServerRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPCRoutesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if createVPNServerRouteOptions.Destination != nil { - body["destination"] = createVPNServerRouteOptions.Destination - } - if createVPNServerRouteOptions.Action != nil { - body["action"] = createVPNServerRouteOptions.Action + if listVPCRoutesOptions.ZoneName != nil { + builder.AddQuery("zone.name", fmt.Sprint(*listVPCRoutesOptions.ZoneName)) } - if createVPNServerRouteOptions.Name != nil { - body["name"] = createVPNServerRouteOptions.Name + if listVPCRoutesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPCRoutesOptions.Start)) } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listVPCRoutesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPCRoutesOptions.Limit)) } request, err := builder.Build() @@ -28772,12 +30293,12 @@ func (vpc *VpcV1) CreateVPNServerRouteWithContext(ctx context.Context, createVPN var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_vpn_server_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpc_routes", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerRoute) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRouteCollectionVPCContext) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -28788,116 +30309,86 @@ func (vpc *VpcV1) CreateVPNServerRouteWithContext(ctx context.Context, createVPN return } -// DeleteVPNServerRoute : Delete a VPN route -// This request deletes a VPN route. This operation cannot be reversed. -func (vpc *VpcV1) DeleteVPNServerRoute(deleteVPNServerRouteOptions *DeleteVPNServerRouteOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteVPNServerRouteWithContext(context.Background(), deleteVPNServerRouteOptions) +// CreateVPCRoute : Create a route in a VPC's default routing table +// This request creates a new route in the VPC's default routing table. The route prototype object is structured in the +// same way as a retrieved route, and contains the information necessary to create the new route. The request will fail +// if the new route will cause a loop. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) CreateVPCRoute(createVPCRouteOptions *CreateVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPCRouteWithContext(context.Background(), createVPCRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteVPNServerRouteWithContext is an alternate form of the DeleteVPNServerRoute method which supports a Context parameter -func (vpc *VpcV1) DeleteVPNServerRouteWithContext(ctx context.Context, deleteVPNServerRouteOptions *DeleteVPNServerRouteOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteVPNServerRouteOptions, "deleteVPNServerRouteOptions cannot be nil") +// CreateVPCRouteWithContext is an alternate form of the CreateVPCRoute method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) CreateVPCRouteWithContext(ctx context.Context, createVPCRouteOptions *CreateVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: CreateVPCRoute") + err = core.ValidateNotNil(createVPCRouteOptions, "createVPCRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteVPNServerRouteOptions, "deleteVPNServerRouteOptions") + err = core.ValidateStruct(createVPCRouteOptions, "createVPCRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_server_id": *deleteVPNServerRouteOptions.VPNServerID, - "id": *deleteVPNServerRouteOptions.ID, + "vpc_id": *createVPCRouteOptions.VPCID, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteVPNServerRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNServerRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPCRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return + body := make(map[string]interface{}) + if createVPCRouteOptions.Destination != nil { + body["destination"] = createVPCRouteOptions.Destination } - - response, err = vpc.Service.Request(request, nil) - if err != nil { - core.EnrichHTTPProblem(err, "delete_vpn_server_route", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return + if createVPCRouteOptions.Zone != nil { + body["zone"] = createVPCRouteOptions.Zone } - - return -} - -// GetVPNServerRoute : Retrieve a VPN route -// This request retrieves a single VPN route specified by the identifier in the URL. -func (vpc *VpcV1) GetVPNServerRoute(getVPNServerRouteOptions *GetVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetVPNServerRouteWithContext(context.Background(), getVPNServerRouteOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// GetVPNServerRouteWithContext is an alternate form of the GetVPNServerRoute method which supports a Context parameter -func (vpc *VpcV1) GetVPNServerRouteWithContext(ctx context.Context, getVPNServerRouteOptions *GetVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getVPNServerRouteOptions, "getVPNServerRouteOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return + if createVPCRouteOptions.Action != nil { + body["action"] = createVPCRouteOptions.Action } - err = core.ValidateStruct(getVPNServerRouteOptions, "getVPNServerRouteOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return + if createVPCRouteOptions.Advertise != nil { + body["advertise"] = createVPCRouteOptions.Advertise } - - pathParamsMap := map[string]string{ - "vpn_server_id": *getVPNServerRouteOptions.VPNServerID, - "id": *getVPNServerRouteOptions.ID, + if createVPCRouteOptions.Name != nil { + body["name"] = createVPCRouteOptions.Name } - - builder := core.NewRequestBuilder(core.GET) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes/{id}`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return + if createVPCRouteOptions.NextHop != nil { + body["next_hop"] = createVPCRouteOptions.NextHop } - - for headerName, headerValue := range getVPNServerRouteOptions.Headers { - builder.AddHeader(headerName, headerValue) + if createVPCRouteOptions.Priority != nil { + body["priority"] = createVPCRouteOptions.Priority } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNServerRoute") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) + _, err = builder.SetBodyContentJSON(body) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return } - builder.AddHeader("Accept", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) request, err := builder.Build() if err != nil { @@ -28908,12 +30399,12 @@ func (vpc *VpcV1) GetVPNServerRouteWithContext(ctx context.Context, getVPNServer var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_vpn_server_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpc_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerRoute) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -28924,131 +30415,122 @@ func (vpc *VpcV1) GetVPNServerRouteWithContext(ctx context.Context, getVPNServer return } -// UpdateVPNServerRoute : Update a VPN route -// This request updates a VPN route with the information in a provided VPN route patch. The VPN route patch object is -// structured in the same way as a retrieved VPN route and contains only the information to be updated. -func (vpc *VpcV1) UpdateVPNServerRoute(updateVPNServerRouteOptions *UpdateVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateVPNServerRouteWithContext(context.Background(), updateVPNServerRouteOptions) +// DeleteVPCRoute : Delete a VPC route +// This request deletes a route. This operation cannot be reversed. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) DeleteVPCRoute(deleteVPCRouteOptions *DeleteVPCRouteOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPCRouteWithContext(context.Background(), deleteVPCRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateVPNServerRouteWithContext is an alternate form of the UpdateVPNServerRoute method which supports a Context parameter -func (vpc *VpcV1) UpdateVPNServerRouteWithContext(ctx context.Context, updateVPNServerRouteOptions *UpdateVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateVPNServerRouteOptions, "updateVPNServerRouteOptions cannot be nil") +// DeleteVPCRouteWithContext is an alternate form of the DeleteVPCRoute method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) DeleteVPCRouteWithContext(ctx context.Context, deleteVPCRouteOptions *DeleteVPCRouteOptions) (response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: DeleteVPCRoute") + err = core.ValidateNotNil(deleteVPCRouteOptions, "deleteVPCRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateVPNServerRouteOptions, "updateVPNServerRouteOptions") + err = core.ValidateStruct(deleteVPCRouteOptions, "deleteVPCRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "vpn_server_id": *updateVPNServerRouteOptions.VPNServerID, - "id": *updateVPNServerRouteOptions.ID, + "vpc_id": *deleteVPCRouteOptions.VPCID, + "id": *deleteVPCRouteOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateVPNServerRouteOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPNServerRoute") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPCRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateVPNServerRouteOptions.VPNServerRoutePatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "update_vpn_server_route", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpc_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerRoute) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListLoadBalancerProfiles : List load balancer profiles -// This request lists load balancer profiles available in the region. A load balancer profile specifies the performance -// characteristics and pricing model for a load balancer. -func (vpc *VpcV1) ListLoadBalancerProfiles(listLoadBalancerProfilesOptions *ListLoadBalancerProfilesOptions) (result *LoadBalancerProfileCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListLoadBalancerProfilesWithContext(context.Background(), listLoadBalancerProfilesOptions) +// GetVPCRoute : Retrieve a VPC route +// This request retrieves a single route specified by the identifier in the URL. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) GetVPCRoute(getVPCRouteOptions *GetVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCRouteWithContext(context.Background(), getVPCRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListLoadBalancerProfilesWithContext is an alternate form of the ListLoadBalancerProfiles method which supports a Context parameter -func (vpc *VpcV1) ListLoadBalancerProfilesWithContext(ctx context.Context, listLoadBalancerProfilesOptions *ListLoadBalancerProfilesOptions) (result *LoadBalancerProfileCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listLoadBalancerProfilesOptions, "listLoadBalancerProfilesOptions") +// GetVPCRouteWithContext is an alternate form of the GetVPCRoute method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) GetVPCRouteWithContext(ctx context.Context, getVPCRouteOptions *GetVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: GetVPCRoute") + err = core.ValidateNotNil(getVPCRouteOptions, "getVPCRouteOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getVPCRouteOptions, "getVPCRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "vpc_id": *getVPCRouteOptions.VPCID, + "id": *getVPCRouteOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancer/profiles`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listLoadBalancerProfilesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerProfiles") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listLoadBalancerProfilesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listLoadBalancerProfilesOptions.Start)) - } - if listLoadBalancerProfilesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listLoadBalancerProfilesOptions.Limit)) - } request, err := builder.Build() if err != nil { @@ -29059,12 +30541,12 @@ func (vpc *VpcV1) ListLoadBalancerProfilesWithContext(ctx context.Context, listL var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_load_balancer_profiles", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerProfileCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29075,53 +30557,65 @@ func (vpc *VpcV1) ListLoadBalancerProfilesWithContext(ctx context.Context, listL return } -// GetLoadBalancerProfile : Retrieve a load balancer profile -// This request retrieves a load balancer profile specified by the name in the URL. -func (vpc *VpcV1) GetLoadBalancerProfile(getLoadBalancerProfileOptions *GetLoadBalancerProfileOptions) (result *LoadBalancerProfile, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetLoadBalancerProfileWithContext(context.Background(), getLoadBalancerProfileOptions) +// UpdateVPCRoute : Update a VPC route +// This request updates a route with the information in a provided route patch. The route patch object is structured in +// the same way as a retrieved route and contains only the information to be updated. +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) UpdateVPCRoute(updateVPCRouteOptions *UpdateVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPCRouteWithContext(context.Background(), updateVPCRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLoadBalancerProfileWithContext is an alternate form of the GetLoadBalancerProfile method which supports a Context parameter -func (vpc *VpcV1) GetLoadBalancerProfileWithContext(ctx context.Context, getLoadBalancerProfileOptions *GetLoadBalancerProfileOptions) (result *LoadBalancerProfile, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLoadBalancerProfileOptions, "getLoadBalancerProfileOptions cannot be nil") +// UpdateVPCRouteWithContext is an alternate form of the UpdateVPCRoute method which supports a Context parameter +// Deprecated: this method is deprecated and may be removed in a future release. +func (vpc *VpcV1) UpdateVPCRouteWithContext(ctx context.Context, updateVPCRouteOptions *UpdateVPCRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + core.GetLogger().Warn("A deprecated operation has been invoked: UpdateVPCRoute") + err = core.ValidateNotNil(updateVPCRouteOptions, "updateVPCRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLoadBalancerProfileOptions, "getLoadBalancerProfileOptions") + err = core.ValidateStruct(updateVPCRouteOptions, "updateVPCRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "name": *getLoadBalancerProfileOptions.Name, + "vpc_id": *updateVPCRouteOptions.VPCID, + "id": *updateVPCRouteOptions.ID, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancer/profiles/{name}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLoadBalancerProfileOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerProfile") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPCRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + _, err = builder.SetBodyContentJSON(updateVPCRouteOptions.RoutePatch) + if err != nil { + err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) + return + } + request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -29131,12 +30625,12 @@ func (vpc *VpcV1) GetLoadBalancerProfileWithContext(ctx context.Context, getLoad var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_load_balancer_profile", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpc_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerProfile) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29147,48 +30641,63 @@ func (vpc *VpcV1) GetLoadBalancerProfileWithContext(ctx context.Context, getLoad return } -// ListLoadBalancers : List load balancers -// This request lists load balancers in the region. -func (vpc *VpcV1) ListLoadBalancers(listLoadBalancersOptions *ListLoadBalancersOptions) (result *LoadBalancerCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListLoadBalancersWithContext(context.Background(), listLoadBalancersOptions) +// ListVPCRoutingTables : List routing tables for a VPC +// This request lists routing tables for a VPC. Each subnet in a VPC is associated with a routing table, which controls +// delivery of packets sent on that subnet according to the action of the most specific matching route in the table. If +// multiple equally-specific routes exist, traffic will be distributed across them. If no routes match, delivery will be +// controlled by the system's built-in routes. +func (vpc *VpcV1) ListVPCRoutingTables(listVPCRoutingTablesOptions *ListVPCRoutingTablesOptions) (result *RoutingTableCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPCRoutingTablesWithContext(context.Background(), listVPCRoutingTablesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListLoadBalancersWithContext is an alternate form of the ListLoadBalancers method which supports a Context parameter -func (vpc *VpcV1) ListLoadBalancersWithContext(ctx context.Context, listLoadBalancersOptions *ListLoadBalancersOptions) (result *LoadBalancerCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listLoadBalancersOptions, "listLoadBalancersOptions") +// ListVPCRoutingTablesWithContext is an alternate form of the ListVPCRoutingTables method which supports a Context parameter +func (vpc *VpcV1) ListVPCRoutingTablesWithContext(ctx context.Context, listVPCRoutingTablesOptions *ListVPCRoutingTablesOptions) (result *RoutingTableCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPCRoutingTablesOptions, "listVPCRoutingTablesOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(listVPCRoutingTablesOptions, "listVPCRoutingTablesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "vpc_id": *listVPCRoutingTablesOptions.VPCID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listLoadBalancersOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCRoutingTables") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancers") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPCRoutingTablesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listLoadBalancersOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listLoadBalancersOptions.Start)) + if listVPCRoutingTablesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPCRoutingTablesOptions.Start)) } - if listLoadBalancersOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listLoadBalancersOptions.Limit)) + if listVPCRoutingTablesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPCRoutingTablesOptions.Limit)) + } + if listVPCRoutingTablesOptions.IsDefault != nil { + builder.AddQuery("is_default", fmt.Sprint(*listVPCRoutingTablesOptions.IsDefault)) } request, err := builder.Build() @@ -29200,12 +30709,12 @@ func (vpc *VpcV1) ListLoadBalancersWithContext(ctx context.Context, listLoadBala var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_load_balancers", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpc_routing_tables", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTableCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29216,42 +30725,50 @@ func (vpc *VpcV1) ListLoadBalancersWithContext(ctx context.Context, listLoadBala return } -// CreateLoadBalancer : Create a load balancer -// This request creates and provisions a new load balancer. -func (vpc *VpcV1) CreateLoadBalancer(createLoadBalancerOptions *CreateLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateLoadBalancerWithContext(context.Background(), createLoadBalancerOptions) +// CreateVPCRoutingTable : Create a routing table for a VPC +// This request creates a routing table from a routing table prototype object. The prototype object is structured in the +// same way as a retrieved routing table, and contains the information necessary to create the new routing table. +// +// At present, the routing table's `resource_group` will be inherited from its VPC, but may be specifiable in the +// future. +func (vpc *VpcV1) CreateVPCRoutingTable(createVPCRoutingTableOptions *CreateVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPCRoutingTableWithContext(context.Background(), createVPCRoutingTableOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateLoadBalancerWithContext is an alternate form of the CreateLoadBalancer method which supports a Context parameter -func (vpc *VpcV1) CreateLoadBalancerWithContext(ctx context.Context, createLoadBalancerOptions *CreateLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createLoadBalancerOptions, "createLoadBalancerOptions cannot be nil") +// CreateVPCRoutingTableWithContext is an alternate form of the CreateVPCRoutingTable method which supports a Context parameter +func (vpc *VpcV1) CreateVPCRoutingTableWithContext(ctx context.Context, createVPCRoutingTableOptions *CreateVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVPCRoutingTableOptions, "createVPCRoutingTableOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createLoadBalancerOptions, "createLoadBalancerOptions") + err = core.ValidateStruct(createVPCRoutingTableOptions, "createVPCRoutingTableOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "vpc_id": *createVPCRoutingTableOptions.VPCID, + } + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createLoadBalancerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCRoutingTable") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPCRoutingTableOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -29261,41 +30778,29 @@ func (vpc *VpcV1) CreateLoadBalancerWithContext(ctx context.Context, createLoadB builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createLoadBalancerOptions.IsPublic != nil { - body["is_public"] = createLoadBalancerOptions.IsPublic - } - if createLoadBalancerOptions.Subnets != nil { - body["subnets"] = createLoadBalancerOptions.Subnets - } - if createLoadBalancerOptions.Dns != nil { - body["dns"] = createLoadBalancerOptions.Dns - } - if createLoadBalancerOptions.IsPrivatePath != nil { - body["is_private_path"] = createLoadBalancerOptions.IsPrivatePath - } - if createLoadBalancerOptions.Listeners != nil { - body["listeners"] = createLoadBalancerOptions.Listeners + if createVPCRoutingTableOptions.AcceptRoutesFrom != nil { + body["accept_routes_from"] = createVPCRoutingTableOptions.AcceptRoutesFrom } - if createLoadBalancerOptions.Logging != nil { - body["logging"] = createLoadBalancerOptions.Logging + if createVPCRoutingTableOptions.AdvertiseRoutesTo != nil { + body["advertise_routes_to"] = createVPCRoutingTableOptions.AdvertiseRoutesTo } - if createLoadBalancerOptions.Name != nil { - body["name"] = createLoadBalancerOptions.Name + if createVPCRoutingTableOptions.Name != nil { + body["name"] = createVPCRoutingTableOptions.Name } - if createLoadBalancerOptions.Pools != nil { - body["pools"] = createLoadBalancerOptions.Pools + if createVPCRoutingTableOptions.RouteDirectLinkIngress != nil { + body["route_direct_link_ingress"] = createVPCRoutingTableOptions.RouteDirectLinkIngress } - if createLoadBalancerOptions.Profile != nil { - body["profile"] = createLoadBalancerOptions.Profile + if createVPCRoutingTableOptions.RouteInternetIngress != nil { + body["route_internet_ingress"] = createVPCRoutingTableOptions.RouteInternetIngress } - if createLoadBalancerOptions.ResourceGroup != nil { - body["resource_group"] = createLoadBalancerOptions.ResourceGroup + if createVPCRoutingTableOptions.RouteTransitGatewayIngress != nil { + body["route_transit_gateway_ingress"] = createVPCRoutingTableOptions.RouteTransitGatewayIngress } - if createLoadBalancerOptions.RouteMode != nil { - body["route_mode"] = createLoadBalancerOptions.RouteMode + if createVPCRoutingTableOptions.RouteVPCZoneIngress != nil { + body["route_vpc_zone_ingress"] = createVPCRoutingTableOptions.RouteVPCZoneIngress } - if createLoadBalancerOptions.SecurityGroups != nil { - body["security_groups"] = createLoadBalancerOptions.SecurityGroups + if createVPCRoutingTableOptions.Routes != nil { + body["routes"] = createVPCRoutingTableOptions.Routes } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -29312,12 +30817,12 @@ func (vpc *VpcV1) CreateLoadBalancerWithContext(ctx context.Context, createLoadB var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_load_balancer", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpc_routing_table", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancer) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29328,51 +30833,52 @@ func (vpc *VpcV1) CreateLoadBalancerWithContext(ctx context.Context, createLoadB return } -// DeleteLoadBalancer : Delete a load balancer -// This request deletes a load balancer. This operation cannot be reversed. A load balancer cannot be deleted if its -// `provisioning_status` is `delete_pending` or it is referenced by a resource. -func (vpc *VpcV1) DeleteLoadBalancer(deleteLoadBalancerOptions *DeleteLoadBalancerOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteLoadBalancerWithContext(context.Background(), deleteLoadBalancerOptions) +// DeleteVPCRoutingTable : Delete a VPC routing table +// This request deletes a routing table. A routing table cannot be deleted if it is associated with any subnets in the +// VPC. Additionally, a VPC's default routing table cannot be deleted. This operation cannot be reversed. +func (vpc *VpcV1) DeleteVPCRoutingTable(deleteVPCRoutingTableOptions *DeleteVPCRoutingTableOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPCRoutingTableWithContext(context.Background(), deleteVPCRoutingTableOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteLoadBalancerWithContext is an alternate form of the DeleteLoadBalancer method which supports a Context parameter -func (vpc *VpcV1) DeleteLoadBalancerWithContext(ctx context.Context, deleteLoadBalancerOptions *DeleteLoadBalancerOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteLoadBalancerOptions, "deleteLoadBalancerOptions cannot be nil") +// DeleteVPCRoutingTableWithContext is an alternate form of the DeleteVPCRoutingTable method which supports a Context parameter +func (vpc *VpcV1) DeleteVPCRoutingTableWithContext(ctx context.Context, deleteVPCRoutingTableOptions *DeleteVPCRoutingTableOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPCRoutingTableOptions, "deleteVPCRoutingTableOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteLoadBalancerOptions, "deleteLoadBalancerOptions") + err = core.ValidateStruct(deleteVPCRoutingTableOptions, "deleteVPCRoutingTableOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteLoadBalancerOptions.ID, + "vpc_id": *deleteVPCRoutingTableOptions.VPCID, + "id": *deleteVPCRoutingTableOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteLoadBalancerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCRoutingTable") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPCRoutingTableOptions.Headers { builder.AddHeader(headerName, headerValue) } - if deleteLoadBalancerOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*deleteLoadBalancerOptions.IfMatch)) + if deleteVPCRoutingTableOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteVPCRoutingTableOptions.IfMatch)) } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) @@ -29386,7 +30892,7 @@ func (vpc *VpcV1) DeleteLoadBalancerWithContext(ctx context.Context, deleteLoadB response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_load_balancer", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpc_routing_table", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -29394,46 +30900,47 @@ func (vpc *VpcV1) DeleteLoadBalancerWithContext(ctx context.Context, deleteLoadB return } -// GetLoadBalancer : Retrieve a load balancer -// This request retrieves a single load balancer specified by the identifier in the URL path. -func (vpc *VpcV1) GetLoadBalancer(getLoadBalancerOptions *GetLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetLoadBalancerWithContext(context.Background(), getLoadBalancerOptions) +// GetVPCRoutingTable : Retrieve a VPC routing table +// This request retrieves a single routing table specified by the identifier in the URL. +func (vpc *VpcV1) GetVPCRoutingTable(getVPCRoutingTableOptions *GetVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCRoutingTableWithContext(context.Background(), getVPCRoutingTableOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLoadBalancerWithContext is an alternate form of the GetLoadBalancer method which supports a Context parameter -func (vpc *VpcV1) GetLoadBalancerWithContext(ctx context.Context, getLoadBalancerOptions *GetLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLoadBalancerOptions, "getLoadBalancerOptions cannot be nil") +// GetVPCRoutingTableWithContext is an alternate form of the GetVPCRoutingTable method which supports a Context parameter +func (vpc *VpcV1) GetVPCRoutingTableWithContext(ctx context.Context, getVPCRoutingTableOptions *GetVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPCRoutingTableOptions, "getVPCRoutingTableOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLoadBalancerOptions, "getLoadBalancerOptions") + err = core.ValidateStruct(getVPCRoutingTableOptions, "getVPCRoutingTableOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getLoadBalancerOptions.ID, + "vpc_id": *getVPCRoutingTableOptions.VPCID, + "id": *getVPCRoutingTableOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLoadBalancerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCRoutingTable") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCRoutingTableOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -29450,12 +30957,12 @@ func (vpc *VpcV1) GetLoadBalancerWithContext(ctx context.Context, getLoadBalance var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_load_balancer", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc_routing_table", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancer) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29466,60 +30973,60 @@ func (vpc *VpcV1) GetLoadBalancerWithContext(ctx context.Context, getLoadBalance return } -// UpdateLoadBalancer : Update a load balancer -// This request updates a load balancer with the information in a provided load balancer patch. The load balancer patch -// object is structured in the same way as a retrieved load balancer and contains only the information to be updated. A -// load balancer can only be updated if its `provisioning_status` is `active`. -func (vpc *VpcV1) UpdateLoadBalancer(updateLoadBalancerOptions *UpdateLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateLoadBalancerWithContext(context.Background(), updateLoadBalancerOptions) +// UpdateVPCRoutingTable : Update a VPC routing table +// This request updates a routing table with the information in a provided routing table patch. The patch object is +// structured in the same way as a retrieved table and contains only the information to be updated. +func (vpc *VpcV1) UpdateVPCRoutingTable(updateVPCRoutingTableOptions *UpdateVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPCRoutingTableWithContext(context.Background(), updateVPCRoutingTableOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateLoadBalancerWithContext is an alternate form of the UpdateLoadBalancer method which supports a Context parameter -func (vpc *VpcV1) UpdateLoadBalancerWithContext(ctx context.Context, updateLoadBalancerOptions *UpdateLoadBalancerOptions) (result *LoadBalancer, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateLoadBalancerOptions, "updateLoadBalancerOptions cannot be nil") +// UpdateVPCRoutingTableWithContext is an alternate form of the UpdateVPCRoutingTable method which supports a Context parameter +func (vpc *VpcV1) UpdateVPCRoutingTableWithContext(ctx context.Context, updateVPCRoutingTableOptions *UpdateVPCRoutingTableOptions) (result *RoutingTable, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPCRoutingTableOptions, "updateVPCRoutingTableOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateLoadBalancerOptions, "updateLoadBalancerOptions") + err = core.ValidateStruct(updateVPCRoutingTableOptions, "updateVPCRoutingTableOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateLoadBalancerOptions.ID, + "vpc_id": *updateVPCRoutingTableOptions.VPCID, + "id": *updateVPCRoutingTableOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateLoadBalancerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCRoutingTable") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancer") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPCRoutingTableOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") - if updateLoadBalancerOptions.IfMatch != nil { - builder.AddHeader("If-Match", fmt.Sprint(*updateLoadBalancerOptions.IfMatch)) + if updateVPCRoutingTableOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateVPCRoutingTableOptions.IfMatch)) } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateLoadBalancerOptions.LoadBalancerPatch) + _, err = builder.SetBodyContentJSON(updateVPCRoutingTableOptions.RoutingTablePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -29534,12 +31041,12 @@ func (vpc *VpcV1) UpdateLoadBalancerWithContext(ctx context.Context, updateLoadB var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_load_balancer", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpc_routing_table", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancer) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoutingTable) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29550,52 +31057,63 @@ func (vpc *VpcV1) UpdateLoadBalancerWithContext(ctx context.Context, updateLoadB return } -// GetLoadBalancerStatistics : List statistics of a load balancer -// This request lists statistics of a load balancer. -func (vpc *VpcV1) GetLoadBalancerStatistics(getLoadBalancerStatisticsOptions *GetLoadBalancerStatisticsOptions) (result *LoadBalancerStatistics, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetLoadBalancerStatisticsWithContext(context.Background(), getLoadBalancerStatisticsOptions) +// ListVPCRoutingTableRoutes : List routes in a VPC routing table +// This request lists routes in a VPC routing table. If subnets are associated with this routing table, delivery of +// packets sent on a subnet is performed according to the action of the most specific matching route in the table +// (provided the subnet and route are in the same zone). If multiple equally-specific routes exist, the route with the +// highest priority will be used. If two matching routes have the same destination and priority, traffic will be +// distributed between them. If no routes match, delivery will be controlled by the system's built-in routes. +func (vpc *VpcV1) ListVPCRoutingTableRoutes(listVPCRoutingTableRoutesOptions *ListVPCRoutingTableRoutesOptions) (result *RouteCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPCRoutingTableRoutesWithContext(context.Background(), listVPCRoutingTableRoutesOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLoadBalancerStatisticsWithContext is an alternate form of the GetLoadBalancerStatistics method which supports a Context parameter -func (vpc *VpcV1) GetLoadBalancerStatisticsWithContext(ctx context.Context, getLoadBalancerStatisticsOptions *GetLoadBalancerStatisticsOptions) (result *LoadBalancerStatistics, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLoadBalancerStatisticsOptions, "getLoadBalancerStatisticsOptions cannot be nil") +// ListVPCRoutingTableRoutesWithContext is an alternate form of the ListVPCRoutingTableRoutes method which supports a Context parameter +func (vpc *VpcV1) ListVPCRoutingTableRoutesWithContext(ctx context.Context, listVPCRoutingTableRoutesOptions *ListVPCRoutingTableRoutesOptions) (result *RouteCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPCRoutingTableRoutesOptions, "listVPCRoutingTableRoutesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLoadBalancerStatisticsOptions, "getLoadBalancerStatisticsOptions") + err = core.ValidateStruct(listVPCRoutingTableRoutesOptions, "listVPCRoutingTableRoutesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getLoadBalancerStatisticsOptions.ID, + "vpc_id": *listVPCRoutingTableRoutesOptions.VPCID, + "routing_table_id": *listVPCRoutingTableRoutesOptions.RoutingTableID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{id}/statistics`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLoadBalancerStatisticsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPCRoutingTableRoutes") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerStatistics") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPCRoutingTableRoutesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listVPCRoutingTableRoutesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPCRoutingTableRoutesOptions.Start)) + } + if listVPCRoutingTableRoutesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPCRoutingTableRoutesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -29606,12 +31124,12 @@ func (vpc *VpcV1) GetLoadBalancerStatisticsWithContext(ctx context.Context, getL var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_load_balancer_statistics", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpc_routing_table_routes", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerStatistics) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRouteCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29622,118 +31140,48 @@ func (vpc *VpcV1) GetLoadBalancerStatisticsWithContext(ctx context.Context, getL return } -// ListLoadBalancerListeners : List listeners for a load balancer -// This request lists listeners for a load balancer. -func (vpc *VpcV1) ListLoadBalancerListeners(listLoadBalancerListenersOptions *ListLoadBalancerListenersOptions) (result *LoadBalancerListenerCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListLoadBalancerListenersWithContext(context.Background(), listLoadBalancerListenersOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// ListLoadBalancerListenersWithContext is an alternate form of the ListLoadBalancerListeners method which supports a Context parameter -func (vpc *VpcV1) ListLoadBalancerListenersWithContext(ctx context.Context, listLoadBalancerListenersOptions *ListLoadBalancerListenersOptions) (result *LoadBalancerListenerCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listLoadBalancerListenersOptions, "listLoadBalancerListenersOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(listLoadBalancerListenersOptions, "listLoadBalancerListenersOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "load_balancer_id": *listLoadBalancerListenersOptions.LoadBalancerID, - } - - builder := core.NewRequestBuilder(core.GET) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range listLoadBalancerListenersOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerListeners") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Accept", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) - if err != nil { - core.EnrichHTTPProblem(err, "list_load_balancer_listeners", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } - - return -} - -// CreateLoadBalancerListener : Create a listener for a load balancer -// This request creates a new listener for a load balancer. -func (vpc *VpcV1) CreateLoadBalancerListener(createLoadBalancerListenerOptions *CreateLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateLoadBalancerListenerWithContext(context.Background(), createLoadBalancerListenerOptions) +// CreateVPCRoutingTableRoute : Create a route in a VPC routing table +// This request creates a new VPC route from a VPC route prototype object. The prototype object is structured in the +// same way as a retrieved VPC route and contains the information necessary to create the route. +func (vpc *VpcV1) CreateVPCRoutingTableRoute(createVPCRoutingTableRouteOptions *CreateVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPCRoutingTableRouteWithContext(context.Background(), createVPCRoutingTableRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateLoadBalancerListenerWithContext is an alternate form of the CreateLoadBalancerListener method which supports a Context parameter -func (vpc *VpcV1) CreateLoadBalancerListenerWithContext(ctx context.Context, createLoadBalancerListenerOptions *CreateLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createLoadBalancerListenerOptions, "createLoadBalancerListenerOptions cannot be nil") +// CreateVPCRoutingTableRouteWithContext is an alternate form of the CreateVPCRoutingTableRoute method which supports a Context parameter +func (vpc *VpcV1) CreateVPCRoutingTableRouteWithContext(ctx context.Context, createVPCRoutingTableRouteOptions *CreateVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVPCRoutingTableRouteOptions, "createVPCRoutingTableRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createLoadBalancerListenerOptions, "createLoadBalancerListenerOptions") + err = core.ValidateStruct(createVPCRoutingTableRouteOptions, "createVPCRoutingTableRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *createLoadBalancerListenerOptions.LoadBalancerID, + "vpc_id": *createVPCRoutingTableRouteOptions.VPCID, + "routing_table_id": *createVPCRoutingTableRouteOptions.RoutingTableID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createLoadBalancerListenerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPCRoutingTableRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerListener") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPCRoutingTableRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -29743,38 +31191,26 @@ func (vpc *VpcV1) CreateLoadBalancerListenerWithContext(ctx context.Context, cre builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createLoadBalancerListenerOptions.Protocol != nil { - body["protocol"] = createLoadBalancerListenerOptions.Protocol - } - if createLoadBalancerListenerOptions.AcceptProxyProtocol != nil { - body["accept_proxy_protocol"] = createLoadBalancerListenerOptions.AcceptProxyProtocol - } - if createLoadBalancerListenerOptions.CertificateInstance != nil { - body["certificate_instance"] = createLoadBalancerListenerOptions.CertificateInstance - } - if createLoadBalancerListenerOptions.ConnectionLimit != nil { - body["connection_limit"] = createLoadBalancerListenerOptions.ConnectionLimit - } - if createLoadBalancerListenerOptions.DefaultPool != nil { - body["default_pool"] = createLoadBalancerListenerOptions.DefaultPool + if createVPCRoutingTableRouteOptions.Destination != nil { + body["destination"] = createVPCRoutingTableRouteOptions.Destination } - if createLoadBalancerListenerOptions.HTTPSRedirect != nil { - body["https_redirect"] = createLoadBalancerListenerOptions.HTTPSRedirect + if createVPCRoutingTableRouteOptions.Zone != nil { + body["zone"] = createVPCRoutingTableRouteOptions.Zone } - if createLoadBalancerListenerOptions.IdleConnectionTimeout != nil { - body["idle_connection_timeout"] = createLoadBalancerListenerOptions.IdleConnectionTimeout + if createVPCRoutingTableRouteOptions.Action != nil { + body["action"] = createVPCRoutingTableRouteOptions.Action } - if createLoadBalancerListenerOptions.Policies != nil { - body["policies"] = createLoadBalancerListenerOptions.Policies + if createVPCRoutingTableRouteOptions.Advertise != nil { + body["advertise"] = createVPCRoutingTableRouteOptions.Advertise } - if createLoadBalancerListenerOptions.Port != nil { - body["port"] = createLoadBalancerListenerOptions.Port + if createVPCRoutingTableRouteOptions.Name != nil { + body["name"] = createVPCRoutingTableRouteOptions.Name } - if createLoadBalancerListenerOptions.PortMax != nil { - body["port_max"] = createLoadBalancerListenerOptions.PortMax + if createVPCRoutingTableRouteOptions.NextHop != nil { + body["next_hop"] = createVPCRoutingTableRouteOptions.NextHop } - if createLoadBalancerListenerOptions.PortMin != nil { - body["port_min"] = createLoadBalancerListenerOptions.PortMin + if createVPCRoutingTableRouteOptions.Priority != nil { + body["priority"] = createVPCRoutingTableRouteOptions.Priority } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -29791,12 +31227,12 @@ func (vpc *VpcV1) CreateLoadBalancerListenerWithContext(ctx context.Context, cre var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_load_balancer_listener", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpc_routing_table_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListener) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29807,48 +31243,49 @@ func (vpc *VpcV1) CreateLoadBalancerListenerWithContext(ctx context.Context, cre return } -// DeleteLoadBalancerListener : Delete a load balancer listener -// This request deletes a load balancer listener. This operation cannot be reversed. For this operation to succeed, the -// listener must not be the target of another load balancer listener. -func (vpc *VpcV1) DeleteLoadBalancerListener(deleteLoadBalancerListenerOptions *DeleteLoadBalancerListenerOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteLoadBalancerListenerWithContext(context.Background(), deleteLoadBalancerListenerOptions) +// DeleteVPCRoutingTableRoute : Delete a VPC routing table route +// This request deletes a VPC route. This operation cannot be reversed. Only VPC routes with an `origin` of `user` are +// allowed to be deleted. +func (vpc *VpcV1) DeleteVPCRoutingTableRoute(deleteVPCRoutingTableRouteOptions *DeleteVPCRoutingTableRouteOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPCRoutingTableRouteWithContext(context.Background(), deleteVPCRoutingTableRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteLoadBalancerListenerWithContext is an alternate form of the DeleteLoadBalancerListener method which supports a Context parameter -func (vpc *VpcV1) DeleteLoadBalancerListenerWithContext(ctx context.Context, deleteLoadBalancerListenerOptions *DeleteLoadBalancerListenerOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteLoadBalancerListenerOptions, "deleteLoadBalancerListenerOptions cannot be nil") +// DeleteVPCRoutingTableRouteWithContext is an alternate form of the DeleteVPCRoutingTableRoute method which supports a Context parameter +func (vpc *VpcV1) DeleteVPCRoutingTableRouteWithContext(ctx context.Context, deleteVPCRoutingTableRouteOptions *DeleteVPCRoutingTableRouteOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPCRoutingTableRouteOptions, "deleteVPCRoutingTableRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteLoadBalancerListenerOptions, "deleteLoadBalancerListenerOptions") + err = core.ValidateStruct(deleteVPCRoutingTableRouteOptions, "deleteVPCRoutingTableRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *deleteLoadBalancerListenerOptions.LoadBalancerID, - "id": *deleteLoadBalancerListenerOptions.ID, + "vpc_id": *deleteVPCRoutingTableRouteOptions.VPCID, + "routing_table_id": *deleteVPCRoutingTableRouteOptions.RoutingTableID, + "id": *deleteVPCRoutingTableRouteOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteLoadBalancerListenerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPCRoutingTableRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerListener") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPCRoutingTableRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -29863,7 +31300,7 @@ func (vpc *VpcV1) DeleteLoadBalancerListenerWithContext(ctx context.Context, del response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_load_balancer_listener", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpc_routing_table_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -29871,47 +31308,48 @@ func (vpc *VpcV1) DeleteLoadBalancerListenerWithContext(ctx context.Context, del return } -// GetLoadBalancerListener : Retrieve a load balancer listener -// This request retrieves a single listener specified by the identifier in the URL path. -func (vpc *VpcV1) GetLoadBalancerListener(getLoadBalancerListenerOptions *GetLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetLoadBalancerListenerWithContext(context.Background(), getLoadBalancerListenerOptions) +// GetVPCRoutingTableRoute : Retrieve a VPC routing table route +// This request retrieves a single VPC route specified by the identifier in the URL path. +func (vpc *VpcV1) GetVPCRoutingTableRoute(getVPCRoutingTableRouteOptions *GetVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPCRoutingTableRouteWithContext(context.Background(), getVPCRoutingTableRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLoadBalancerListenerWithContext is an alternate form of the GetLoadBalancerListener method which supports a Context parameter -func (vpc *VpcV1) GetLoadBalancerListenerWithContext(ctx context.Context, getLoadBalancerListenerOptions *GetLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLoadBalancerListenerOptions, "getLoadBalancerListenerOptions cannot be nil") +// GetVPCRoutingTableRouteWithContext is an alternate form of the GetVPCRoutingTableRoute method which supports a Context parameter +func (vpc *VpcV1) GetVPCRoutingTableRouteWithContext(ctx context.Context, getVPCRoutingTableRouteOptions *GetVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPCRoutingTableRouteOptions, "getVPCRoutingTableRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLoadBalancerListenerOptions, "getLoadBalancerListenerOptions") + err = core.ValidateStruct(getVPCRoutingTableRouteOptions, "getVPCRoutingTableRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *getLoadBalancerListenerOptions.LoadBalancerID, - "id": *getLoadBalancerListenerOptions.ID, + "vpc_id": *getVPCRoutingTableRouteOptions.VPCID, + "routing_table_id": *getVPCRoutingTableRouteOptions.RoutingTableID, + "id": *getVPCRoutingTableRouteOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLoadBalancerListenerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPCRoutingTableRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerListener") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPCRoutingTableRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -29928,12 +31366,12 @@ func (vpc *VpcV1) GetLoadBalancerListenerWithContext(ctx context.Context, getLoa var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_load_balancer_listener", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpc_routing_table_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListener) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -29944,47 +31382,50 @@ func (vpc *VpcV1) GetLoadBalancerListenerWithContext(ctx context.Context, getLoa return } -// UpdateLoadBalancerListener : Update a load balancer listener -// This request updates a load balancer listener from a listener patch. -func (vpc *VpcV1) UpdateLoadBalancerListener(updateLoadBalancerListenerOptions *UpdateLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateLoadBalancerListenerWithContext(context.Background(), updateLoadBalancerListenerOptions) +// UpdateVPCRoutingTableRoute : Update a VPC routing table route +// This request updates a VPC route with the information provided in a route patch object. The patch object is +// structured in the same way as a retrieved VPC route and needs to contain only the information to be updated. Only VPC +// routes with an `origin` of `user` are allowed to be updated. +func (vpc *VpcV1) UpdateVPCRoutingTableRoute(updateVPCRoutingTableRouteOptions *UpdateVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPCRoutingTableRouteWithContext(context.Background(), updateVPCRoutingTableRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateLoadBalancerListenerWithContext is an alternate form of the UpdateLoadBalancerListener method which supports a Context parameter -func (vpc *VpcV1) UpdateLoadBalancerListenerWithContext(ctx context.Context, updateLoadBalancerListenerOptions *UpdateLoadBalancerListenerOptions) (result *LoadBalancerListener, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateLoadBalancerListenerOptions, "updateLoadBalancerListenerOptions cannot be nil") +// UpdateVPCRoutingTableRouteWithContext is an alternate form of the UpdateVPCRoutingTableRoute method which supports a Context parameter +func (vpc *VpcV1) UpdateVPCRoutingTableRouteWithContext(ctx context.Context, updateVPCRoutingTableRouteOptions *UpdateVPCRoutingTableRouteOptions) (result *Route, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPCRoutingTableRouteOptions, "updateVPCRoutingTableRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateLoadBalancerListenerOptions, "updateLoadBalancerListenerOptions") + err = core.ValidateStruct(updateVPCRoutingTableRouteOptions, "updateVPCRoutingTableRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *updateLoadBalancerListenerOptions.LoadBalancerID, - "id": *updateLoadBalancerListenerOptions.ID, + "vpc_id": *updateVPCRoutingTableRouteOptions.VPCID, + "routing_table_id": *updateVPCRoutingTableRouteOptions.RoutingTableID, + "id": *updateVPCRoutingTableRouteOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpcs/{vpc_id}/routing_tables/{routing_table_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateLoadBalancerListenerOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPCRoutingTableRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerListener") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPCRoutingTableRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -29993,7 +31434,7 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerWithContext(ctx context.Context, upd builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateLoadBalancerListenerOptions.LoadBalancerListenerPatch) + _, err = builder.SetBodyContentJSON(updateVPCRoutingTableRouteOptions.RoutePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -30008,12 +31449,12 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerWithContext(ctx context.Context, upd var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_load_balancer_listener", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpc_routing_table_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListener) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30024,54 +31465,49 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerWithContext(ctx context.Context, upd return } -// ListLoadBalancerListenerPolicies : List policies for a load balancer listener -// This request lists policies for a load balancer listener. A policy consists of rules to match against each incoming -// request, and an action to apply to the request if a rule matches. -func (vpc *VpcV1) ListLoadBalancerListenerPolicies(listLoadBalancerListenerPoliciesOptions *ListLoadBalancerListenerPoliciesOptions) (result *LoadBalancerListenerPolicyCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListLoadBalancerListenerPoliciesWithContext(context.Background(), listLoadBalancerListenerPoliciesOptions) +// ListIkePolicies : List IKE policies +// This request lists IKE policies in the region. +func (vpc *VpcV1) ListIkePolicies(listIkePoliciesOptions *ListIkePoliciesOptions) (result *IkePolicyCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListIkePoliciesWithContext(context.Background(), listIkePoliciesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListLoadBalancerListenerPoliciesWithContext is an alternate form of the ListLoadBalancerListenerPolicies method which supports a Context parameter -func (vpc *VpcV1) ListLoadBalancerListenerPoliciesWithContext(ctx context.Context, listLoadBalancerListenerPoliciesOptions *ListLoadBalancerListenerPoliciesOptions) (result *LoadBalancerListenerPolicyCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listLoadBalancerListenerPoliciesOptions, "listLoadBalancerListenerPoliciesOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(listLoadBalancerListenerPoliciesOptions, "listLoadBalancerListenerPoliciesOptions") +// ListIkePoliciesWithContext is an alternate form of the ListIkePolicies method which supports a Context parameter +func (vpc *VpcV1) ListIkePoliciesWithContext(ctx context.Context, listIkePoliciesOptions *ListIkePoliciesOptions) (result *IkePolicyCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listIkePoliciesOptions, "listIkePoliciesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "load_balancer_id": *listLoadBalancerListenerPoliciesOptions.LoadBalancerID, - "listener_id": *listLoadBalancerListenerPoliciesOptions.ListenerID, - } - builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listLoadBalancerListenerPoliciesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListIkePolicies") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerListenerPolicies") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listIkePoliciesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listIkePoliciesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listIkePoliciesOptions.Start)) + } + if listIkePoliciesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listIkePoliciesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -30082,12 +31518,12 @@ func (vpc *VpcV1) ListLoadBalancerListenerPoliciesWithContext(ctx context.Contex var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_load_balancer_listener_policies", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_ike_policies", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicyCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30098,49 +31534,42 @@ func (vpc *VpcV1) ListLoadBalancerListenerPoliciesWithContext(ctx context.Contex return } -// CreateLoadBalancerListenerPolicy : Create a policy for a load balancer listener -// This request creates a new policy from a load balancer listener policy object. The prototype object is structured in -// the same way as a retrieved policy, and contains the information necessary to create the new policy. For this request -// to succeed, the load balancer must be in the `application` family. -func (vpc *VpcV1) CreateLoadBalancerListenerPolicy(createLoadBalancerListenerPolicyOptions *CreateLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateLoadBalancerListenerPolicyWithContext(context.Background(), createLoadBalancerListenerPolicyOptions) +// CreateIkePolicy : Create an IKE policy +// This request creates a new IKE policy. +func (vpc *VpcV1) CreateIkePolicy(createIkePolicyOptions *CreateIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateIkePolicyWithContext(context.Background(), createIkePolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateLoadBalancerListenerPolicyWithContext is an alternate form of the CreateLoadBalancerListenerPolicy method which supports a Context parameter -func (vpc *VpcV1) CreateLoadBalancerListenerPolicyWithContext(ctx context.Context, createLoadBalancerListenerPolicyOptions *CreateLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createLoadBalancerListenerPolicyOptions, "createLoadBalancerListenerPolicyOptions cannot be nil") +// CreateIkePolicyWithContext is an alternate form of the CreateIkePolicy method which supports a Context parameter +func (vpc *VpcV1) CreateIkePolicyWithContext(ctx context.Context, createIkePolicyOptions *CreateIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createIkePolicyOptions, "createIkePolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createLoadBalancerListenerPolicyOptions, "createLoadBalancerListenerPolicyOptions") + err = core.ValidateStruct(createIkePolicyOptions, "createIkePolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "load_balancer_id": *createLoadBalancerListenerPolicyOptions.LoadBalancerID, - "listener_id": *createLoadBalancerListenerPolicyOptions.ListenerID, - } - builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createLoadBalancerListenerPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateIkePolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerListenerPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createIkePolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -30150,20 +31579,26 @@ func (vpc *VpcV1) CreateLoadBalancerListenerPolicyWithContext(ctx context.Contex builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createLoadBalancerListenerPolicyOptions.Action != nil { - body["action"] = createLoadBalancerListenerPolicyOptions.Action + if createIkePolicyOptions.AuthenticationAlgorithm != nil { + body["authentication_algorithm"] = createIkePolicyOptions.AuthenticationAlgorithm } - if createLoadBalancerListenerPolicyOptions.Priority != nil { - body["priority"] = createLoadBalancerListenerPolicyOptions.Priority + if createIkePolicyOptions.DhGroup != nil { + body["dh_group"] = createIkePolicyOptions.DhGroup } - if createLoadBalancerListenerPolicyOptions.Name != nil { - body["name"] = createLoadBalancerListenerPolicyOptions.Name + if createIkePolicyOptions.EncryptionAlgorithm != nil { + body["encryption_algorithm"] = createIkePolicyOptions.EncryptionAlgorithm } - if createLoadBalancerListenerPolicyOptions.Rules != nil { - body["rules"] = createLoadBalancerListenerPolicyOptions.Rules + if createIkePolicyOptions.IkeVersion != nil { + body["ike_version"] = createIkePolicyOptions.IkeVersion } - if createLoadBalancerListenerPolicyOptions.Target != nil { - body["target"] = createLoadBalancerListenerPolicyOptions.Target + if createIkePolicyOptions.KeyLifetime != nil { + body["key_lifetime"] = createIkePolicyOptions.KeyLifetime + } + if createIkePolicyOptions.Name != nil { + body["name"] = createIkePolicyOptions.Name + } + if createIkePolicyOptions.ResourceGroup != nil { + body["resource_group"] = createIkePolicyOptions.ResourceGroup } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -30180,12 +31615,12 @@ func (vpc *VpcV1) CreateLoadBalancerListenerPolicyWithContext(ctx context.Contex var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_load_balancer_listener_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_ike_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30196,48 +31631,47 @@ func (vpc *VpcV1) CreateLoadBalancerListenerPolicyWithContext(ctx context.Contex return } -// DeleteLoadBalancerListenerPolicy : Delete a load balancer listener policy -// Deletes a policy of the load balancer listener. This operation cannot be reversed. -func (vpc *VpcV1) DeleteLoadBalancerListenerPolicy(deleteLoadBalancerListenerPolicyOptions *DeleteLoadBalancerListenerPolicyOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteLoadBalancerListenerPolicyWithContext(context.Background(), deleteLoadBalancerListenerPolicyOptions) +// DeleteIkePolicy : Delete an IKE policy +// This request deletes an IKE policy. This operation cannot be reversed. For this request to succeed, there must not be +// any VPN gateway connections using this policy. +func (vpc *VpcV1) DeleteIkePolicy(deleteIkePolicyOptions *DeleteIkePolicyOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteIkePolicyWithContext(context.Background(), deleteIkePolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteLoadBalancerListenerPolicyWithContext is an alternate form of the DeleteLoadBalancerListenerPolicy method which supports a Context parameter -func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyWithContext(ctx context.Context, deleteLoadBalancerListenerPolicyOptions *DeleteLoadBalancerListenerPolicyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteLoadBalancerListenerPolicyOptions, "deleteLoadBalancerListenerPolicyOptions cannot be nil") +// DeleteIkePolicyWithContext is an alternate form of the DeleteIkePolicy method which supports a Context parameter +func (vpc *VpcV1) DeleteIkePolicyWithContext(ctx context.Context, deleteIkePolicyOptions *DeleteIkePolicyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteIkePolicyOptions, "deleteIkePolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteLoadBalancerListenerPolicyOptions, "deleteLoadBalancerListenerPolicyOptions") + err = core.ValidateStruct(deleteIkePolicyOptions, "deleteIkePolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *deleteLoadBalancerListenerPolicyOptions.LoadBalancerID, - "listener_id": *deleteLoadBalancerListenerPolicyOptions.ListenerID, - "id": *deleteLoadBalancerListenerPolicyOptions.ID, + "id": *deleteIkePolicyOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteLoadBalancerListenerPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteIkePolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerListenerPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteIkePolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -30252,7 +31686,7 @@ func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyWithContext(ctx context.Contex response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_load_balancer_listener_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_ike_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -30260,48 +31694,46 @@ func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyWithContext(ctx context.Contex return } -// GetLoadBalancerListenerPolicy : Retrieve a load balancer listener policy -// Retrieve a single policy specified by the identifier in the URL path. -func (vpc *VpcV1) GetLoadBalancerListenerPolicy(getLoadBalancerListenerPolicyOptions *GetLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetLoadBalancerListenerPolicyWithContext(context.Background(), getLoadBalancerListenerPolicyOptions) +// GetIkePolicy : Retrieve an IKE policy +// This request retrieves a single IKE policy specified by the identifier in the URL. +func (vpc *VpcV1) GetIkePolicy(getIkePolicyOptions *GetIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetIkePolicyWithContext(context.Background(), getIkePolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLoadBalancerListenerPolicyWithContext is an alternate form of the GetLoadBalancerListenerPolicy method which supports a Context parameter -func (vpc *VpcV1) GetLoadBalancerListenerPolicyWithContext(ctx context.Context, getLoadBalancerListenerPolicyOptions *GetLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLoadBalancerListenerPolicyOptions, "getLoadBalancerListenerPolicyOptions cannot be nil") +// GetIkePolicyWithContext is an alternate form of the GetIkePolicy method which supports a Context parameter +func (vpc *VpcV1) GetIkePolicyWithContext(ctx context.Context, getIkePolicyOptions *GetIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getIkePolicyOptions, "getIkePolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLoadBalancerListenerPolicyOptions, "getLoadBalancerListenerPolicyOptions") + err = core.ValidateStruct(getIkePolicyOptions, "getIkePolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *getLoadBalancerListenerPolicyOptions.LoadBalancerID, - "listener_id": *getLoadBalancerListenerPolicyOptions.ListenerID, - "id": *getLoadBalancerListenerPolicyOptions.ID, + "id": *getIkePolicyOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLoadBalancerListenerPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetIkePolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerListenerPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getIkePolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -30318,12 +31750,12 @@ func (vpc *VpcV1) GetLoadBalancerListenerPolicyWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_load_balancer_listener_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_ike_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30334,49 +31766,46 @@ func (vpc *VpcV1) GetLoadBalancerListenerPolicyWithContext(ctx context.Context, return } -// UpdateLoadBalancerListenerPolicy : Update a load balancer listener policy -// This request updates a load balancer listener policy with the information in a provided policy patch. The policy -// patch object is structured in the same way as a retrieved policy and contains only the information to be updated. -func (vpc *VpcV1) UpdateLoadBalancerListenerPolicy(updateLoadBalancerListenerPolicyOptions *UpdateLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateLoadBalancerListenerPolicyWithContext(context.Background(), updateLoadBalancerListenerPolicyOptions) +// UpdateIkePolicy : Update an IKE policy +// This request updates the properties of an existing IKE policy. +func (vpc *VpcV1) UpdateIkePolicy(updateIkePolicyOptions *UpdateIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateIkePolicyWithContext(context.Background(), updateIkePolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateLoadBalancerListenerPolicyWithContext is an alternate form of the UpdateLoadBalancerListenerPolicy method which supports a Context parameter -func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyWithContext(ctx context.Context, updateLoadBalancerListenerPolicyOptions *UpdateLoadBalancerListenerPolicyOptions) (result *LoadBalancerListenerPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateLoadBalancerListenerPolicyOptions, "updateLoadBalancerListenerPolicyOptions cannot be nil") +// UpdateIkePolicyWithContext is an alternate form of the UpdateIkePolicy method which supports a Context parameter +func (vpc *VpcV1) UpdateIkePolicyWithContext(ctx context.Context, updateIkePolicyOptions *UpdateIkePolicyOptions) (result *IkePolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateIkePolicyOptions, "updateIkePolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateLoadBalancerListenerPolicyOptions, "updateLoadBalancerListenerPolicyOptions") + err = core.ValidateStruct(updateIkePolicyOptions, "updateIkePolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *updateLoadBalancerListenerPolicyOptions.LoadBalancerID, - "listener_id": *updateLoadBalancerListenerPolicyOptions.ListenerID, - "id": *updateLoadBalancerListenerPolicyOptions.ID, + "id": *updateIkePolicyOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateLoadBalancerListenerPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateIkePolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerListenerPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateIkePolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -30385,7 +31814,7 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyWithContext(ctx context.Contex builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateLoadBalancerListenerPolicyOptions.LoadBalancerListenerPolicyPatch) + _, err = builder.SetBodyContentJSON(updateIkePolicyOptions.IkePolicyPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -30400,12 +31829,12 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyWithContext(ctx context.Contex var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_load_balancer_listener_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_ike_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30416,54 +31845,127 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyWithContext(ctx context.Contex return } -// ListLoadBalancerListenerPolicyRules : List rules of a load balancer listener policy -// This request lists rules of a load balancer listener policy. -func (vpc *VpcV1) ListLoadBalancerListenerPolicyRules(listLoadBalancerListenerPolicyRulesOptions *ListLoadBalancerListenerPolicyRulesOptions) (result *LoadBalancerListenerPolicyRuleCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListLoadBalancerListenerPolicyRulesWithContext(context.Background(), listLoadBalancerListenerPolicyRulesOptions) +// ListIkePolicyConnections : List VPN gateway connections that use a specified IKE policy +// This request lists VPN gateway connections that use an IKE policy. +func (vpc *VpcV1) ListIkePolicyConnections(listIkePolicyConnectionsOptions *ListIkePolicyConnectionsOptions) (result *IkePolicyConnectionCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListIkePolicyConnectionsWithContext(context.Background(), listIkePolicyConnectionsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListLoadBalancerListenerPolicyRulesWithContext is an alternate form of the ListLoadBalancerListenerPolicyRules method which supports a Context parameter -func (vpc *VpcV1) ListLoadBalancerListenerPolicyRulesWithContext(ctx context.Context, listLoadBalancerListenerPolicyRulesOptions *ListLoadBalancerListenerPolicyRulesOptions) (result *LoadBalancerListenerPolicyRuleCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listLoadBalancerListenerPolicyRulesOptions, "listLoadBalancerListenerPolicyRulesOptions cannot be nil") +// ListIkePolicyConnectionsWithContext is an alternate form of the ListIkePolicyConnections method which supports a Context parameter +func (vpc *VpcV1) ListIkePolicyConnectionsWithContext(ctx context.Context, listIkePolicyConnectionsOptions *ListIkePolicyConnectionsOptions) (result *IkePolicyConnectionCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listIkePolicyConnectionsOptions, "listIkePolicyConnectionsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listLoadBalancerListenerPolicyRulesOptions, "listLoadBalancerListenerPolicyRulesOptions") + err = core.ValidateStruct(listIkePolicyConnectionsOptions, "listIkePolicyConnectionsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *listLoadBalancerListenerPolicyRulesOptions.LoadBalancerID, - "listener_id": *listLoadBalancerListenerPolicyRulesOptions.ListenerID, - "policy_id": *listLoadBalancerListenerPolicyRulesOptions.PolicyID, + "id": *listIkePolicyConnectionsOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ike_policies/{id}/connections`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listLoadBalancerListenerPolicyRulesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListIkePolicyConnections") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerListenerPolicyRules") + for headerName, headerValue := range listIkePolicyConnectionsOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listIkePolicyConnectionsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listIkePolicyConnectionsOptions.Start)) + } + if listIkePolicyConnectionsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listIkePolicyConnectionsOptions.Limit)) + } + + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return + } + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "list_ike_policy_connections", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return + } + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIkePolicyConnectionCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result + } + + return +} + +// ListIpsecPolicies : List IPsec policies +// This request lists IPsec policies in the region. +func (vpc *VpcV1) ListIpsecPolicies(listIpsecPoliciesOptions *ListIpsecPoliciesOptions) (result *IPsecPolicyCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListIpsecPoliciesWithContext(context.Background(), listIpsecPoliciesOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ListIpsecPoliciesWithContext is an alternate form of the ListIpsecPolicies method which supports a Context parameter +func (vpc *VpcV1) ListIpsecPoliciesWithContext(ctx context.Context, listIpsecPoliciesOptions *ListIpsecPoliciesOptions) (result *IPsecPolicyCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listIpsecPoliciesOptions, "listIpsecPoliciesOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return + } + + builder := core.NewRequestBuilder(core.GET) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return + } + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListIpsecPolicies") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } + + for headerName, headerValue := range listIpsecPoliciesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listIpsecPoliciesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listIpsecPoliciesOptions.Start)) + } + if listIpsecPoliciesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listIpsecPoliciesOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -30474,12 +31976,12 @@ func (vpc *VpcV1) ListLoadBalancerListenerPolicyRulesWithContext(ctx context.Con var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_load_balancer_listener_policy_rules", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_ipsec_policies", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyRuleCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicyCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30490,48 +31992,42 @@ func (vpc *VpcV1) ListLoadBalancerListenerPolicyRulesWithContext(ctx context.Con return } -// CreateLoadBalancerListenerPolicyRule : Create a rule for a load balancer listener policy -// Creates a new rule for the load balancer listener policy. -func (vpc *VpcV1) CreateLoadBalancerListenerPolicyRule(createLoadBalancerListenerPolicyRuleOptions *CreateLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateLoadBalancerListenerPolicyRuleWithContext(context.Background(), createLoadBalancerListenerPolicyRuleOptions) +// CreateIpsecPolicy : Create an IPsec policy +// This request creates a new IPsec policy. +func (vpc *VpcV1) CreateIpsecPolicy(createIpsecPolicyOptions *CreateIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateIpsecPolicyWithContext(context.Background(), createIpsecPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateLoadBalancerListenerPolicyRuleWithContext is an alternate form of the CreateLoadBalancerListenerPolicyRule method which supports a Context parameter -func (vpc *VpcV1) CreateLoadBalancerListenerPolicyRuleWithContext(ctx context.Context, createLoadBalancerListenerPolicyRuleOptions *CreateLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createLoadBalancerListenerPolicyRuleOptions, "createLoadBalancerListenerPolicyRuleOptions cannot be nil") +// CreateIpsecPolicyWithContext is an alternate form of the CreateIpsecPolicy method which supports a Context parameter +func (vpc *VpcV1) CreateIpsecPolicyWithContext(ctx context.Context, createIpsecPolicyOptions *CreateIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createIpsecPolicyOptions, "createIpsecPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createLoadBalancerListenerPolicyRuleOptions, "createLoadBalancerListenerPolicyRuleOptions") + err = core.ValidateStruct(createIpsecPolicyOptions, "createIpsecPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "load_balancer_id": *createLoadBalancerListenerPolicyRuleOptions.LoadBalancerID, - "listener_id": *createLoadBalancerListenerPolicyRuleOptions.ListenerID, - "policy_id": *createLoadBalancerListenerPolicyRuleOptions.PolicyID, - } - builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createLoadBalancerListenerPolicyRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateIpsecPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerListenerPolicyRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createIpsecPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -30541,17 +32037,23 @@ func (vpc *VpcV1) CreateLoadBalancerListenerPolicyRuleWithContext(ctx context.Co builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createLoadBalancerListenerPolicyRuleOptions.Condition != nil { - body["condition"] = createLoadBalancerListenerPolicyRuleOptions.Condition + if createIpsecPolicyOptions.AuthenticationAlgorithm != nil { + body["authentication_algorithm"] = createIpsecPolicyOptions.AuthenticationAlgorithm } - if createLoadBalancerListenerPolicyRuleOptions.Type != nil { - body["type"] = createLoadBalancerListenerPolicyRuleOptions.Type + if createIpsecPolicyOptions.EncryptionAlgorithm != nil { + body["encryption_algorithm"] = createIpsecPolicyOptions.EncryptionAlgorithm } - if createLoadBalancerListenerPolicyRuleOptions.Value != nil { - body["value"] = createLoadBalancerListenerPolicyRuleOptions.Value + if createIpsecPolicyOptions.Pfs != nil { + body["pfs"] = createIpsecPolicyOptions.Pfs } - if createLoadBalancerListenerPolicyRuleOptions.Field != nil { - body["field"] = createLoadBalancerListenerPolicyRuleOptions.Field + if createIpsecPolicyOptions.KeyLifetime != nil { + body["key_lifetime"] = createIpsecPolicyOptions.KeyLifetime + } + if createIpsecPolicyOptions.Name != nil { + body["name"] = createIpsecPolicyOptions.Name + } + if createIpsecPolicyOptions.ResourceGroup != nil { + body["resource_group"] = createIpsecPolicyOptions.ResourceGroup } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -30568,12 +32070,12 @@ func (vpc *VpcV1) CreateLoadBalancerListenerPolicyRuleWithContext(ctx context.Co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_load_balancer_listener_policy_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_ipsec_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyRule) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30584,49 +32086,47 @@ func (vpc *VpcV1) CreateLoadBalancerListenerPolicyRuleWithContext(ctx context.Co return } -// DeleteLoadBalancerListenerPolicyRule : Delete a load balancer listener policy rule -// Deletes a rule from the load balancer listener policy. This operation cannot be reversed. -func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyRule(deleteLoadBalancerListenerPolicyRuleOptions *DeleteLoadBalancerListenerPolicyRuleOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteLoadBalancerListenerPolicyRuleWithContext(context.Background(), deleteLoadBalancerListenerPolicyRuleOptions) +// DeleteIpsecPolicy : Delete an IPsec policy +// This request deletes an IPsec policy. This operation cannot be reversed. For this request to succeed, there must not +// be any VPN gateway connections using this policy. +func (vpc *VpcV1) DeleteIpsecPolicy(deleteIpsecPolicyOptions *DeleteIpsecPolicyOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteIpsecPolicyWithContext(context.Background(), deleteIpsecPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteLoadBalancerListenerPolicyRuleWithContext is an alternate form of the DeleteLoadBalancerListenerPolicyRule method which supports a Context parameter -func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyRuleWithContext(ctx context.Context, deleteLoadBalancerListenerPolicyRuleOptions *DeleteLoadBalancerListenerPolicyRuleOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteLoadBalancerListenerPolicyRuleOptions, "deleteLoadBalancerListenerPolicyRuleOptions cannot be nil") +// DeleteIpsecPolicyWithContext is an alternate form of the DeleteIpsecPolicy method which supports a Context parameter +func (vpc *VpcV1) DeleteIpsecPolicyWithContext(ctx context.Context, deleteIpsecPolicyOptions *DeleteIpsecPolicyOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteIpsecPolicyOptions, "deleteIpsecPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteLoadBalancerListenerPolicyRuleOptions, "deleteLoadBalancerListenerPolicyRuleOptions") + err = core.ValidateStruct(deleteIpsecPolicyOptions, "deleteIpsecPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *deleteLoadBalancerListenerPolicyRuleOptions.LoadBalancerID, - "listener_id": *deleteLoadBalancerListenerPolicyRuleOptions.ListenerID, - "policy_id": *deleteLoadBalancerListenerPolicyRuleOptions.PolicyID, - "id": *deleteLoadBalancerListenerPolicyRuleOptions.ID, + "id": *deleteIpsecPolicyOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteLoadBalancerListenerPolicyRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteIpsecPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerListenerPolicyRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteIpsecPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -30641,7 +32141,7 @@ func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyRuleWithContext(ctx context.Co response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_load_balancer_listener_policy_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_ipsec_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -30649,49 +32149,46 @@ func (vpc *VpcV1) DeleteLoadBalancerListenerPolicyRuleWithContext(ctx context.Co return } -// GetLoadBalancerListenerPolicyRule : Retrieve a load balancer listener policy rule -// Retrieves a single rule specified by the identifier in the URL path. -func (vpc *VpcV1) GetLoadBalancerListenerPolicyRule(getLoadBalancerListenerPolicyRuleOptions *GetLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetLoadBalancerListenerPolicyRuleWithContext(context.Background(), getLoadBalancerListenerPolicyRuleOptions) +// GetIpsecPolicy : Retrieve an IPsec policy +// This request retrieves a single IPsec policy specified by the identifier in the URL. +func (vpc *VpcV1) GetIpsecPolicy(getIpsecPolicyOptions *GetIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetIpsecPolicyWithContext(context.Background(), getIpsecPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLoadBalancerListenerPolicyRuleWithContext is an alternate form of the GetLoadBalancerListenerPolicyRule method which supports a Context parameter -func (vpc *VpcV1) GetLoadBalancerListenerPolicyRuleWithContext(ctx context.Context, getLoadBalancerListenerPolicyRuleOptions *GetLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLoadBalancerListenerPolicyRuleOptions, "getLoadBalancerListenerPolicyRuleOptions cannot be nil") +// GetIpsecPolicyWithContext is an alternate form of the GetIpsecPolicy method which supports a Context parameter +func (vpc *VpcV1) GetIpsecPolicyWithContext(ctx context.Context, getIpsecPolicyOptions *GetIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getIpsecPolicyOptions, "getIpsecPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLoadBalancerListenerPolicyRuleOptions, "getLoadBalancerListenerPolicyRuleOptions") + err = core.ValidateStruct(getIpsecPolicyOptions, "getIpsecPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *getLoadBalancerListenerPolicyRuleOptions.LoadBalancerID, - "listener_id": *getLoadBalancerListenerPolicyRuleOptions.ListenerID, - "policy_id": *getLoadBalancerListenerPolicyRuleOptions.PolicyID, - "id": *getLoadBalancerListenerPolicyRuleOptions.ID, + "id": *getIpsecPolicyOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLoadBalancerListenerPolicyRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetIpsecPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerListenerPolicyRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getIpsecPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -30708,12 +32205,12 @@ func (vpc *VpcV1) GetLoadBalancerListenerPolicyRuleWithContext(ctx context.Conte var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_load_balancer_listener_policy_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_ipsec_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyRule) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30724,49 +32221,46 @@ func (vpc *VpcV1) GetLoadBalancerListenerPolicyRuleWithContext(ctx context.Conte return } -// UpdateLoadBalancerListenerPolicyRule : Update a load balancer listener policy rule -// Updates a rule of the load balancer listener policy. -func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyRule(updateLoadBalancerListenerPolicyRuleOptions *UpdateLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateLoadBalancerListenerPolicyRuleWithContext(context.Background(), updateLoadBalancerListenerPolicyRuleOptions) +// UpdateIpsecPolicy : Update an IPsec policy +// This request updates the properties of an existing IPsec policy. +func (vpc *VpcV1) UpdateIpsecPolicy(updateIpsecPolicyOptions *UpdateIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateIpsecPolicyWithContext(context.Background(), updateIpsecPolicyOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateLoadBalancerListenerPolicyRuleWithContext is an alternate form of the UpdateLoadBalancerListenerPolicyRule method which supports a Context parameter -func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyRuleWithContext(ctx context.Context, updateLoadBalancerListenerPolicyRuleOptions *UpdateLoadBalancerListenerPolicyRuleOptions) (result *LoadBalancerListenerPolicyRule, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateLoadBalancerListenerPolicyRuleOptions, "updateLoadBalancerListenerPolicyRuleOptions cannot be nil") +// UpdateIpsecPolicyWithContext is an alternate form of the UpdateIpsecPolicy method which supports a Context parameter +func (vpc *VpcV1) UpdateIpsecPolicyWithContext(ctx context.Context, updateIpsecPolicyOptions *UpdateIpsecPolicyOptions) (result *IPsecPolicy, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateIpsecPolicyOptions, "updateIpsecPolicyOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateLoadBalancerListenerPolicyRuleOptions, "updateLoadBalancerListenerPolicyRuleOptions") + err = core.ValidateStruct(updateIpsecPolicyOptions, "updateIpsecPolicyOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *updateLoadBalancerListenerPolicyRuleOptions.LoadBalancerID, - "listener_id": *updateLoadBalancerListenerPolicyRuleOptions.ListenerID, - "policy_id": *updateLoadBalancerListenerPolicyRuleOptions.PolicyID, - "id": *updateLoadBalancerListenerPolicyRuleOptions.ID, + "id": *updateIpsecPolicyOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/listeners/{listener_id}/policies/{policy_id}/rules/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateLoadBalancerListenerPolicyRuleOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateIpsecPolicy") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerListenerPolicyRule") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateIpsecPolicyOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -30775,7 +32269,7 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyRuleWithContext(ctx context.Co builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateLoadBalancerListenerPolicyRuleOptions.LoadBalancerListenerPolicyRulePatch) + _, err = builder.SetBodyContentJSON(updateIpsecPolicyOptions.IPsecPolicyPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -30790,12 +32284,12 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyRuleWithContext(ctx context.Co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_load_balancer_listener_policy_rule", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_ipsec_policy", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerListenerPolicyRule) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicy) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30806,52 +32300,58 @@ func (vpc *VpcV1) UpdateLoadBalancerListenerPolicyRuleWithContext(ctx context.Co return } -// ListLoadBalancerPools : List pools of a load balancer -// This request lists pools of a load balancer. -func (vpc *VpcV1) ListLoadBalancerPools(listLoadBalancerPoolsOptions *ListLoadBalancerPoolsOptions) (result *LoadBalancerPoolCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListLoadBalancerPoolsWithContext(context.Background(), listLoadBalancerPoolsOptions) +// ListIpsecPolicyConnections : List VPN gateway connections that use a specified IPsec policy +// This request lists VPN gateway connections that use an IPsec policy. +func (vpc *VpcV1) ListIpsecPolicyConnections(listIpsecPolicyConnectionsOptions *ListIpsecPolicyConnectionsOptions) (result *IPsecPolicyConnectionCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListIpsecPolicyConnectionsWithContext(context.Background(), listIpsecPolicyConnectionsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListLoadBalancerPoolsWithContext is an alternate form of the ListLoadBalancerPools method which supports a Context parameter -func (vpc *VpcV1) ListLoadBalancerPoolsWithContext(ctx context.Context, listLoadBalancerPoolsOptions *ListLoadBalancerPoolsOptions) (result *LoadBalancerPoolCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listLoadBalancerPoolsOptions, "listLoadBalancerPoolsOptions cannot be nil") +// ListIpsecPolicyConnectionsWithContext is an alternate form of the ListIpsecPolicyConnections method which supports a Context parameter +func (vpc *VpcV1) ListIpsecPolicyConnectionsWithContext(ctx context.Context, listIpsecPolicyConnectionsOptions *ListIpsecPolicyConnectionsOptions) (result *IPsecPolicyConnectionCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listIpsecPolicyConnectionsOptions, "listIpsecPolicyConnectionsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listLoadBalancerPoolsOptions, "listLoadBalancerPoolsOptions") + err = core.ValidateStruct(listIpsecPolicyConnectionsOptions, "listIpsecPolicyConnectionsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *listLoadBalancerPoolsOptions.LoadBalancerID, + "id": *listIpsecPolicyConnectionsOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/ipsec_policies/{id}/connections`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listLoadBalancerPoolsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListIpsecPolicyConnections") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerPools") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listIpsecPolicyConnectionsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listIpsecPolicyConnectionsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listIpsecPolicyConnectionsOptions.Start)) + } + if listIpsecPolicyConnectionsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listIpsecPolicyConnectionsOptions.Limit)) + } request, err := builder.Build() if err != nil { @@ -30862,12 +32362,12 @@ func (vpc *VpcV1) ListLoadBalancerPoolsWithContext(ctx context.Context, listLoad var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_load_balancer_pools", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_ipsec_policy_connections", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalIPsecPolicyConnectionCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30878,80 +32378,129 @@ func (vpc *VpcV1) ListLoadBalancerPoolsWithContext(ctx context.Context, listLoad return } -// CreateLoadBalancerPool : Create a load balancer pool -// This request creates a new pool from a pool prototype object. -func (vpc *VpcV1) CreateLoadBalancerPool(createLoadBalancerPoolOptions *CreateLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateLoadBalancerPoolWithContext(context.Background(), createLoadBalancerPoolOptions) +// ListVPNGateways : List VPN gateways +// This request lists VPN gateways in the region. +func (vpc *VpcV1) ListVPNGateways(listVPNGatewaysOptions *ListVPNGatewaysOptions) (result *VPNGatewayCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPNGatewaysWithContext(context.Background(), listVPNGatewaysOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateLoadBalancerPoolWithContext is an alternate form of the CreateLoadBalancerPool method which supports a Context parameter -func (vpc *VpcV1) CreateLoadBalancerPoolWithContext(ctx context.Context, createLoadBalancerPoolOptions *CreateLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createLoadBalancerPoolOptions, "createLoadBalancerPoolOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(createLoadBalancerPoolOptions, "createLoadBalancerPoolOptions") +// ListVPNGatewaysWithContext is an alternate form of the ListVPNGateways method which supports a Context parameter +func (vpc *VpcV1) ListVPNGatewaysWithContext(ctx context.Context, listVPNGatewaysOptions *ListVPNGatewaysOptions) (result *VPNGatewayCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listVPNGatewaysOptions, "listVPNGatewaysOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - pathParamsMap := map[string]string{ - "load_balancer_id": *createLoadBalancerPoolOptions.LoadBalancerID, - } - - builder := core.NewRequestBuilder(core.POST) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createLoadBalancerPoolOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNGateways") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerPool") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPNGatewaysOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listVPNGatewaysOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPNGatewaysOptions.Start)) + } + if listVPNGatewaysOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPNGatewaysOptions.Limit)) + } + if listVPNGatewaysOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listVPNGatewaysOptions.ResourceGroupID)) + } + if listVPNGatewaysOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listVPNGatewaysOptions.Sort)) + } + if listVPNGatewaysOptions.Mode != nil { + builder.AddQuery("mode", fmt.Sprint(*listVPNGatewaysOptions.Mode)) + } - body := make(map[string]interface{}) - if createLoadBalancerPoolOptions.Algorithm != nil { - body["algorithm"] = createLoadBalancerPoolOptions.Algorithm + request, err := builder.Build() + if err != nil { + err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) + return } - if createLoadBalancerPoolOptions.HealthMonitor != nil { - body["health_monitor"] = createLoadBalancerPoolOptions.HealthMonitor + + var rawResponse map[string]json.RawMessage + response, err = vpc.Service.Request(request, &rawResponse) + if err != nil { + core.EnrichHTTPProblem(err, "list_vpn_gateways", getServiceComponentInfo()) + err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) + return } - if createLoadBalancerPoolOptions.Protocol != nil { - body["protocol"] = createLoadBalancerPoolOptions.Protocol + if rawResponse != nil { + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayCollection) + if err != nil { + err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) + return + } + response.Result = result } - if createLoadBalancerPoolOptions.FailsafePolicy != nil { - body["failsafe_policy"] = createLoadBalancerPoolOptions.FailsafePolicy + + return +} + +// CreateVPNGateway : Create a VPN gateway +// This request creates a new VPN gateway. +func (vpc *VpcV1) CreateVPNGateway(createVPNGatewayOptions *CreateVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPNGatewayWithContext(context.Background(), createVPNGatewayOptions) + err = core.RepurposeSDKProblem(err, "") + return +} + +// CreateVPNGatewayWithContext is an alternate form of the CreateVPNGateway method which supports a Context parameter +func (vpc *VpcV1) CreateVPNGatewayWithContext(ctx context.Context, createVPNGatewayOptions *CreateVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVPNGatewayOptions, "createVPNGatewayOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return } - if createLoadBalancerPoolOptions.Members != nil { - body["members"] = createLoadBalancerPoolOptions.Members + err = core.ValidateStruct(createVPNGatewayOptions, "createVPNGatewayOptions") + if err != nil { + err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) + return } - if createLoadBalancerPoolOptions.Name != nil { - body["name"] = createLoadBalancerPoolOptions.Name + + builder := core.NewRequestBuilder(core.POST) + builder = builder.WithContext(ctx) + builder.EnableGzipCompression = vpc.GetEnableGzipCompression() + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways`, nil) + if err != nil { + err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) + return } - if createLoadBalancerPoolOptions.ProxyProtocol != nil { - body["proxy_protocol"] = createLoadBalancerPoolOptions.ProxyProtocol + + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPNGateway") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) } - if createLoadBalancerPoolOptions.SessionPersistence != nil { - body["session_persistence"] = createLoadBalancerPoolOptions.SessionPersistence + + for headerName, headerValue := range createVPNGatewayOptions.Headers { + builder.AddHeader(headerName, headerValue) } - _, err = builder.SetBodyContentJSON(body) + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + builder.AddQuery("version", fmt.Sprint(*vpc.Version)) + builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + + _, err = builder.SetBodyContentJSON(createVPNGatewayOptions.VPNGatewayPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -30966,12 +32515,12 @@ func (vpc *VpcV1) CreateLoadBalancerPoolWithContext(ctx context.Context, createL var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_load_balancer_pool", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpn_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPool) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -30982,48 +32531,48 @@ func (vpc *VpcV1) CreateLoadBalancerPoolWithContext(ctx context.Context, createL return } -// DeleteLoadBalancerPool : Delete a load balancer pool -// This request deletes a load balancer pool. This operation cannot be reversed. The pool must not currently be the -// default pool for any listener in the load balancer, nor be the target pool in the failsafe policy for any other pool. -func (vpc *VpcV1) DeleteLoadBalancerPool(deleteLoadBalancerPoolOptions *DeleteLoadBalancerPoolOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteLoadBalancerPoolWithContext(context.Background(), deleteLoadBalancerPoolOptions) +// DeleteVPNGateway : Delete a VPN gateway +// This request deletes a VPN gateway. This operation cannot be reversed. For this request to succeed, the VPN gateway +// must not have a `status` of `pending`, and there must not be any VPC routes using the VPN gateway's connections as a +// next hop. +func (vpc *VpcV1) DeleteVPNGateway(deleteVPNGatewayOptions *DeleteVPNGatewayOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPNGatewayWithContext(context.Background(), deleteVPNGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteLoadBalancerPoolWithContext is an alternate form of the DeleteLoadBalancerPool method which supports a Context parameter -func (vpc *VpcV1) DeleteLoadBalancerPoolWithContext(ctx context.Context, deleteLoadBalancerPoolOptions *DeleteLoadBalancerPoolOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteLoadBalancerPoolOptions, "deleteLoadBalancerPoolOptions cannot be nil") +// DeleteVPNGatewayWithContext is an alternate form of the DeleteVPNGateway method which supports a Context parameter +func (vpc *VpcV1) DeleteVPNGatewayWithContext(ctx context.Context, deleteVPNGatewayOptions *DeleteVPNGatewayOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPNGatewayOptions, "deleteVPNGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteLoadBalancerPoolOptions, "deleteLoadBalancerPoolOptions") + err = core.ValidateStruct(deleteVPNGatewayOptions, "deleteVPNGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *deleteLoadBalancerPoolOptions.LoadBalancerID, - "id": *deleteLoadBalancerPoolOptions.ID, + "id": *deleteVPNGatewayOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteLoadBalancerPoolOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerPool") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPNGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -31038,7 +32587,7 @@ func (vpc *VpcV1) DeleteLoadBalancerPoolWithContext(ctx context.Context, deleteL response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_load_balancer_pool", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpn_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -31046,47 +32595,46 @@ func (vpc *VpcV1) DeleteLoadBalancerPoolWithContext(ctx context.Context, deleteL return } -// GetLoadBalancerPool : Retrieve a load balancer pool -// This request retrieves a single pool specified by the identifier in the URL path. -func (vpc *VpcV1) GetLoadBalancerPool(getLoadBalancerPoolOptions *GetLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetLoadBalancerPoolWithContext(context.Background(), getLoadBalancerPoolOptions) +// GetVPNGateway : Retrieve a VPN gateway +// This request retrieves a single VPN gateway specified by the identifier in the URL. +func (vpc *VpcV1) GetVPNGateway(getVPNGatewayOptions *GetVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPNGatewayWithContext(context.Background(), getVPNGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLoadBalancerPoolWithContext is an alternate form of the GetLoadBalancerPool method which supports a Context parameter -func (vpc *VpcV1) GetLoadBalancerPoolWithContext(ctx context.Context, getLoadBalancerPoolOptions *GetLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLoadBalancerPoolOptions, "getLoadBalancerPoolOptions cannot be nil") +// GetVPNGatewayWithContext is an alternate form of the GetVPNGateway method which supports a Context parameter +func (vpc *VpcV1) GetVPNGatewayWithContext(ctx context.Context, getVPNGatewayOptions *GetVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPNGatewayOptions, "getVPNGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLoadBalancerPoolOptions, "getLoadBalancerPoolOptions") + err = core.ValidateStruct(getVPNGatewayOptions, "getVPNGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *getLoadBalancerPoolOptions.LoadBalancerID, - "id": *getLoadBalancerPoolOptions.ID, + "id": *getVPNGatewayOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLoadBalancerPoolOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerPool") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPNGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -31103,12 +32651,12 @@ func (vpc *VpcV1) GetLoadBalancerPoolWithContext(ctx context.Context, getLoadBal var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_load_balancer_pool", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpn_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPool) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -31119,47 +32667,46 @@ func (vpc *VpcV1) GetLoadBalancerPoolWithContext(ctx context.Context, getLoadBal return } -// UpdateLoadBalancerPool : Update a load balancer pool -// This request updates a load balancer pool from a pool patch. -func (vpc *VpcV1) UpdateLoadBalancerPool(updateLoadBalancerPoolOptions *UpdateLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateLoadBalancerPoolWithContext(context.Background(), updateLoadBalancerPoolOptions) +// UpdateVPNGateway : Update a VPN gateway +// This request updates the properties of an existing VPN gateway. +func (vpc *VpcV1) UpdateVPNGateway(updateVPNGatewayOptions *UpdateVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPNGatewayWithContext(context.Background(), updateVPNGatewayOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateLoadBalancerPoolWithContext is an alternate form of the UpdateLoadBalancerPool method which supports a Context parameter -func (vpc *VpcV1) UpdateLoadBalancerPoolWithContext(ctx context.Context, updateLoadBalancerPoolOptions *UpdateLoadBalancerPoolOptions) (result *LoadBalancerPool, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateLoadBalancerPoolOptions, "updateLoadBalancerPoolOptions cannot be nil") +// UpdateVPNGatewayWithContext is an alternate form of the UpdateVPNGateway method which supports a Context parameter +func (vpc *VpcV1) UpdateVPNGatewayWithContext(ctx context.Context, updateVPNGatewayOptions *UpdateVPNGatewayOptions) (result VPNGatewayIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPNGatewayOptions, "updateVPNGatewayOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateLoadBalancerPoolOptions, "updateLoadBalancerPoolOptions") + err = core.ValidateStruct(updateVPNGatewayOptions, "updateVPNGatewayOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *updateLoadBalancerPoolOptions.LoadBalancerID, - "id": *updateLoadBalancerPoolOptions.ID, + "id": *updateVPNGatewayOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateLoadBalancerPoolOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPNGateway") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerPool") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPNGatewayOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -31168,7 +32715,7 @@ func (vpc *VpcV1) UpdateLoadBalancerPoolWithContext(ctx context.Context, updateL builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateLoadBalancerPoolOptions.LoadBalancerPoolPatch) + _, err = builder.SetBodyContentJSON(updateVPNGatewayOptions.VPNGatewayPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -31183,12 +32730,12 @@ func (vpc *VpcV1) UpdateLoadBalancerPoolWithContext(ctx context.Context, updateL var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_load_balancer_pool", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpn_gateway", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPool) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGateway) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -31199,53 +32746,61 @@ func (vpc *VpcV1) UpdateLoadBalancerPoolWithContext(ctx context.Context, updateL return } -// ListLoadBalancerPoolMembers : List members of a load balancer pool -// This request lists members of a load balancer pool. -func (vpc *VpcV1) ListLoadBalancerPoolMembers(listLoadBalancerPoolMembersOptions *ListLoadBalancerPoolMembersOptions) (result *LoadBalancerPoolMemberCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListLoadBalancerPoolMembersWithContext(context.Background(), listLoadBalancerPoolMembersOptions) +// ListVPNGatewayConnections : List connections of a VPN gateway +// This request lists connections of a VPN gateway. +func (vpc *VpcV1) ListVPNGatewayConnections(listVPNGatewayConnectionsOptions *ListVPNGatewayConnectionsOptions) (result *VPNGatewayConnectionCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPNGatewayConnectionsWithContext(context.Background(), listVPNGatewayConnectionsOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListLoadBalancerPoolMembersWithContext is an alternate form of the ListLoadBalancerPoolMembers method which supports a Context parameter -func (vpc *VpcV1) ListLoadBalancerPoolMembersWithContext(ctx context.Context, listLoadBalancerPoolMembersOptions *ListLoadBalancerPoolMembersOptions) (result *LoadBalancerPoolMemberCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listLoadBalancerPoolMembersOptions, "listLoadBalancerPoolMembersOptions cannot be nil") +// ListVPNGatewayConnectionsWithContext is an alternate form of the ListVPNGatewayConnections method which supports a Context parameter +func (vpc *VpcV1) ListVPNGatewayConnectionsWithContext(ctx context.Context, listVPNGatewayConnectionsOptions *ListVPNGatewayConnectionsOptions) (result *VPNGatewayConnectionCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPNGatewayConnectionsOptions, "listVPNGatewayConnectionsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listLoadBalancerPoolMembersOptions, "listLoadBalancerPoolMembersOptions") + err = core.ValidateStruct(listVPNGatewayConnectionsOptions, "listVPNGatewayConnectionsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *listLoadBalancerPoolMembersOptions.LoadBalancerID, - "pool_id": *listLoadBalancerPoolMembersOptions.PoolID, + "vpn_gateway_id": *listVPNGatewayConnectionsOptions.VPNGatewayID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listLoadBalancerPoolMembersOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNGatewayConnections") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListLoadBalancerPoolMembers") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPNGatewayConnectionsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) + if listVPNGatewayConnectionsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPNGatewayConnectionsOptions.Start)) + } + if listVPNGatewayConnectionsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPNGatewayConnectionsOptions.Limit)) + } + if listVPNGatewayConnectionsOptions.Status != nil { + builder.AddQuery("status", fmt.Sprint(*listVPNGatewayConnectionsOptions.Status)) + } request, err := builder.Build() if err != nil { @@ -31256,12 +32811,12 @@ func (vpc *VpcV1) ListLoadBalancerPoolMembersWithContext(ctx context.Context, li var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_load_balancer_pool_members", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpn_gateway_connections", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMemberCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnectionCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -31272,140 +32827,46 @@ func (vpc *VpcV1) ListLoadBalancerPoolMembersWithContext(ctx context.Context, li return } -// CreateLoadBalancerPoolMember : Create a member in a load balancer pool -// This request creates a new member and adds the member to the pool. -// -// The pool must not already have a member targeting a load balancer. -func (vpc *VpcV1) CreateLoadBalancerPoolMember(createLoadBalancerPoolMemberOptions *CreateLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateLoadBalancerPoolMemberWithContext(context.Background(), createLoadBalancerPoolMemberOptions) +// CreateVPNGatewayConnection : Create a connection for a VPN gateway +// This request creates a new VPN gateway connection. +func (vpc *VpcV1) CreateVPNGatewayConnection(createVPNGatewayConnectionOptions *CreateVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPNGatewayConnectionWithContext(context.Background(), createVPNGatewayConnectionOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateLoadBalancerPoolMemberWithContext is an alternate form of the CreateLoadBalancerPoolMember method which supports a Context parameter -func (vpc *VpcV1) CreateLoadBalancerPoolMemberWithContext(ctx context.Context, createLoadBalancerPoolMemberOptions *CreateLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createLoadBalancerPoolMemberOptions, "createLoadBalancerPoolMemberOptions cannot be nil") +// CreateVPNGatewayConnectionWithContext is an alternate form of the CreateVPNGatewayConnection method which supports a Context parameter +func (vpc *VpcV1) CreateVPNGatewayConnectionWithContext(ctx context.Context, createVPNGatewayConnectionOptions *CreateVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVPNGatewayConnectionOptions, "createVPNGatewayConnectionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createLoadBalancerPoolMemberOptions, "createLoadBalancerPoolMemberOptions") + err = core.ValidateStruct(createVPNGatewayConnectionOptions, "createVPNGatewayConnectionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *createLoadBalancerPoolMemberOptions.LoadBalancerID, - "pool_id": *createLoadBalancerPoolMemberOptions.PoolID, + "vpn_gateway_id": *createVPNGatewayConnectionOptions.VPNGatewayID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createLoadBalancerPoolMemberOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateLoadBalancerPoolMember") + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPNGatewayConnection") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if createLoadBalancerPoolMemberOptions.Port != nil { - body["port"] = createLoadBalancerPoolMemberOptions.Port - } - if createLoadBalancerPoolMemberOptions.Target != nil { - body["target"] = createLoadBalancerPoolMemberOptions.Target - } - if createLoadBalancerPoolMemberOptions.Weight != nil { - body["weight"] = createLoadBalancerPoolMemberOptions.Weight - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) - if err != nil { - core.EnrichHTTPProblem(err, "create_load_balancer_pool_member", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMember) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } - - return -} - -// ReplaceLoadBalancerPoolMembers : Replace load balancer pool members -// This request replaces the existing members of the load balancer pool with new members created from the collection of -// member prototype objects. -func (vpc *VpcV1) ReplaceLoadBalancerPoolMembers(replaceLoadBalancerPoolMembersOptions *ReplaceLoadBalancerPoolMembersOptions) (result *LoadBalancerPoolMemberCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ReplaceLoadBalancerPoolMembersWithContext(context.Background(), replaceLoadBalancerPoolMembersOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// ReplaceLoadBalancerPoolMembersWithContext is an alternate form of the ReplaceLoadBalancerPoolMembers method which supports a Context parameter -func (vpc *VpcV1) ReplaceLoadBalancerPoolMembersWithContext(ctx context.Context, replaceLoadBalancerPoolMembersOptions *ReplaceLoadBalancerPoolMembersOptions) (result *LoadBalancerPoolMemberCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(replaceLoadBalancerPoolMembersOptions, "replaceLoadBalancerPoolMembersOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(replaceLoadBalancerPoolMembersOptions, "replaceLoadBalancerPoolMembersOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "load_balancer_id": *replaceLoadBalancerPoolMembersOptions.LoadBalancerID, - "pool_id": *replaceLoadBalancerPoolMembersOptions.PoolID, - } - - builder := core.NewRequestBuilder(core.PUT) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range replaceLoadBalancerPoolMembersOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ReplaceLoadBalancerPoolMembers") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPNGatewayConnectionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -31414,11 +32875,7 @@ func (vpc *VpcV1) ReplaceLoadBalancerPoolMembersWithContext(ctx context.Context, builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if replaceLoadBalancerPoolMembersOptions.Members != nil { - body["members"] = replaceLoadBalancerPoolMembersOptions.Members - } - _, err = builder.SetBodyContentJSON(body) + _, err = builder.SetBodyContentJSON(createVPNGatewayConnectionOptions.VPNGatewayConnectionPrototype) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -31433,12 +32890,12 @@ func (vpc *VpcV1) ReplaceLoadBalancerPoolMembersWithContext(ctx context.Context, var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "replace_load_balancer_pool_members", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpn_gateway_connection", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMemberCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -31449,48 +32906,48 @@ func (vpc *VpcV1) ReplaceLoadBalancerPoolMembersWithContext(ctx context.Context, return } -// DeleteLoadBalancerPoolMember : Delete a load balancer pool member -// This request deletes a member from the pool. This operation cannot be reversed. -func (vpc *VpcV1) DeleteLoadBalancerPoolMember(deleteLoadBalancerPoolMemberOptions *DeleteLoadBalancerPoolMemberOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteLoadBalancerPoolMemberWithContext(context.Background(), deleteLoadBalancerPoolMemberOptions) +// DeleteVPNGatewayConnection : Delete a VPN gateway connection +// This request deletes a VPN gateway connection. This operation cannot be reversed. For this request to succeed, there +// must not be VPC routes using this VPN connection as a next hop. +func (vpc *VpcV1) DeleteVPNGatewayConnection(deleteVPNGatewayConnectionOptions *DeleteVPNGatewayConnectionOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPNGatewayConnectionWithContext(context.Background(), deleteVPNGatewayConnectionOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteLoadBalancerPoolMemberWithContext is an alternate form of the DeleteLoadBalancerPoolMember method which supports a Context parameter -func (vpc *VpcV1) DeleteLoadBalancerPoolMemberWithContext(ctx context.Context, deleteLoadBalancerPoolMemberOptions *DeleteLoadBalancerPoolMemberOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteLoadBalancerPoolMemberOptions, "deleteLoadBalancerPoolMemberOptions cannot be nil") +// DeleteVPNGatewayConnectionWithContext is an alternate form of the DeleteVPNGatewayConnection method which supports a Context parameter +func (vpc *VpcV1) DeleteVPNGatewayConnectionWithContext(ctx context.Context, deleteVPNGatewayConnectionOptions *DeleteVPNGatewayConnectionOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPNGatewayConnectionOptions, "deleteVPNGatewayConnectionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteLoadBalancerPoolMemberOptions, "deleteLoadBalancerPoolMemberOptions") + err = core.ValidateStruct(deleteVPNGatewayConnectionOptions, "deleteVPNGatewayConnectionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *deleteLoadBalancerPoolMemberOptions.LoadBalancerID, - "pool_id": *deleteLoadBalancerPoolMemberOptions.PoolID, - "id": *deleteLoadBalancerPoolMemberOptions.ID, + "vpn_gateway_id": *deleteVPNGatewayConnectionOptions.VPNGatewayID, + "id": *deleteVPNGatewayConnectionOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteLoadBalancerPoolMemberOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNGatewayConnection") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteLoadBalancerPoolMember") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPNGatewayConnectionOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -31505,7 +32962,7 @@ func (vpc *VpcV1) DeleteLoadBalancerPoolMemberWithContext(ctx context.Context, d response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_load_balancer_pool_member", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpn_gateway_connection", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -31513,48 +32970,47 @@ func (vpc *VpcV1) DeleteLoadBalancerPoolMemberWithContext(ctx context.Context, d return } -// GetLoadBalancerPoolMember : Retrieve a load balancer pool member -// This request retrieves a single member specified by the identifier in the URL path. -func (vpc *VpcV1) GetLoadBalancerPoolMember(getLoadBalancerPoolMemberOptions *GetLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetLoadBalancerPoolMemberWithContext(context.Background(), getLoadBalancerPoolMemberOptions) +// GetVPNGatewayConnection : Retrieve a VPN gateway connection +// This request retrieves a single VPN gateway connection specified by the identifier in the URL. +func (vpc *VpcV1) GetVPNGatewayConnection(getVPNGatewayConnectionOptions *GetVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPNGatewayConnectionWithContext(context.Background(), getVPNGatewayConnectionOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetLoadBalancerPoolMemberWithContext is an alternate form of the GetLoadBalancerPoolMember method which supports a Context parameter -func (vpc *VpcV1) GetLoadBalancerPoolMemberWithContext(ctx context.Context, getLoadBalancerPoolMemberOptions *GetLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getLoadBalancerPoolMemberOptions, "getLoadBalancerPoolMemberOptions cannot be nil") +// GetVPNGatewayConnectionWithContext is an alternate form of the GetVPNGatewayConnection method which supports a Context parameter +func (vpc *VpcV1) GetVPNGatewayConnectionWithContext(ctx context.Context, getVPNGatewayConnectionOptions *GetVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPNGatewayConnectionOptions, "getVPNGatewayConnectionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getLoadBalancerPoolMemberOptions, "getLoadBalancerPoolMemberOptions") + err = core.ValidateStruct(getVPNGatewayConnectionOptions, "getVPNGatewayConnectionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *getLoadBalancerPoolMemberOptions.LoadBalancerID, - "pool_id": *getLoadBalancerPoolMemberOptions.PoolID, - "id": *getLoadBalancerPoolMemberOptions.ID, + "vpn_gateway_id": *getVPNGatewayConnectionOptions.VPNGatewayID, + "id": *getVPNGatewayConnectionOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getLoadBalancerPoolMemberOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNGatewayConnection") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetLoadBalancerPoolMember") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPNGatewayConnectionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -31571,12 +33027,12 @@ func (vpc *VpcV1) GetLoadBalancerPoolMemberWithContext(ctx context.Context, getL var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_load_balancer_pool_member", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpn_gateway_connection", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMember) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -31587,48 +33043,47 @@ func (vpc *VpcV1) GetLoadBalancerPoolMemberWithContext(ctx context.Context, getL return } -// UpdateLoadBalancerPoolMember : Update a load balancer pool member -// This request updates an existing member from a member patch. -func (vpc *VpcV1) UpdateLoadBalancerPoolMember(updateLoadBalancerPoolMemberOptions *UpdateLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateLoadBalancerPoolMemberWithContext(context.Background(), updateLoadBalancerPoolMemberOptions) +// UpdateVPNGatewayConnection : Update a VPN gateway connection +// This request updates the properties of an existing VPN gateway connection. +func (vpc *VpcV1) UpdateVPNGatewayConnection(updateVPNGatewayConnectionOptions *UpdateVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPNGatewayConnectionWithContext(context.Background(), updateVPNGatewayConnectionOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateLoadBalancerPoolMemberWithContext is an alternate form of the UpdateLoadBalancerPoolMember method which supports a Context parameter -func (vpc *VpcV1) UpdateLoadBalancerPoolMemberWithContext(ctx context.Context, updateLoadBalancerPoolMemberOptions *UpdateLoadBalancerPoolMemberOptions) (result *LoadBalancerPoolMember, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateLoadBalancerPoolMemberOptions, "updateLoadBalancerPoolMemberOptions cannot be nil") +// UpdateVPNGatewayConnectionWithContext is an alternate form of the UpdateVPNGatewayConnection method which supports a Context parameter +func (vpc *VpcV1) UpdateVPNGatewayConnectionWithContext(ctx context.Context, updateVPNGatewayConnectionOptions *UpdateVPNGatewayConnectionOptions) (result VPNGatewayConnectionIntf, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPNGatewayConnectionOptions, "updateVPNGatewayConnectionOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateLoadBalancerPoolMemberOptions, "updateLoadBalancerPoolMemberOptions") + err = core.ValidateStruct(updateVPNGatewayConnectionOptions, "updateVPNGatewayConnectionOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "load_balancer_id": *updateLoadBalancerPoolMemberOptions.LoadBalancerID, - "pool_id": *updateLoadBalancerPoolMemberOptions.PoolID, - "id": *updateLoadBalancerPoolMemberOptions.ID, + "vpn_gateway_id": *updateVPNGatewayConnectionOptions.VPNGatewayID, + "id": *updateVPNGatewayConnectionOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/load_balancers/{load_balancer_id}/pools/{pool_id}/members/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateLoadBalancerPoolMemberOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPNGatewayConnection") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateLoadBalancerPoolMember") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPNGatewayConnectionOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -31637,7 +33092,7 @@ func (vpc *VpcV1) UpdateLoadBalancerPoolMemberWithContext(ctx context.Context, u builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateLoadBalancerPoolMemberOptions.LoadBalancerPoolMemberPatch) + _, err = builder.SetBodyContentJSON(updateVPNGatewayConnectionOptions.VPNGatewayConnectionPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -31652,103 +33107,12 @@ func (vpc *VpcV1) UpdateLoadBalancerPoolMemberWithContext(ctx context.Context, u var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_load_balancer_pool_member", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLoadBalancerPoolMember) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } - - return -} - -// ListEndpointGateways : List endpoint gateways -// This request lists endpoint gateways in the region. An endpoint gateway maps one or more reserved IPs in a VPC to a -// target outside the VPC. -func (vpc *VpcV1) ListEndpointGateways(listEndpointGatewaysOptions *ListEndpointGatewaysOptions) (result *EndpointGatewayCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListEndpointGatewaysWithContext(context.Background(), listEndpointGatewaysOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// ListEndpointGatewaysWithContext is an alternate form of the ListEndpointGateways method which supports a Context parameter -func (vpc *VpcV1) ListEndpointGatewaysWithContext(ctx context.Context, listEndpointGatewaysOptions *ListEndpointGatewaysOptions) (result *EndpointGatewayCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listEndpointGatewaysOptions, "listEndpointGatewaysOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - builder := core.NewRequestBuilder(core.GET) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways`, nil) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range listEndpointGatewaysOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListEndpointGateways") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Accept", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listEndpointGatewaysOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listEndpointGatewaysOptions.Name)) - } - if listEndpointGatewaysOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listEndpointGatewaysOptions.Start)) - } - if listEndpointGatewaysOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listEndpointGatewaysOptions.Limit)) - } - if listEndpointGatewaysOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listEndpointGatewaysOptions.ResourceGroupID)) - } - if listEndpointGatewaysOptions.LifecycleState != nil { - builder.AddQuery("lifecycle_state", strings.Join(listEndpointGatewaysOptions.LifecycleState, ",")) - } - if listEndpointGatewaysOptions.VPCID != nil { - builder.AddQuery("vpc.id", fmt.Sprint(*listEndpointGatewaysOptions.VPCID)) - } - if listEndpointGatewaysOptions.VPCCRN != nil { - builder.AddQuery("vpc.crn", fmt.Sprint(*listEndpointGatewaysOptions.VPCCRN)) - } - if listEndpointGatewaysOptions.VPCName != nil { - builder.AddQuery("vpc.name", fmt.Sprint(*listEndpointGatewaysOptions.VPCName)) - } - if listEndpointGatewaysOptions.AllowDnsResolutionBinding != nil { - builder.AddQuery("allow_dns_resolution_binding", fmt.Sprint(*listEndpointGatewaysOptions.AllowDnsResolutionBinding)) - } - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) - if err != nil { - core.EnrichHTTPProblem(err, "list_endpoint_gateways", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpn_gateway_connection", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEndpointGatewayCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -31759,79 +33123,56 @@ func (vpc *VpcV1) ListEndpointGatewaysWithContext(ctx context.Context, listEndpo return } -// CreateEndpointGateway : Create an endpoint gateway -// This request creates a new endpoint gateway. An endpoint gateway maps one or more reserved IPs in a VPC to a target -// outside the VPC. -func (vpc *VpcV1) CreateEndpointGateway(createEndpointGatewayOptions *CreateEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateEndpointGatewayWithContext(context.Background(), createEndpointGatewayOptions) +// ListVPNGatewayConnectionsLocalCIDRs : List local CIDRs for a VPN gateway connection +// This request lists local CIDRs for a VPN gateway connection. +// +// This request is only supported for policy mode VPN gateways. +func (vpc *VpcV1) ListVPNGatewayConnectionsLocalCIDRs(listVPNGatewayConnectionsLocalCIDRsOptions *ListVPNGatewayConnectionsLocalCIDRsOptions) (result *VPNGatewayConnectionCIDRs, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPNGatewayConnectionsLocalCIDRsWithContext(context.Background(), listVPNGatewayConnectionsLocalCIDRsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateEndpointGatewayWithContext is an alternate form of the CreateEndpointGateway method which supports a Context parameter -func (vpc *VpcV1) CreateEndpointGatewayWithContext(ctx context.Context, createEndpointGatewayOptions *CreateEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createEndpointGatewayOptions, "createEndpointGatewayOptions cannot be nil") +// ListVPNGatewayConnectionsLocalCIDRsWithContext is an alternate form of the ListVPNGatewayConnectionsLocalCIDRs method which supports a Context parameter +func (vpc *VpcV1) ListVPNGatewayConnectionsLocalCIDRsWithContext(ctx context.Context, listVPNGatewayConnectionsLocalCIDRsOptions *ListVPNGatewayConnectionsLocalCIDRsOptions) (result *VPNGatewayConnectionCIDRs, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPNGatewayConnectionsLocalCIDRsOptions, "listVPNGatewayConnectionsLocalCIDRsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createEndpointGatewayOptions, "createEndpointGatewayOptions") + err = core.ValidateStruct(listVPNGatewayConnectionsLocalCIDRsOptions, "listVPNGatewayConnectionsLocalCIDRsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "vpn_gateway_id": *listVPNGatewayConnectionsLocalCIDRsOptions.VPNGatewayID, + "id": *listVPNGatewayConnectionsLocalCIDRsOptions.ID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/local/cidrs`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createEndpointGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNGatewayConnectionsLocalCIDRs") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateEndpointGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPNGatewayConnectionsLocalCIDRsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - body := make(map[string]interface{}) - if createEndpointGatewayOptions.Target != nil { - body["target"] = createEndpointGatewayOptions.Target - } - if createEndpointGatewayOptions.VPC != nil { - body["vpc"] = createEndpointGatewayOptions.VPC - } - if createEndpointGatewayOptions.AllowDnsResolutionBinding != nil { - body["allow_dns_resolution_binding"] = createEndpointGatewayOptions.AllowDnsResolutionBinding - } - if createEndpointGatewayOptions.Ips != nil { - body["ips"] = createEndpointGatewayOptions.Ips - } - if createEndpointGatewayOptions.Name != nil { - body["name"] = createEndpointGatewayOptions.Name - } - if createEndpointGatewayOptions.ResourceGroup != nil { - body["resource_group"] = createEndpointGatewayOptions.ResourceGroup - } - if createEndpointGatewayOptions.SecurityGroups != nil { - body["security_groups"] = createEndpointGatewayOptions.SecurityGroups - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) @@ -31841,12 +33182,12 @@ func (vpc *VpcV1) CreateEndpointGatewayWithContext(ctx context.Context, createEn var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_endpoint_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpn_gateway_connections_local_cidrs", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEndpointGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnectionCIDRs) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -31857,61 +33198,55 @@ func (vpc *VpcV1) CreateEndpointGatewayWithContext(ctx context.Context, createEn return } -// ListEndpointGatewayIps : List reserved IPs bound to an endpoint gateway -// This request lists reserved IPs bound to an endpoint gateway. -func (vpc *VpcV1) ListEndpointGatewayIps(listEndpointGatewayIpsOptions *ListEndpointGatewayIpsOptions) (result *ReservedIPCollectionEndpointGatewayContext, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListEndpointGatewayIpsWithContext(context.Background(), listEndpointGatewayIpsOptions) +// RemoveVPNGatewayConnectionsLocalCIDR : Remove a local CIDR from a VPN gateway connection +// This request removes a CIDR from a VPN gateway connection. +// +// This request is only supported for policy mode VPN gateways. +func (vpc *VpcV1) RemoveVPNGatewayConnectionsLocalCIDR(removeVPNGatewayConnectionsLocalCIDROptions *RemoveVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RemoveVPNGatewayConnectionsLocalCIDRWithContext(context.Background(), removeVPNGatewayConnectionsLocalCIDROptions) err = core.RepurposeSDKProblem(err, "") return } -// ListEndpointGatewayIpsWithContext is an alternate form of the ListEndpointGatewayIps method which supports a Context parameter -func (vpc *VpcV1) ListEndpointGatewayIpsWithContext(ctx context.Context, listEndpointGatewayIpsOptions *ListEndpointGatewayIpsOptions) (result *ReservedIPCollectionEndpointGatewayContext, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listEndpointGatewayIpsOptions, "listEndpointGatewayIpsOptions cannot be nil") +// RemoveVPNGatewayConnectionsLocalCIDRWithContext is an alternate form of the RemoveVPNGatewayConnectionsLocalCIDR method which supports a Context parameter +func (vpc *VpcV1) RemoveVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Context, removeVPNGatewayConnectionsLocalCIDROptions *RemoveVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(removeVPNGatewayConnectionsLocalCIDROptions, "removeVPNGatewayConnectionsLocalCIDROptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listEndpointGatewayIpsOptions, "listEndpointGatewayIpsOptions") + err = core.ValidateStruct(removeVPNGatewayConnectionsLocalCIDROptions, "removeVPNGatewayConnectionsLocalCIDROptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "endpoint_gateway_id": *listEndpointGatewayIpsOptions.EndpointGatewayID, + "vpn_gateway_id": *removeVPNGatewayConnectionsLocalCIDROptions.VPNGatewayID, + "id": *removeVPNGatewayConnectionsLocalCIDROptions.ID, + "cidr": *removeVPNGatewayConnectionsLocalCIDROptions.CIDR, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{endpoint_gateway_id}/ips`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/local/cidrs/{cidr}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listEndpointGatewayIpsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveVPNGatewayConnectionsLocalCIDR") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListEndpointGatewayIps") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range removeVPNGatewayConnectionsLocalCIDROptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listEndpointGatewayIpsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listEndpointGatewayIpsOptions.Start)) - } - if listEndpointGatewayIpsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listEndpointGatewayIpsOptions.Limit)) - } - if listEndpointGatewayIpsOptions.Sort != nil { - builder.AddQuery("sort", fmt.Sprint(*listEndpointGatewayIpsOptions.Sort)) - } request, err := builder.Build() if err != nil { @@ -31919,67 +33254,60 @@ func (vpc *VpcV1) ListEndpointGatewayIpsWithContext(ctx context.Context, listEnd return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "list_endpoint_gateway_ips", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "remove_vpn_gateway_connections_local_cidr", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIPCollectionEndpointGatewayContext) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// RemoveEndpointGatewayIP : Unbind a reserved IP from an endpoint gateway -// This request unbinds the specified reserved IP from the specified endpoint gateway. If the reserved IP has -// `auto_delete` set to `true`, the reserved IP will be deleted. -func (vpc *VpcV1) RemoveEndpointGatewayIP(removeEndpointGatewayIPOptions *RemoveEndpointGatewayIPOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RemoveEndpointGatewayIPWithContext(context.Background(), removeEndpointGatewayIPOptions) +// CheckVPNGatewayConnectionsLocalCIDR : Check if the specified local CIDR exists on a VPN gateway connection +// This request succeeds if a CIDR exists on the specified VPN gateway connection, and fails otherwise. +// +// This request is only supported for policy mode VPN gateways. +func (vpc *VpcV1) CheckVPNGatewayConnectionsLocalCIDR(checkVPNGatewayConnectionsLocalCIDROptions *CheckVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { + response, err = vpc.CheckVPNGatewayConnectionsLocalCIDRWithContext(context.Background(), checkVPNGatewayConnectionsLocalCIDROptions) err = core.RepurposeSDKProblem(err, "") return } -// RemoveEndpointGatewayIPWithContext is an alternate form of the RemoveEndpointGatewayIP method which supports a Context parameter -func (vpc *VpcV1) RemoveEndpointGatewayIPWithContext(ctx context.Context, removeEndpointGatewayIPOptions *RemoveEndpointGatewayIPOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(removeEndpointGatewayIPOptions, "removeEndpointGatewayIPOptions cannot be nil") +// CheckVPNGatewayConnectionsLocalCIDRWithContext is an alternate form of the CheckVPNGatewayConnectionsLocalCIDR method which supports a Context parameter +func (vpc *VpcV1) CheckVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Context, checkVPNGatewayConnectionsLocalCIDROptions *CheckVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(checkVPNGatewayConnectionsLocalCIDROptions, "checkVPNGatewayConnectionsLocalCIDROptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(removeEndpointGatewayIPOptions, "removeEndpointGatewayIPOptions") + err = core.ValidateStruct(checkVPNGatewayConnectionsLocalCIDROptions, "checkVPNGatewayConnectionsLocalCIDROptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "endpoint_gateway_id": *removeEndpointGatewayIPOptions.EndpointGatewayID, - "id": *removeEndpointGatewayIPOptions.ID, + "vpn_gateway_id": *checkVPNGatewayConnectionsLocalCIDROptions.VPNGatewayID, + "id": *checkVPNGatewayConnectionsLocalCIDROptions.ID, + "cidr": *checkVPNGatewayConnectionsLocalCIDROptions.CIDR, } - builder := core.NewRequestBuilder(core.DELETE) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{endpoint_gateway_id}/ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/local/cidrs/{cidr}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range removeEndpointGatewayIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CheckVPNGatewayConnectionsLocalCIDR") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveEndpointGatewayIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range checkVPNGatewayConnectionsLocalCIDROptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -31994,7 +33322,7 @@ func (vpc *VpcV1) RemoveEndpointGatewayIPWithContext(ctx context.Context, remove response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "remove_endpoint_gateway_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "check_vpn_gateway_connections_local_cidr", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -32002,50 +33330,53 @@ func (vpc *VpcV1) RemoveEndpointGatewayIPWithContext(ctx context.Context, remove return } -// GetEndpointGatewayIP : Retrieve a reserved IP bound to an endpoint gateway -// This request retrieves the specified reserved IP address if it is bound to the endpoint gateway specified in the URL. -func (vpc *VpcV1) GetEndpointGatewayIP(getEndpointGatewayIPOptions *GetEndpointGatewayIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetEndpointGatewayIPWithContext(context.Background(), getEndpointGatewayIPOptions) +// AddVPNGatewayConnectionsLocalCIDR : Set a local CIDR on a VPN gateway connection +// This request adds the specified CIDR to the specified VPN gateway connection. This request succeeds if the specified +// CIDR already exists. A request body is not required, and if provided, is ignored. +// +// This request is only supported for policy mode VPN gateways. +func (vpc *VpcV1) AddVPNGatewayConnectionsLocalCIDR(addVPNGatewayConnectionsLocalCIDROptions *AddVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { + response, err = vpc.AddVPNGatewayConnectionsLocalCIDRWithContext(context.Background(), addVPNGatewayConnectionsLocalCIDROptions) err = core.RepurposeSDKProblem(err, "") return } -// GetEndpointGatewayIPWithContext is an alternate form of the GetEndpointGatewayIP method which supports a Context parameter -func (vpc *VpcV1) GetEndpointGatewayIPWithContext(ctx context.Context, getEndpointGatewayIPOptions *GetEndpointGatewayIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getEndpointGatewayIPOptions, "getEndpointGatewayIPOptions cannot be nil") +// AddVPNGatewayConnectionsLocalCIDRWithContext is an alternate form of the AddVPNGatewayConnectionsLocalCIDR method which supports a Context parameter +func (vpc *VpcV1) AddVPNGatewayConnectionsLocalCIDRWithContext(ctx context.Context, addVPNGatewayConnectionsLocalCIDROptions *AddVPNGatewayConnectionsLocalCIDROptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(addVPNGatewayConnectionsLocalCIDROptions, "addVPNGatewayConnectionsLocalCIDROptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getEndpointGatewayIPOptions, "getEndpointGatewayIPOptions") + err = core.ValidateStruct(addVPNGatewayConnectionsLocalCIDROptions, "addVPNGatewayConnectionsLocalCIDROptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "endpoint_gateway_id": *getEndpointGatewayIPOptions.EndpointGatewayID, - "id": *getEndpointGatewayIPOptions.ID, + "vpn_gateway_id": *addVPNGatewayConnectionsLocalCIDROptions.VPNGatewayID, + "id": *addVPNGatewayConnectionsLocalCIDROptions.ID, + "cidr": *addVPNGatewayConnectionsLocalCIDROptions.CIDR, } - builder := core.NewRequestBuilder(core.GET) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{endpoint_gateway_id}/ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/local/cidrs/{cidr}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getEndpointGatewayIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddVPNGatewayConnectionsLocalCIDR") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetEndpointGatewayIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range addVPNGatewayConnectionsLocalCIDROptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -32056,69 +33387,59 @@ func (vpc *VpcV1) GetEndpointGatewayIPWithContext(ctx context.Context, getEndpoi return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_endpoint_gateway_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "add_vpn_gateway_connections_local_cidr", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// AddEndpointGatewayIP : Bind a reserved IP to an endpoint gateway -// This request binds the specified reserved IP to the specified endpoint gateway. The reserved IP: +// ListVPNGatewayConnectionsPeerCIDRs : List peer CIDRs for a VPN gateway connection +// This request lists peer CIDRs for a VPN gateway connection. // -// - must currently be unbound, or not required by its target -// - must not be in the same zone as any other reserved IP bound to the endpoint gateway. -func (vpc *VpcV1) AddEndpointGatewayIP(addEndpointGatewayIPOptions *AddEndpointGatewayIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - result, response, err = vpc.AddEndpointGatewayIPWithContext(context.Background(), addEndpointGatewayIPOptions) +// This request is only supported for policy mode VPN gateways. +func (vpc *VpcV1) ListVPNGatewayConnectionsPeerCIDRs(listVPNGatewayConnectionsPeerCIDRsOptions *ListVPNGatewayConnectionsPeerCIDRsOptions) (result *VPNGatewayConnectionCIDRs, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPNGatewayConnectionsPeerCIDRsWithContext(context.Background(), listVPNGatewayConnectionsPeerCIDRsOptions) err = core.RepurposeSDKProblem(err, "") return } -// AddEndpointGatewayIPWithContext is an alternate form of the AddEndpointGatewayIP method which supports a Context parameter -func (vpc *VpcV1) AddEndpointGatewayIPWithContext(ctx context.Context, addEndpointGatewayIPOptions *AddEndpointGatewayIPOptions) (result *ReservedIP, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(addEndpointGatewayIPOptions, "addEndpointGatewayIPOptions cannot be nil") +// ListVPNGatewayConnectionsPeerCIDRsWithContext is an alternate form of the ListVPNGatewayConnectionsPeerCIDRs method which supports a Context parameter +func (vpc *VpcV1) ListVPNGatewayConnectionsPeerCIDRsWithContext(ctx context.Context, listVPNGatewayConnectionsPeerCIDRsOptions *ListVPNGatewayConnectionsPeerCIDRsOptions) (result *VPNGatewayConnectionCIDRs, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPNGatewayConnectionsPeerCIDRsOptions, "listVPNGatewayConnectionsPeerCIDRsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(addEndpointGatewayIPOptions, "addEndpointGatewayIPOptions") + err = core.ValidateStruct(listVPNGatewayConnectionsPeerCIDRsOptions, "listVPNGatewayConnectionsPeerCIDRsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "endpoint_gateway_id": *addEndpointGatewayIPOptions.EndpointGatewayID, - "id": *addEndpointGatewayIPOptions.ID, + "vpn_gateway_id": *listVPNGatewayConnectionsPeerCIDRsOptions.VPNGatewayID, + "id": *listVPNGatewayConnectionsPeerCIDRsOptions.ID, } - builder := core.NewRequestBuilder(core.PUT) + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{endpoint_gateway_id}/ips/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/peer/cidrs`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range addEndpointGatewayIPOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNGatewayConnectionsPeerCIDRs") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddEndpointGatewayIP") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPNGatewayConnectionsPeerCIDRsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -32135,12 +33456,12 @@ func (vpc *VpcV1) AddEndpointGatewayIPWithContext(ctx context.Context, addEndpoi var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "add_endpoint_gateway_ip", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpn_gateway_connections_peer_cidrs", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReservedIP) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNGatewayConnectionCIDRs) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -32151,49 +33472,50 @@ func (vpc *VpcV1) AddEndpointGatewayIPWithContext(ctx context.Context, addEndpoi return } -// DeleteEndpointGateway : Delete an endpoint gateway -// This request deletes an endpoint gateway. This operation cannot be reversed. +// RemoveVPNGatewayConnectionsPeerCIDR : Remove a peer CIDR from a VPN gateway connection +// This request removes a CIDR from a VPN gateway connection. // -// Reserved IPs that were bound to the endpoint gateway will be released if their -// `auto_delete` property is set to true. -func (vpc *VpcV1) DeleteEndpointGateway(deleteEndpointGatewayOptions *DeleteEndpointGatewayOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteEndpointGatewayWithContext(context.Background(), deleteEndpointGatewayOptions) +// This request is only supported for policy mode VPN gateways. +func (vpc *VpcV1) RemoveVPNGatewayConnectionsPeerCIDR(removeVPNGatewayConnectionsPeerCIDROptions *RemoveVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { + response, err = vpc.RemoveVPNGatewayConnectionsPeerCIDRWithContext(context.Background(), removeVPNGatewayConnectionsPeerCIDROptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteEndpointGatewayWithContext is an alternate form of the DeleteEndpointGateway method which supports a Context parameter -func (vpc *VpcV1) DeleteEndpointGatewayWithContext(ctx context.Context, deleteEndpointGatewayOptions *DeleteEndpointGatewayOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteEndpointGatewayOptions, "deleteEndpointGatewayOptions cannot be nil") +// RemoveVPNGatewayConnectionsPeerCIDRWithContext is an alternate form of the RemoveVPNGatewayConnectionsPeerCIDR method which supports a Context parameter +func (vpc *VpcV1) RemoveVPNGatewayConnectionsPeerCIDRWithContext(ctx context.Context, removeVPNGatewayConnectionsPeerCIDROptions *RemoveVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(removeVPNGatewayConnectionsPeerCIDROptions, "removeVPNGatewayConnectionsPeerCIDROptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteEndpointGatewayOptions, "deleteEndpointGatewayOptions") + err = core.ValidateStruct(removeVPNGatewayConnectionsPeerCIDROptions, "removeVPNGatewayConnectionsPeerCIDROptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteEndpointGatewayOptions.ID, + "vpn_gateway_id": *removeVPNGatewayConnectionsPeerCIDROptions.VPNGatewayID, + "id": *removeVPNGatewayConnectionsPeerCIDROptions.ID, + "cidr": *removeVPNGatewayConnectionsPeerCIDROptions.CIDR, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/peer/cidrs/{cidr}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteEndpointGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RemoveVPNGatewayConnectionsPeerCIDR") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteEndpointGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range removeVPNGatewayConnectionsPeerCIDROptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -32208,7 +33530,7 @@ func (vpc *VpcV1) DeleteEndpointGatewayWithContext(ctx context.Context, deleteEn response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_endpoint_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "remove_vpn_gateway_connections_peer_cidr", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -32216,49 +33538,52 @@ func (vpc *VpcV1) DeleteEndpointGatewayWithContext(ctx context.Context, deleteEn return } -// GetEndpointGateway : Retrieve an endpoint gateway -// This request retrieves a single endpoint gateway specified by the identifier in the URL. -func (vpc *VpcV1) GetEndpointGateway(getEndpointGatewayOptions *GetEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetEndpointGatewayWithContext(context.Background(), getEndpointGatewayOptions) +// CheckVPNGatewayConnectionsPeerCIDR : Check if the specified peer CIDR exists on a VPN gateway connection +// This request succeeds if a CIDR exists on the specified VPN gateway connection, and fails otherwise. +// +// This request is only supported for policy mode VPN gateways. +func (vpc *VpcV1) CheckVPNGatewayConnectionsPeerCIDR(checkVPNGatewayConnectionsPeerCIDROptions *CheckVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { + response, err = vpc.CheckVPNGatewayConnectionsPeerCIDRWithContext(context.Background(), checkVPNGatewayConnectionsPeerCIDROptions) err = core.RepurposeSDKProblem(err, "") return } -// GetEndpointGatewayWithContext is an alternate form of the GetEndpointGateway method which supports a Context parameter -func (vpc *VpcV1) GetEndpointGatewayWithContext(ctx context.Context, getEndpointGatewayOptions *GetEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getEndpointGatewayOptions, "getEndpointGatewayOptions cannot be nil") +// CheckVPNGatewayConnectionsPeerCIDRWithContext is an alternate form of the CheckVPNGatewayConnectionsPeerCIDR method which supports a Context parameter +func (vpc *VpcV1) CheckVPNGatewayConnectionsPeerCIDRWithContext(ctx context.Context, checkVPNGatewayConnectionsPeerCIDROptions *CheckVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(checkVPNGatewayConnectionsPeerCIDROptions, "checkVPNGatewayConnectionsPeerCIDROptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getEndpointGatewayOptions, "getEndpointGatewayOptions") + err = core.ValidateStruct(checkVPNGatewayConnectionsPeerCIDROptions, "checkVPNGatewayConnectionsPeerCIDROptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getEndpointGatewayOptions.ID, + "vpn_gateway_id": *checkVPNGatewayConnectionsPeerCIDROptions.VPNGatewayID, + "id": *checkVPNGatewayConnectionsPeerCIDROptions.ID, + "cidr": *checkVPNGatewayConnectionsPeerCIDROptions.CIDR, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/peer/cidrs/{cidr}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getEndpointGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CheckVPNGatewayConnectionsPeerCIDR") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetEndpointGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range checkVPNGatewayConnectionsPeerCIDROptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -32269,118 +33594,94 @@ func (vpc *VpcV1) GetEndpointGatewayWithContext(ctx context.Context, getEndpoint return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "get_endpoint_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "check_vpn_gateway_connections_peer_cidr", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEndpointGateway) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// UpdateEndpointGateway : Update an endpoint gateway -// This request updates an endpoint gateway's name. -func (vpc *VpcV1) UpdateEndpointGateway(updateEndpointGatewayOptions *UpdateEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateEndpointGatewayWithContext(context.Background(), updateEndpointGatewayOptions) +// AddVPNGatewayConnectionsPeerCIDR : Set a peer CIDR on a VPN gateway connection +// This request adds the specified CIDR to the specified VPN gateway connection. This request succeeds if the specified +// CIDR already exists. A request body is not required, and if provided, is ignored. +// +// This request is only supported for policy mode VPN gateways. +func (vpc *VpcV1) AddVPNGatewayConnectionsPeerCIDR(addVPNGatewayConnectionsPeerCIDROptions *AddVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { + response, err = vpc.AddVPNGatewayConnectionsPeerCIDRWithContext(context.Background(), addVPNGatewayConnectionsPeerCIDROptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateEndpointGatewayWithContext is an alternate form of the UpdateEndpointGateway method which supports a Context parameter -func (vpc *VpcV1) UpdateEndpointGatewayWithContext(ctx context.Context, updateEndpointGatewayOptions *UpdateEndpointGatewayOptions) (result *EndpointGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateEndpointGatewayOptions, "updateEndpointGatewayOptions cannot be nil") +// AddVPNGatewayConnectionsPeerCIDRWithContext is an alternate form of the AddVPNGatewayConnectionsPeerCIDR method which supports a Context parameter +func (vpc *VpcV1) AddVPNGatewayConnectionsPeerCIDRWithContext(ctx context.Context, addVPNGatewayConnectionsPeerCIDROptions *AddVPNGatewayConnectionsPeerCIDROptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(addVPNGatewayConnectionsPeerCIDROptions, "addVPNGatewayConnectionsPeerCIDROptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateEndpointGatewayOptions, "updateEndpointGatewayOptions") + err = core.ValidateStruct(addVPNGatewayConnectionsPeerCIDROptions, "addVPNGatewayConnectionsPeerCIDROptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateEndpointGatewayOptions.ID, + "vpn_gateway_id": *addVPNGatewayConnectionsPeerCIDROptions.VPNGatewayID, + "id": *addVPNGatewayConnectionsPeerCIDROptions.ID, + "cidr": *addVPNGatewayConnectionsPeerCIDROptions.CIDR, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/endpoint_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_gateways/{vpn_gateway_id}/connections/{id}/peer/cidrs/{cidr}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateEndpointGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "AddVPNGatewayConnectionsPeerCIDR") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateEndpointGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range addVPNGatewayConnectionsPeerCIDROptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateEndpointGatewayOptions.EndpointGatewayPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "update_endpoint_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "add_vpn_gateway_connections_peer_cidr", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalEndpointGateway) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListFlowLogCollectors : List flow log collectors -// This request lists flow log collectors in the region. A [flow log -// collector](https://cloud.ibm.com/docs/vpc?topic=vpc-flow-logs) summarizes TCP and UDP data sent over the instance -// network interfaces and instance network attachments contained within its target. The collected flow logs are written -// to a cloud object storage bucket, where they can be [viewed](https://cloud.ibm.com/docs/vpc?topic=vpc-fl-analyze). -func (vpc *VpcV1) ListFlowLogCollectors(listFlowLogCollectorsOptions *ListFlowLogCollectorsOptions) (result *FlowLogCollectorCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListFlowLogCollectorsWithContext(context.Background(), listFlowLogCollectorsOptions) +// ListVPNServers : List VPN servers +// This request lists VPN servers. +func (vpc *VpcV1) ListVPNServers(listVPNServersOptions *ListVPNServersOptions) (result *VPNServerCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPNServersWithContext(context.Background(), listVPNServersOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListFlowLogCollectorsWithContext is an alternate form of the ListFlowLogCollectors method which supports a Context parameter -func (vpc *VpcV1) ListFlowLogCollectorsWithContext(ctx context.Context, listFlowLogCollectorsOptions *ListFlowLogCollectorsOptions) (result *FlowLogCollectorCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listFlowLogCollectorsOptions, "listFlowLogCollectorsOptions") +// ListVPNServersWithContext is an alternate form of the ListVPNServers method which supports a Context parameter +func (vpc *VpcV1) ListVPNServersWithContext(ctx context.Context, listVPNServersOptions *ListVPNServersOptions) (result *VPNServerCollection, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listVPNServersOptions, "listVPNServersOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -32389,50 +33690,38 @@ func (vpc *VpcV1) ListFlowLogCollectorsWithContext(ctx context.Context, listFlow builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listFlowLogCollectorsOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNServers") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListFlowLogCollectors") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPNServersOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listFlowLogCollectorsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listFlowLogCollectorsOptions.Start)) - } - if listFlowLogCollectorsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listFlowLogCollectorsOptions.Limit)) - } - if listFlowLogCollectorsOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listFlowLogCollectorsOptions.ResourceGroupID)) - } - if listFlowLogCollectorsOptions.Name != nil { - builder.AddQuery("name", fmt.Sprint(*listFlowLogCollectorsOptions.Name)) - } - if listFlowLogCollectorsOptions.VPCID != nil { - builder.AddQuery("vpc.id", fmt.Sprint(*listFlowLogCollectorsOptions.VPCID)) + if listVPNServersOptions.Name != nil { + builder.AddQuery("name", fmt.Sprint(*listVPNServersOptions.Name)) } - if listFlowLogCollectorsOptions.VPCCRN != nil { - builder.AddQuery("vpc.crn", fmt.Sprint(*listFlowLogCollectorsOptions.VPCCRN)) + if listVPNServersOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPNServersOptions.Start)) } - if listFlowLogCollectorsOptions.VPCName != nil { - builder.AddQuery("vpc.name", fmt.Sprint(*listFlowLogCollectorsOptions.VPCName)) + if listVPNServersOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPNServersOptions.Limit)) } - if listFlowLogCollectorsOptions.TargetID != nil { - builder.AddQuery("target.id", fmt.Sprint(*listFlowLogCollectorsOptions.TargetID)) + if listVPNServersOptions.ResourceGroupID != nil { + builder.AddQuery("resource_group.id", fmt.Sprint(*listVPNServersOptions.ResourceGroupID)) } - if listFlowLogCollectorsOptions.TargetResourceType != nil { - builder.AddQuery("target.resource_type", fmt.Sprint(*listFlowLogCollectorsOptions.TargetResourceType)) + if listVPNServersOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listVPNServersOptions.Sort)) } request, err := builder.Build() @@ -32444,12 +33733,12 @@ func (vpc *VpcV1) ListFlowLogCollectorsWithContext(ctx context.Context, listFlow var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_flow_log_collectors", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpn_servers", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFlowLogCollectorCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -32460,24 +33749,22 @@ func (vpc *VpcV1) ListFlowLogCollectorsWithContext(ctx context.Context, listFlow return } -// CreateFlowLogCollector : Create a flow log collector -// This request creates and starts a new flow log collector from a flow log collector prototype object. The prototype -// object is structured in the same way as a retrieved flow log collector, and contains the information necessary to -// create and start the new flow log collector. -func (vpc *VpcV1) CreateFlowLogCollector(createFlowLogCollectorOptions *CreateFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreateFlowLogCollectorWithContext(context.Background(), createFlowLogCollectorOptions) +// CreateVPNServer : Create a VPN server +// This request creates a new VPN server. +func (vpc *VpcV1) CreateVPNServer(createVPNServerOptions *CreateVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPNServerWithContext(context.Background(), createVPNServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreateFlowLogCollectorWithContext is an alternate form of the CreateFlowLogCollector method which supports a Context parameter -func (vpc *VpcV1) CreateFlowLogCollectorWithContext(ctx context.Context, createFlowLogCollectorOptions *CreateFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createFlowLogCollectorOptions, "createFlowLogCollectorOptions cannot be nil") +// CreateVPNServerWithContext is an alternate form of the CreateVPNServer method which supports a Context parameter +func (vpc *VpcV1) CreateVPNServerWithContext(ctx context.Context, createVPNServerOptions *CreateVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVPNServerOptions, "createVPNServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createFlowLogCollectorOptions, "createFlowLogCollectorOptions") + err = core.ValidateStruct(createVPNServerOptions, "createVPNServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return @@ -32486,18 +33773,18 @@ func (vpc *VpcV1) CreateFlowLogCollectorWithContext(ctx context.Context, createF builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers`, nil) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createFlowLogCollectorOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPNServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateFlowLogCollector") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPNServerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -32507,20 +33794,41 @@ func (vpc *VpcV1) CreateFlowLogCollectorWithContext(ctx context.Context, createF builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createFlowLogCollectorOptions.StorageBucket != nil { - body["storage_bucket"] = createFlowLogCollectorOptions.StorageBucket + if createVPNServerOptions.Certificate != nil { + body["certificate"] = createVPNServerOptions.Certificate } - if createFlowLogCollectorOptions.Target != nil { - body["target"] = createFlowLogCollectorOptions.Target + if createVPNServerOptions.ClientAuthentication != nil { + body["client_authentication"] = createVPNServerOptions.ClientAuthentication } - if createFlowLogCollectorOptions.Active != nil { - body["active"] = createFlowLogCollectorOptions.Active + if createVPNServerOptions.ClientIPPool != nil { + body["client_ip_pool"] = createVPNServerOptions.ClientIPPool } - if createFlowLogCollectorOptions.Name != nil { - body["name"] = createFlowLogCollectorOptions.Name + if createVPNServerOptions.Subnets != nil { + body["subnets"] = createVPNServerOptions.Subnets } - if createFlowLogCollectorOptions.ResourceGroup != nil { - body["resource_group"] = createFlowLogCollectorOptions.ResourceGroup + if createVPNServerOptions.ClientDnsServerIps != nil { + body["client_dns_server_ips"] = createVPNServerOptions.ClientDnsServerIps + } + if createVPNServerOptions.ClientIdleTimeout != nil { + body["client_idle_timeout"] = createVPNServerOptions.ClientIdleTimeout + } + if createVPNServerOptions.EnableSplitTunneling != nil { + body["enable_split_tunneling"] = createVPNServerOptions.EnableSplitTunneling + } + if createVPNServerOptions.Name != nil { + body["name"] = createVPNServerOptions.Name + } + if createVPNServerOptions.Port != nil { + body["port"] = createVPNServerOptions.Port + } + if createVPNServerOptions.Protocol != nil { + body["protocol"] = createVPNServerOptions.Protocol + } + if createVPNServerOptions.ResourceGroup != nil { + body["resource_group"] = createVPNServerOptions.ResourceGroup + } + if createVPNServerOptions.SecurityGroups != nil { + body["security_groups"] = createVPNServerOptions.SecurityGroups } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -32537,12 +33845,12 @@ func (vpc *VpcV1) CreateFlowLogCollectorWithContext(ctx context.Context, createF var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_flow_log_collector", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpn_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFlowLogCollector) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -32553,50 +33861,51 @@ func (vpc *VpcV1) CreateFlowLogCollectorWithContext(ctx context.Context, createF return } -// DeleteFlowLogCollector : Delete a flow log collector -// This request stops and deletes a flow log collector. This operation cannot be reversed. -// -// Collected flow logs remain available within the flow log collector's Cloud Object Storage bucket. -func (vpc *VpcV1) DeleteFlowLogCollector(deleteFlowLogCollectorOptions *DeleteFlowLogCollectorOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeleteFlowLogCollectorWithContext(context.Background(), deleteFlowLogCollectorOptions) +// DeleteVPNServer : Delete a VPN server +// This request deletes a VPN server. This operation cannot be reversed. +func (vpc *VpcV1) DeleteVPNServer(deleteVPNServerOptions *DeleteVPNServerOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPNServerWithContext(context.Background(), deleteVPNServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeleteFlowLogCollectorWithContext is an alternate form of the DeleteFlowLogCollector method which supports a Context parameter -func (vpc *VpcV1) DeleteFlowLogCollectorWithContext(ctx context.Context, deleteFlowLogCollectorOptions *DeleteFlowLogCollectorOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deleteFlowLogCollectorOptions, "deleteFlowLogCollectorOptions cannot be nil") +// DeleteVPNServerWithContext is an alternate form of the DeleteVPNServer method which supports a Context parameter +func (vpc *VpcV1) DeleteVPNServerWithContext(ctx context.Context, deleteVPNServerOptions *DeleteVPNServerOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPNServerOptions, "deleteVPNServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deleteFlowLogCollectorOptions, "deleteFlowLogCollectorOptions") + err = core.ValidateStruct(deleteVPNServerOptions, "deleteVPNServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deleteFlowLogCollectorOptions.ID, + "id": *deleteVPNServerOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deleteFlowLogCollectorOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteFlowLogCollector") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPNServerOptions.Headers { builder.AddHeader(headerName, headerValue) } + if deleteVPNServerOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*deleteVPNServerOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) @@ -32609,7 +33918,7 @@ func (vpc *VpcV1) DeleteFlowLogCollectorWithContext(ctx context.Context, deleteF response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_flow_log_collector", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpn_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -32617,46 +33926,46 @@ func (vpc *VpcV1) DeleteFlowLogCollectorWithContext(ctx context.Context, deleteF return } -// GetFlowLogCollector : Retrieve a flow log collector -// This request retrieves a single flow log collector specified by the identifier in the URL. -func (vpc *VpcV1) GetFlowLogCollector(getFlowLogCollectorOptions *GetFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetFlowLogCollectorWithContext(context.Background(), getFlowLogCollectorOptions) +// GetVPNServer : Retrieve a VPN server +// This request retrieves a single VPN server specified by the identifier in the URL. +func (vpc *VpcV1) GetVPNServer(getVPNServerOptions *GetVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPNServerWithContext(context.Background(), getVPNServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetFlowLogCollectorWithContext is an alternate form of the GetFlowLogCollector method which supports a Context parameter -func (vpc *VpcV1) GetFlowLogCollectorWithContext(ctx context.Context, getFlowLogCollectorOptions *GetFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getFlowLogCollectorOptions, "getFlowLogCollectorOptions cannot be nil") +// GetVPNServerWithContext is an alternate form of the GetVPNServer method which supports a Context parameter +func (vpc *VpcV1) GetVPNServerWithContext(ctx context.Context, getVPNServerOptions *GetVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPNServerOptions, "getVPNServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getFlowLogCollectorOptions, "getFlowLogCollectorOptions") + err = core.ValidateStruct(getVPNServerOptions, "getVPNServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getFlowLogCollectorOptions.ID, + "id": *getVPNServerOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getFlowLogCollectorOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetFlowLogCollector") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPNServerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -32673,12 +33982,12 @@ func (vpc *VpcV1) GetFlowLogCollectorWithContext(ctx context.Context, getFlowLog var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_flow_log_collector", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpn_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFlowLogCollector) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -32689,57 +33998,59 @@ func (vpc *VpcV1) GetFlowLogCollectorWithContext(ctx context.Context, getFlowLog return } -// UpdateFlowLogCollector : Update a flow log collector -// This request updates a flow log collector with the information in a provided flow log collector patch. The flow log -// collector patch object is structured in the same way as a retrieved flow log collector and contains only the -// information to be updated. -func (vpc *VpcV1) UpdateFlowLogCollector(updateFlowLogCollectorOptions *UpdateFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdateFlowLogCollectorWithContext(context.Background(), updateFlowLogCollectorOptions) +// UpdateVPNServer : Update a VPN server +// This request updates the properties of an existing VPN server. Any updates other than to `name` will cause all +// connected VPN clients to be disconnected. +func (vpc *VpcV1) UpdateVPNServer(updateVPNServerOptions *UpdateVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPNServerWithContext(context.Background(), updateVPNServerOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdateFlowLogCollectorWithContext is an alternate form of the UpdateFlowLogCollector method which supports a Context parameter -func (vpc *VpcV1) UpdateFlowLogCollectorWithContext(ctx context.Context, updateFlowLogCollectorOptions *UpdateFlowLogCollectorOptions) (result *FlowLogCollector, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updateFlowLogCollectorOptions, "updateFlowLogCollectorOptions cannot be nil") +// UpdateVPNServerWithContext is an alternate form of the UpdateVPNServer method which supports a Context parameter +func (vpc *VpcV1) UpdateVPNServerWithContext(ctx context.Context, updateVPNServerOptions *UpdateVPNServerOptions) (result *VPNServer, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPNServerOptions, "updateVPNServerOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updateFlowLogCollectorOptions, "updateFlowLogCollectorOptions") + err = core.ValidateStruct(updateVPNServerOptions, "updateVPNServerOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updateFlowLogCollectorOptions.ID, + "id": *updateVPNServerOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/flow_log_collectors/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updateFlowLogCollectorOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPNServer") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateFlowLogCollector") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPNServerOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/merge-patch+json") + if updateVPNServerOptions.IfMatch != nil { + builder.AddHeader("If-Match", fmt.Sprint(*updateVPNServerOptions.IfMatch)) + } builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updateFlowLogCollectorOptions.FlowLogCollectorPatch) + _, err = builder.SetBodyContentJSON(updateVPNServerOptions.VPNServerPatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -32754,12 +34065,12 @@ func (vpc *VpcV1) UpdateFlowLogCollectorWithContext(ctx context.Context, updateF var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_flow_log_collector", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpn_server", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFlowLogCollector) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServer) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -32770,59 +34081,53 @@ func (vpc *VpcV1) UpdateFlowLogCollectorWithContext(ctx context.Context, updateF return } -// ListPrivatePathServiceGateways : List private path service gateways -// This request lists private path service gateways in the region. Private path service gateways allow -// [service -// providers](https://cloud.ibm.com/docs/private-path?topic=private-path-private-path-service-architecture#private-path-service-components) -// to make their services available using -// [private path -// connectivity](https://cloud.ibm.com/docs/private-path?topic=private-path-private-path-service-architecture#private-path-service-components). -// Private path service gateways are used to facilitate and manage the private path connectivity between private path -// network load balancers and their associated endpoint gateways. -func (vpc *VpcV1) ListPrivatePathServiceGateways(listPrivatePathServiceGatewaysOptions *ListPrivatePathServiceGatewaysOptions) (result *PrivatePathServiceGatewayCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListPrivatePathServiceGatewaysWithContext(context.Background(), listPrivatePathServiceGatewaysOptions) +// GetVPNServerClientConfiguration : Retrieve client configuration +// This request retrieves OpenVPN client configuration on a single VPN server specified by the identifier in the URL. +// This configuration includes directives compatible with OpenVPN releases 2.4 and 2.5. +func (vpc *VpcV1) GetVPNServerClientConfiguration(getVPNServerClientConfigurationOptions *GetVPNServerClientConfigurationOptions) (result *string, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPNServerClientConfigurationWithContext(context.Background(), getVPNServerClientConfigurationOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListPrivatePathServiceGatewaysWithContext is an alternate form of the ListPrivatePathServiceGateways method which supports a Context parameter -func (vpc *VpcV1) ListPrivatePathServiceGatewaysWithContext(ctx context.Context, listPrivatePathServiceGatewaysOptions *ListPrivatePathServiceGatewaysOptions) (result *PrivatePathServiceGatewayCollection, response *core.DetailedResponse, err error) { - err = core.ValidateStruct(listPrivatePathServiceGatewaysOptions, "listPrivatePathServiceGatewaysOptions") +// GetVPNServerClientConfigurationWithContext is an alternate form of the GetVPNServerClientConfiguration method which supports a Context parameter +func (vpc *VpcV1) GetVPNServerClientConfigurationWithContext(ctx context.Context, getVPNServerClientConfigurationOptions *GetVPNServerClientConfigurationOptions) (result *string, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPNServerClientConfigurationOptions, "getVPNServerClientConfigurationOptions cannot be nil") + if err != nil { + err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) + return + } + err = core.ValidateStruct(getVPNServerClientConfigurationOptions, "getVPNServerClientConfigurationOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } + pathParamsMap := map[string]string{ + "id": *getVPNServerClientConfigurationOptions.ID, + } + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{id}/client_configuration`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listPrivatePathServiceGatewaysOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNServerClientConfiguration") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPrivatePathServiceGateways") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPNServerClientConfigurationOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") + builder.AddHeader("Accept", "text/plain") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listPrivatePathServiceGatewaysOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listPrivatePathServiceGatewaysOptions.Start)) - } - if listPrivatePathServiceGatewaysOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listPrivatePathServiceGatewaysOptions.Limit)) - } - if listPrivatePathServiceGatewaysOptions.ResourceGroupID != nil { - builder.AddQuery("resource_group.id", fmt.Sprint(*listPrivatePathServiceGatewaysOptions.ResourceGroupID)) - } request, err := builder.Build() if err != nil { @@ -32830,94 +34135,71 @@ func (vpc *VpcV1) ListPrivatePathServiceGatewaysWithContext(ctx context.Context, return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, &result) if err != nil { - core.EnrichHTTPProblem(err, "list_private_path_service_gateways", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpn_server_client_configuration", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// CreatePrivatePathServiceGateway : Create a private path service gateway -// This request creates a private path service gateway from a private path service gateway prototype object. The -// prototype object is structured in the same way as a retrieved private path service gateway, and contains the -// information necessary to create the new private path service gateway. -func (vpc *VpcV1) CreatePrivatePathServiceGateway(createPrivatePathServiceGatewayOptions *CreatePrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreatePrivatePathServiceGatewayWithContext(context.Background(), createPrivatePathServiceGatewayOptions) +// ListVPNServerClients : List VPN clients for a VPN server +// This request retrieves connected VPN clients, and any disconnected VPN clients that the VPN server has not yet +// deleted based on its auto-deletion policy. +func (vpc *VpcV1) ListVPNServerClients(listVPNServerClientsOptions *ListVPNServerClientsOptions) (result *VPNServerClientCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPNServerClientsWithContext(context.Background(), listVPNServerClientsOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreatePrivatePathServiceGatewayWithContext is an alternate form of the CreatePrivatePathServiceGateway method which supports a Context parameter -func (vpc *VpcV1) CreatePrivatePathServiceGatewayWithContext(ctx context.Context, createPrivatePathServiceGatewayOptions *CreatePrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createPrivatePathServiceGatewayOptions, "createPrivatePathServiceGatewayOptions cannot be nil") +// ListVPNServerClientsWithContext is an alternate form of the ListVPNServerClients method which supports a Context parameter +func (vpc *VpcV1) ListVPNServerClientsWithContext(ctx context.Context, listVPNServerClientsOptions *ListVPNServerClientsOptions) (result *VPNServerClientCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPNServerClientsOptions, "listVPNServerClientsOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createPrivatePathServiceGatewayOptions, "createPrivatePathServiceGatewayOptions") + err = core.ValidateStruct(listVPNServerClientsOptions, "listVPNServerClientsOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } - builder := core.NewRequestBuilder(core.POST) + pathParamsMap := map[string]string{ + "vpn_server_id": *listVPNServerClientsOptions.VPNServerID, + } + + builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways`, nil) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/clients`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createPrivatePathServiceGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNServerClients") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePrivatePathServiceGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPNServerClientsOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if createPrivatePathServiceGatewayOptions.LoadBalancer != nil { - body["load_balancer"] = createPrivatePathServiceGatewayOptions.LoadBalancer + if listVPNServerClientsOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPNServerClientsOptions.Start)) } - if createPrivatePathServiceGatewayOptions.ServiceEndpoints != nil { - body["service_endpoints"] = createPrivatePathServiceGatewayOptions.ServiceEndpoints + if listVPNServerClientsOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPNServerClientsOptions.Limit)) } - if createPrivatePathServiceGatewayOptions.DefaultAccessPolicy != nil { - body["default_access_policy"] = createPrivatePathServiceGatewayOptions.DefaultAccessPolicy - } - if createPrivatePathServiceGatewayOptions.Name != nil { - body["name"] = createPrivatePathServiceGatewayOptions.Name - } - if createPrivatePathServiceGatewayOptions.ResourceGroup != nil { - body["resource_group"] = createPrivatePathServiceGatewayOptions.ResourceGroup - } - if createPrivatePathServiceGatewayOptions.ZonalAffinity != nil { - body["zonal_affinity"] = createPrivatePathServiceGatewayOptions.ZonalAffinity - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return + if listVPNServerClientsOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listVPNServerClientsOptions.Sort)) } request, err := builder.Build() @@ -32929,12 +34211,12 @@ func (vpc *VpcV1) CreatePrivatePathServiceGatewayWithContext(ctx context.Context var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_private_path_service_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpn_server_clients", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerClientCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -32945,47 +34227,49 @@ func (vpc *VpcV1) CreatePrivatePathServiceGatewayWithContext(ctx context.Context return } -// DeletePrivatePathServiceGateway : Delete a private path service gateway -// This request deletes a private path service gateway. For this request to succeed, the value of -// `endpoint_gateway_count` must be `0`. This operation cannot be reversed. -func (vpc *VpcV1) DeletePrivatePathServiceGateway(deletePrivatePathServiceGatewayOptions *DeletePrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeletePrivatePathServiceGatewayWithContext(context.Background(), deletePrivatePathServiceGatewayOptions) +// DeleteVPNServerClient : Delete a VPN client +// This request disconnects and deletes the VPN client from the VPN server. The VPN client may reconnect unless its +// authentication permissions for the configured authentication methods (such as its client certificate) have been +// revoked. +func (vpc *VpcV1) DeleteVPNServerClient(deleteVPNServerClientOptions *DeleteVPNServerClientOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPNServerClientWithContext(context.Background(), deleteVPNServerClientOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeletePrivatePathServiceGatewayWithContext is an alternate form of the DeletePrivatePathServiceGateway method which supports a Context parameter -func (vpc *VpcV1) DeletePrivatePathServiceGatewayWithContext(ctx context.Context, deletePrivatePathServiceGatewayOptions *DeletePrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deletePrivatePathServiceGatewayOptions, "deletePrivatePathServiceGatewayOptions cannot be nil") +// DeleteVPNServerClientWithContext is an alternate form of the DeleteVPNServerClient method which supports a Context parameter +func (vpc *VpcV1) DeleteVPNServerClientWithContext(ctx context.Context, deleteVPNServerClientOptions *DeleteVPNServerClientOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPNServerClientOptions, "deleteVPNServerClientOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deletePrivatePathServiceGatewayOptions, "deletePrivatePathServiceGatewayOptions") + err = core.ValidateStruct(deleteVPNServerClientOptions, "deleteVPNServerClientOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *deletePrivatePathServiceGatewayOptions.ID, + "vpn_server_id": *deleteVPNServerClientOptions.VPNServerID, + "id": *deleteVPNServerClientOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/clients/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deletePrivatePathServiceGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNServerClient") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePrivatePathServiceGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPNServerClientOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -33000,7 +34284,7 @@ func (vpc *VpcV1) DeletePrivatePathServiceGatewayWithContext(ctx context.Context response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_private_path_service_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpn_server_client", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -33008,46 +34292,47 @@ func (vpc *VpcV1) DeletePrivatePathServiceGatewayWithContext(ctx context.Context return } -// GetPrivatePathServiceGateway : Retrieve a private path service gateway -// This request retrieves the private path service gateway specified by the identifier in the URL. -func (vpc *VpcV1) GetPrivatePathServiceGateway(getPrivatePathServiceGatewayOptions *GetPrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetPrivatePathServiceGatewayWithContext(context.Background(), getPrivatePathServiceGatewayOptions) +// GetVPNServerClient : Retrieve a VPN client +// This request retrieves a single VPN client specified by the identifier in the URL. +func (vpc *VpcV1) GetVPNServerClient(getVPNServerClientOptions *GetVPNServerClientOptions) (result *VPNServerClient, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPNServerClientWithContext(context.Background(), getVPNServerClientOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetPrivatePathServiceGatewayWithContext is an alternate form of the GetPrivatePathServiceGateway method which supports a Context parameter -func (vpc *VpcV1) GetPrivatePathServiceGatewayWithContext(ctx context.Context, getPrivatePathServiceGatewayOptions *GetPrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getPrivatePathServiceGatewayOptions, "getPrivatePathServiceGatewayOptions cannot be nil") +// GetVPNServerClientWithContext is an alternate form of the GetVPNServerClient method which supports a Context parameter +func (vpc *VpcV1) GetVPNServerClientWithContext(ctx context.Context, getVPNServerClientOptions *GetVPNServerClientOptions) (result *VPNServerClient, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPNServerClientOptions, "getVPNServerClientOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getPrivatePathServiceGatewayOptions, "getPrivatePathServiceGatewayOptions") + err = core.ValidateStruct(getVPNServerClientOptions, "getVPNServerClientOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *getPrivatePathServiceGatewayOptions.ID, + "vpn_server_id": *getVPNServerClientOptions.VPNServerID, + "id": *getVPNServerClientOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/clients/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getPrivatePathServiceGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNServerClient") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPrivatePathServiceGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPNServerClientOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -33064,12 +34349,12 @@ func (vpc *VpcV1) GetPrivatePathServiceGatewayWithContext(ctx context.Context, g var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_private_path_service_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpn_server_client", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGateway) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerClient) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -33080,146 +34365,127 @@ func (vpc *VpcV1) GetPrivatePathServiceGatewayWithContext(ctx context.Context, g return } -// UpdatePrivatePathServiceGateway : Update a private path service gateway -// This request updates a private path service gateway with the information provided in a private path service gateway -// patch object. The private path service gateway patch object is structured in the same way as a retrieved private path -// service gateway and contains only the information to be updated. -func (vpc *VpcV1) UpdatePrivatePathServiceGateway(updatePrivatePathServiceGatewayOptions *UpdatePrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdatePrivatePathServiceGatewayWithContext(context.Background(), updatePrivatePathServiceGatewayOptions) +// DisconnectVPNClient : Disconnect a VPN client +// This request disconnects the specified VPN client, and deletes the client according to the VPN server's auto-deletion +// policy. The VPN client may reconnect unless its authentication permissions for the configured authentication methods +// (such as its client certificate) have been revoked. +func (vpc *VpcV1) DisconnectVPNClient(disconnectVPNClientOptions *DisconnectVPNClientOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DisconnectVPNClientWithContext(context.Background(), disconnectVPNClientOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdatePrivatePathServiceGatewayWithContext is an alternate form of the UpdatePrivatePathServiceGateway method which supports a Context parameter -func (vpc *VpcV1) UpdatePrivatePathServiceGatewayWithContext(ctx context.Context, updatePrivatePathServiceGatewayOptions *UpdatePrivatePathServiceGatewayOptions) (result *PrivatePathServiceGateway, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updatePrivatePathServiceGatewayOptions, "updatePrivatePathServiceGatewayOptions cannot be nil") +// DisconnectVPNClientWithContext is an alternate form of the DisconnectVPNClient method which supports a Context parameter +func (vpc *VpcV1) DisconnectVPNClientWithContext(ctx context.Context, disconnectVPNClientOptions *DisconnectVPNClientOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(disconnectVPNClientOptions, "disconnectVPNClientOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updatePrivatePathServiceGatewayOptions, "updatePrivatePathServiceGatewayOptions") + err = core.ValidateStruct(disconnectVPNClientOptions, "disconnectVPNClientOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "id": *updatePrivatePathServiceGatewayOptions.ID, + "vpn_server_id": *disconnectVPNClientOptions.VPNServerID, + "id": *disconnectVPNClientOptions.ID, } - builder := core.NewRequestBuilder(core.PATCH) + builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/clients/{id}/disconnect`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updatePrivatePathServiceGatewayOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DisconnectVPNClient") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePrivatePathServiceGateway") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range disconnectVPNClientOptions.Headers { builder.AddHeader(headerName, headerValue) } - builder.AddHeader("Accept", "application/json") - builder.AddHeader("Content-Type", "application/merge-patch+json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updatePrivatePathServiceGatewayOptions.PrivatePathServiceGatewayPatch) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - request, err := builder.Build() if err != nil { err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) return } - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) + response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "update_private_path_service_gateway", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "disconnect_vpn_client", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGateway) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } return } -// ListPrivatePathServiceGatewayAccountPolicies : List account policies for a private path service gateway -// This request lists account policies for a private path service gateway. Each policy defines how requests to use the -// private path service gateway from that account will be handled. -// -// The account policies will be sorted by their `created_at` property values, with newest account policies first. -// Account policies with identical `created_at` property values will in turn be sorted by ascending `id` property -// values. -func (vpc *VpcV1) ListPrivatePathServiceGatewayAccountPolicies(listPrivatePathServiceGatewayAccountPoliciesOptions *ListPrivatePathServiceGatewayAccountPoliciesOptions) (result *PrivatePathServiceGatewayAccountPolicyCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListPrivatePathServiceGatewayAccountPoliciesWithContext(context.Background(), listPrivatePathServiceGatewayAccountPoliciesOptions) +// ListVPNServerRoutes : List VPN routes for a VPN server +// This request lists VPN routes in a VPN server. All VPN routes are provided to the VPN client when the connection is +// established. Packets received from the VPN client will be dropped by the VPN server if there is no VPN route +// matching their specified destinations. All VPN routes must be unique within the VPN server. +func (vpc *VpcV1) ListVPNServerRoutes(listVPNServerRoutesOptions *ListVPNServerRoutesOptions) (result *VPNServerRouteCollection, response *core.DetailedResponse, err error) { + result, response, err = vpc.ListVPNServerRoutesWithContext(context.Background(), listVPNServerRoutesOptions) err = core.RepurposeSDKProblem(err, "") return } -// ListPrivatePathServiceGatewayAccountPoliciesWithContext is an alternate form of the ListPrivatePathServiceGatewayAccountPolicies method which supports a Context parameter -func (vpc *VpcV1) ListPrivatePathServiceGatewayAccountPoliciesWithContext(ctx context.Context, listPrivatePathServiceGatewayAccountPoliciesOptions *ListPrivatePathServiceGatewayAccountPoliciesOptions) (result *PrivatePathServiceGatewayAccountPolicyCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listPrivatePathServiceGatewayAccountPoliciesOptions, "listPrivatePathServiceGatewayAccountPoliciesOptions cannot be nil") +// ListVPNServerRoutesWithContext is an alternate form of the ListVPNServerRoutes method which supports a Context parameter +func (vpc *VpcV1) ListVPNServerRoutesWithContext(ctx context.Context, listVPNServerRoutesOptions *ListVPNServerRoutesOptions) (result *VPNServerRouteCollection, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(listVPNServerRoutesOptions, "listVPNServerRoutesOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(listPrivatePathServiceGatewayAccountPoliciesOptions, "listPrivatePathServiceGatewayAccountPoliciesOptions") + err = core.ValidateStruct(listVPNServerRoutesOptions, "listVPNServerRoutesOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *listPrivatePathServiceGatewayAccountPoliciesOptions.PrivatePathServiceGatewayID, + "vpn_server_id": *listVPNServerRoutesOptions.VPNServerID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range listPrivatePathServiceGatewayAccountPoliciesOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListVPNServerRoutes") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPrivatePathServiceGatewayAccountPolicies") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range listVPNServerRoutesOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listPrivatePathServiceGatewayAccountPoliciesOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listPrivatePathServiceGatewayAccountPoliciesOptions.Start)) + if listVPNServerRoutesOptions.Start != nil { + builder.AddQuery("start", fmt.Sprint(*listVPNServerRoutesOptions.Start)) } - if listPrivatePathServiceGatewayAccountPoliciesOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listPrivatePathServiceGatewayAccountPoliciesOptions.Limit)) + if listVPNServerRoutesOptions.Limit != nil { + builder.AddQuery("limit", fmt.Sprint(*listVPNServerRoutesOptions.Limit)) } - if listPrivatePathServiceGatewayAccountPoliciesOptions.AccountID != nil { - builder.AddQuery("account.id", fmt.Sprint(*listPrivatePathServiceGatewayAccountPoliciesOptions.AccountID)) + if listVPNServerRoutesOptions.Sort != nil { + builder.AddQuery("sort", fmt.Sprint(*listVPNServerRoutesOptions.Sort)) } request, err := builder.Build() @@ -33231,12 +34497,12 @@ func (vpc *VpcV1) ListPrivatePathServiceGatewayAccountPoliciesWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "list_private_path_service_gateway_account_policies", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "list_vpn_server_routes", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayAccountPolicyCollection) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerRouteCollection) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -33247,47 +34513,48 @@ func (vpc *VpcV1) ListPrivatePathServiceGatewayAccountPoliciesWithContext(ctx co return } -// CreatePrivatePathServiceGatewayAccountPolicy : Create an account policy for a private path service gateway -// This request creates an account policy from an account policy prototype object. The prototype object is structured in -// the same way as a retrieved account policy, and contains the information necessary to create the new account policy. -func (vpc *VpcV1) CreatePrivatePathServiceGatewayAccountPolicy(createPrivatePathServiceGatewayAccountPolicyOptions *CreatePrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.CreatePrivatePathServiceGatewayAccountPolicyWithContext(context.Background(), createPrivatePathServiceGatewayAccountPolicyOptions) +// CreateVPNServerRoute : Create a VPN route for a VPN server +// This request creates a new VPN route in the VPN server. All VPN routes are provided to the VPN client when the +// connection is established. Packets received from the VPN client will be dropped by the VPN server if there is no VPN +// route matching their specified destinations. All VPN routes must be unique within the VPN server. +func (vpc *VpcV1) CreateVPNServerRoute(createVPNServerRouteOptions *CreateVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { + result, response, err = vpc.CreateVPNServerRouteWithContext(context.Background(), createVPNServerRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// CreatePrivatePathServiceGatewayAccountPolicyWithContext is an alternate form of the CreatePrivatePathServiceGatewayAccountPolicy method which supports a Context parameter -func (vpc *VpcV1) CreatePrivatePathServiceGatewayAccountPolicyWithContext(ctx context.Context, createPrivatePathServiceGatewayAccountPolicyOptions *CreatePrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(createPrivatePathServiceGatewayAccountPolicyOptions, "createPrivatePathServiceGatewayAccountPolicyOptions cannot be nil") +// CreateVPNServerRouteWithContext is an alternate form of the CreateVPNServerRoute method which supports a Context parameter +func (vpc *VpcV1) CreateVPNServerRouteWithContext(ctx context.Context, createVPNServerRouteOptions *CreateVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(createVPNServerRouteOptions, "createVPNServerRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(createPrivatePathServiceGatewayAccountPolicyOptions, "createPrivatePathServiceGatewayAccountPolicyOptions") + err = core.ValidateStruct(createVPNServerRouteOptions, "createVPNServerRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *createPrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayID, + "vpn_server_id": *createVPNServerRouteOptions.VPNServerID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range createPrivatePathServiceGatewayAccountPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreateVPNServerRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "CreatePrivatePathServiceGatewayAccountPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range createVPNServerRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -33297,11 +34564,14 @@ func (vpc *VpcV1) CreatePrivatePathServiceGatewayAccountPolicyWithContext(ctx co builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) body := make(map[string]interface{}) - if createPrivatePathServiceGatewayAccountPolicyOptions.AccessPolicy != nil { - body["access_policy"] = createPrivatePathServiceGatewayAccountPolicyOptions.AccessPolicy + if createVPNServerRouteOptions.Destination != nil { + body["destination"] = createVPNServerRouteOptions.Destination } - if createPrivatePathServiceGatewayAccountPolicyOptions.Account != nil { - body["account"] = createPrivatePathServiceGatewayAccountPolicyOptions.Account + if createVPNServerRouteOptions.Action != nil { + body["action"] = createVPNServerRouteOptions.Action + } + if createVPNServerRouteOptions.Name != nil { + body["name"] = createVPNServerRouteOptions.Name } _, err = builder.SetBodyContentJSON(body) if err != nil { @@ -33318,12 +34588,12 @@ func (vpc *VpcV1) CreatePrivatePathServiceGatewayAccountPolicyWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "create_private_path_service_gateway_account_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "create_vpn_server_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayAccountPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -33334,48 +34604,47 @@ func (vpc *VpcV1) CreatePrivatePathServiceGatewayAccountPolicyWithContext(ctx co return } -// DeletePrivatePathServiceGatewayAccountPolicy : Delete an account policy for a private path service gateway -// This request deletes an account policy. This operation cannot be reversed and it does not affect the `status` of any -// existing endpoint gateway bindings. -func (vpc *VpcV1) DeletePrivatePathServiceGatewayAccountPolicy(deletePrivatePathServiceGatewayAccountPolicyOptions *DeletePrivatePathServiceGatewayAccountPolicyOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DeletePrivatePathServiceGatewayAccountPolicyWithContext(context.Background(), deletePrivatePathServiceGatewayAccountPolicyOptions) +// DeleteVPNServerRoute : Delete a VPN route +// This request deletes a VPN route. This operation cannot be reversed. +func (vpc *VpcV1) DeleteVPNServerRoute(deleteVPNServerRouteOptions *DeleteVPNServerRouteOptions) (response *core.DetailedResponse, err error) { + response, err = vpc.DeleteVPNServerRouteWithContext(context.Background(), deleteVPNServerRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// DeletePrivatePathServiceGatewayAccountPolicyWithContext is an alternate form of the DeletePrivatePathServiceGatewayAccountPolicy method which supports a Context parameter -func (vpc *VpcV1) DeletePrivatePathServiceGatewayAccountPolicyWithContext(ctx context.Context, deletePrivatePathServiceGatewayAccountPolicyOptions *DeletePrivatePathServiceGatewayAccountPolicyOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(deletePrivatePathServiceGatewayAccountPolicyOptions, "deletePrivatePathServiceGatewayAccountPolicyOptions cannot be nil") +// DeleteVPNServerRouteWithContext is an alternate form of the DeleteVPNServerRoute method which supports a Context parameter +func (vpc *VpcV1) DeleteVPNServerRouteWithContext(ctx context.Context, deleteVPNServerRouteOptions *DeleteVPNServerRouteOptions) (response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteVPNServerRouteOptions, "deleteVPNServerRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(deletePrivatePathServiceGatewayAccountPolicyOptions, "deletePrivatePathServiceGatewayAccountPolicyOptions") + err = core.ValidateStruct(deleteVPNServerRouteOptions, "deleteVPNServerRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *deletePrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayID, - "id": *deletePrivatePathServiceGatewayAccountPolicyOptions.ID, + "vpn_server_id": *deleteVPNServerRouteOptions.VPNServerID, + "id": *deleteVPNServerRouteOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range deletePrivatePathServiceGatewayAccountPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeleteVPNServerRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DeletePrivatePathServiceGatewayAccountPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range deleteVPNServerRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } @@ -33390,7 +34659,7 @@ func (vpc *VpcV1) DeletePrivatePathServiceGatewayAccountPolicyWithContext(ctx co response, err = vpc.Service.Request(request, nil) if err != nil { - core.EnrichHTTPProblem(err, "delete_private_path_service_gateway_account_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "delete_vpn_server_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } @@ -33398,47 +34667,47 @@ func (vpc *VpcV1) DeletePrivatePathServiceGatewayAccountPolicyWithContext(ctx co return } -// GetPrivatePathServiceGatewayAccountPolicy : Retrieve an account policy for a private path service gateway -// This request retrieves a single account policy specified by the identifier in the URL. -func (vpc *VpcV1) GetPrivatePathServiceGatewayAccountPolicy(getPrivatePathServiceGatewayAccountPolicyOptions *GetPrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetPrivatePathServiceGatewayAccountPolicyWithContext(context.Background(), getPrivatePathServiceGatewayAccountPolicyOptions) +// GetVPNServerRoute : Retrieve a VPN route +// This request retrieves a single VPN route specified by the identifier in the URL. +func (vpc *VpcV1) GetVPNServerRoute(getVPNServerRouteOptions *GetVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { + result, response, err = vpc.GetVPNServerRouteWithContext(context.Background(), getVPNServerRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// GetPrivatePathServiceGatewayAccountPolicyWithContext is an alternate form of the GetPrivatePathServiceGatewayAccountPolicy method which supports a Context parameter -func (vpc *VpcV1) GetPrivatePathServiceGatewayAccountPolicyWithContext(ctx context.Context, getPrivatePathServiceGatewayAccountPolicyOptions *GetPrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getPrivatePathServiceGatewayAccountPolicyOptions, "getPrivatePathServiceGatewayAccountPolicyOptions cannot be nil") +// GetVPNServerRouteWithContext is an alternate form of the GetVPNServerRoute method which supports a Context parameter +func (vpc *VpcV1) GetVPNServerRouteWithContext(ctx context.Context, getVPNServerRouteOptions *GetVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getVPNServerRouteOptions, "getVPNServerRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(getPrivatePathServiceGatewayAccountPolicyOptions, "getPrivatePathServiceGatewayAccountPolicyOptions") + err = core.ValidateStruct(getVPNServerRouteOptions, "getVPNServerRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *getPrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayID, - "id": *getPrivatePathServiceGatewayAccountPolicyOptions.ID, + "vpn_server_id": *getVPNServerRouteOptions.VPNServerID, + "id": *getVPNServerRouteOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range getPrivatePathServiceGatewayAccountPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetVPNServerRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPrivatePathServiceGatewayAccountPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range getVPNServerRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -33455,12 +34724,12 @@ func (vpc *VpcV1) GetPrivatePathServiceGatewayAccountPolicyWithContext(ctx conte var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "get_private_path_service_gateway_account_policy", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "get_vpn_server_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayAccountPolicy) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -33471,49 +34740,48 @@ func (vpc *VpcV1) GetPrivatePathServiceGatewayAccountPolicyWithContext(ctx conte return } -// UpdatePrivatePathServiceGatewayAccountPolicy : Update an account policy for a private path service gateway -// This request updates an account policy with the information in a provided account policy patch. The account policy -// patch object is structured in the same way as a retrieved account policy and contains only the information to be -// updated. -func (vpc *VpcV1) UpdatePrivatePathServiceGatewayAccountPolicy(updatePrivatePathServiceGatewayAccountPolicyOptions *UpdatePrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { - result, response, err = vpc.UpdatePrivatePathServiceGatewayAccountPolicyWithContext(context.Background(), updatePrivatePathServiceGatewayAccountPolicyOptions) +// UpdateVPNServerRoute : Update a VPN route +// This request updates a VPN route with the information in a provided VPN route patch. The VPN route patch object is +// structured in the same way as a retrieved VPN route and contains only the information to be updated. +func (vpc *VpcV1) UpdateVPNServerRoute(updateVPNServerRouteOptions *UpdateVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { + result, response, err = vpc.UpdateVPNServerRouteWithContext(context.Background(), updateVPNServerRouteOptions) err = core.RepurposeSDKProblem(err, "") return } -// UpdatePrivatePathServiceGatewayAccountPolicyWithContext is an alternate form of the UpdatePrivatePathServiceGatewayAccountPolicy method which supports a Context parameter -func (vpc *VpcV1) UpdatePrivatePathServiceGatewayAccountPolicyWithContext(ctx context.Context, updatePrivatePathServiceGatewayAccountPolicyOptions *UpdatePrivatePathServiceGatewayAccountPolicyOptions) (result *PrivatePathServiceGatewayAccountPolicy, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(updatePrivatePathServiceGatewayAccountPolicyOptions, "updatePrivatePathServiceGatewayAccountPolicyOptions cannot be nil") +// UpdateVPNServerRouteWithContext is an alternate form of the UpdateVPNServerRoute method which supports a Context parameter +func (vpc *VpcV1) UpdateVPNServerRouteWithContext(ctx context.Context, updateVPNServerRouteOptions *UpdateVPNServerRouteOptions) (result *VPNServerRoute, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateVPNServerRouteOptions, "updateVPNServerRouteOptions cannot be nil") if err != nil { err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) return } - err = core.ValidateStruct(updatePrivatePathServiceGatewayAccountPolicyOptions, "updatePrivatePathServiceGatewayAccountPolicyOptions") + err = core.ValidateStruct(updateVPNServerRouteOptions, "updateVPNServerRouteOptions") if err != nil { err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) return } pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *updatePrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayID, - "id": *updatePrivatePathServiceGatewayAccountPolicyOptions.ID, + "vpn_server_id": *updateVPNServerRouteOptions.VPNServerID, + "id": *updateVPNServerRouteOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/account_policies/{id}`, pathParamsMap) + _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/vpn_servers/{vpn_server_id}/routes/{id}`, pathParamsMap) if err != nil { err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) return } - for headerName, headerValue := range updatePrivatePathServiceGatewayAccountPolicyOptions.Headers { + sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdateVPNServerRoute") + for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UpdatePrivatePathServiceGatewayAccountPolicy") - for headerName, headerValue := range sdkHeaders { + for headerName, headerValue := range updateVPNServerRouteOptions.Headers { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") @@ -33522,7 +34790,7 @@ func (vpc *VpcV1) UpdatePrivatePathServiceGatewayAccountPolicyWithContext(ctx co builder.AddQuery("version", fmt.Sprint(*vpc.Version)) builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - _, err = builder.SetBodyContentJSON(updatePrivatePathServiceGatewayAccountPolicyOptions.PrivatePathServiceGatewayAccountPolicyPatch) + _, err = builder.SetBodyContentJSON(updateVPNServerRouteOptions.VPNServerRoutePatch) if err != nil { err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) return @@ -33537,176 +34805,12 @@ func (vpc *VpcV1) UpdatePrivatePathServiceGatewayAccountPolicyWithContext(ctx co var rawResponse map[string]json.RawMessage response, err = vpc.Service.Request(request, &rawResponse) if err != nil { - core.EnrichHTTPProblem(err, "update_private_path_service_gateway_account_policy", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayAccountPolicy) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } - - return -} - -// ListPrivatePathServiceGatewayEndpointGatewayBindings : List endpoint gateway bindings for a private path service gateway -// This request lists endpoint gateway bindings for a private path service gateway. Each endpoint gateway binding is -// implicitly created when an endpoint gateway is created targeting the private path service gateway. The associated -// account policy is applied to all new endpoint gateway bindings. If an associated account policy doesn't exist, the -// private path service gateway's `default_access_policy` is used. -// -// The endpoint gateway bindings will be sorted by their `created_at` property values, with newest endpoint gateway -// bindings first. Endpoint gateway bindings with identical -// `created_at` property values will in turn be sorted by ascending `name` property values. -func (vpc *VpcV1) ListPrivatePathServiceGatewayEndpointGatewayBindings(listPrivatePathServiceGatewayEndpointGatewayBindingsOptions *ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions) (result *PrivatePathServiceGatewayEndpointGatewayBindingCollection, response *core.DetailedResponse, err error) { - result, response, err = vpc.ListPrivatePathServiceGatewayEndpointGatewayBindingsWithContext(context.Background(), listPrivatePathServiceGatewayEndpointGatewayBindingsOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// ListPrivatePathServiceGatewayEndpointGatewayBindingsWithContext is an alternate form of the ListPrivatePathServiceGatewayEndpointGatewayBindings method which supports a Context parameter -func (vpc *VpcV1) ListPrivatePathServiceGatewayEndpointGatewayBindingsWithContext(ctx context.Context, listPrivatePathServiceGatewayEndpointGatewayBindingsOptions *ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions) (result *PrivatePathServiceGatewayEndpointGatewayBindingCollection, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(listPrivatePathServiceGatewayEndpointGatewayBindingsOptions, "listPrivatePathServiceGatewayEndpointGatewayBindingsOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(listPrivatePathServiceGatewayEndpointGatewayBindingsOptions, "listPrivatePathServiceGatewayEndpointGatewayBindingsOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.PrivatePathServiceGatewayID, - } - - builder := core.NewRequestBuilder(core.GET) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/endpoint_gateway_bindings`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "ListPrivatePathServiceGatewayEndpointGatewayBindings") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Accept", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - if listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Start != nil { - builder.AddQuery("start", fmt.Sprint(*listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Start)) - } - if listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Limit != nil { - builder.AddQuery("limit", fmt.Sprint(*listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Limit)) - } - if listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Status != nil { - builder.AddQuery("status", fmt.Sprint(*listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.Status)) - } - if listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.AccountID != nil { - builder.AddQuery("account.id", fmt.Sprint(*listPrivatePathServiceGatewayEndpointGatewayBindingsOptions.AccountID)) - } - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) - if err != nil { - core.EnrichHTTPProblem(err, "list_private_path_service_gateway_endpoint_gateway_bindings", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayEndpointGatewayBindingCollection) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) - return - } - response.Result = result - } - - return -} - -// GetPrivatePathServiceGatewayEndpointGatewayBinding : Retrieve an endpoint gateway binding for a private path service gateway -// This request retrieves a single endpoint gateway binding specified by the identifier in the URL. -func (vpc *VpcV1) GetPrivatePathServiceGatewayEndpointGatewayBinding(getPrivatePathServiceGatewayEndpointGatewayBindingOptions *GetPrivatePathServiceGatewayEndpointGatewayBindingOptions) (result *PrivatePathServiceGatewayEndpointGatewayBinding, response *core.DetailedResponse, err error) { - result, response, err = vpc.GetPrivatePathServiceGatewayEndpointGatewayBindingWithContext(context.Background(), getPrivatePathServiceGatewayEndpointGatewayBindingOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// GetPrivatePathServiceGatewayEndpointGatewayBindingWithContext is an alternate form of the GetPrivatePathServiceGatewayEndpointGatewayBinding method which supports a Context parameter -func (vpc *VpcV1) GetPrivatePathServiceGatewayEndpointGatewayBindingWithContext(ctx context.Context, getPrivatePathServiceGatewayEndpointGatewayBindingOptions *GetPrivatePathServiceGatewayEndpointGatewayBindingOptions) (result *PrivatePathServiceGatewayEndpointGatewayBinding, response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(getPrivatePathServiceGatewayEndpointGatewayBindingOptions, "getPrivatePathServiceGatewayEndpointGatewayBindingOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(getPrivatePathServiceGatewayEndpointGatewayBindingOptions, "getPrivatePathServiceGatewayEndpointGatewayBindingOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *getPrivatePathServiceGatewayEndpointGatewayBindingOptions.PrivatePathServiceGatewayID, - "id": *getPrivatePathServiceGatewayEndpointGatewayBindingOptions.ID, - } - - builder := core.NewRequestBuilder(core.GET) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/endpoint_gateway_bindings/{id}`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range getPrivatePathServiceGatewayEndpointGatewayBindingOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "GetPrivatePathServiceGatewayEndpointGatewayBinding") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Accept", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - var rawResponse map[string]json.RawMessage - response, err = vpc.Service.Request(request, &rawResponse) - if err != nil { - core.EnrichHTTPProblem(err, "get_private_path_service_gateway_endpoint_gateway_binding", getServiceComponentInfo()) + core.EnrichHTTPProblem(err, "update_vpn_server_route", getServiceComponentInfo()) err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) return } if rawResponse != nil { - err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPrivatePathServiceGatewayEndpointGatewayBinding) + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalVPNServerRoute) if err != nil { err = core.SDKErrorf(err, "", "unmarshal-resp-error", common.GetComponentInfo()) return @@ -33716,360 +34820,8 @@ func (vpc *VpcV1) GetPrivatePathServiceGatewayEndpointGatewayBindingWithContext( return } - -// DenyPrivatePathServiceGatewayEndpointGatewayBinding : Deny an endpoint gateway binding for a private path service gateway -// This request denies a `pending` endpoint gateway request, and optionally sets the policy to deny future requests from -// the same account. -func (vpc *VpcV1) DenyPrivatePathServiceGatewayEndpointGatewayBinding(denyPrivatePathServiceGatewayEndpointGatewayBindingOptions *DenyPrivatePathServiceGatewayEndpointGatewayBindingOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.DenyPrivatePathServiceGatewayEndpointGatewayBindingWithContext(context.Background(), denyPrivatePathServiceGatewayEndpointGatewayBindingOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// DenyPrivatePathServiceGatewayEndpointGatewayBindingWithContext is an alternate form of the DenyPrivatePathServiceGatewayEndpointGatewayBinding method which supports a Context parameter -func (vpc *VpcV1) DenyPrivatePathServiceGatewayEndpointGatewayBindingWithContext(ctx context.Context, denyPrivatePathServiceGatewayEndpointGatewayBindingOptions *DenyPrivatePathServiceGatewayEndpointGatewayBindingOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(denyPrivatePathServiceGatewayEndpointGatewayBindingOptions, "denyPrivatePathServiceGatewayEndpointGatewayBindingOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(denyPrivatePathServiceGatewayEndpointGatewayBindingOptions, "denyPrivatePathServiceGatewayEndpointGatewayBindingOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.PrivatePathServiceGatewayID, - "id": *denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.ID, - } - - builder := core.NewRequestBuilder(core.POST) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/endpoint_gateway_bindings/{id}/deny`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "DenyPrivatePathServiceGatewayEndpointGatewayBinding") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Content-Type", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.SetAccountPolicy != nil { - body["set_account_policy"] = denyPrivatePathServiceGatewayEndpointGatewayBindingOptions.SetAccountPolicy - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - response, err = vpc.Service.Request(request, nil) - if err != nil { - core.EnrichHTTPProblem(err, "deny_private_path_service_gateway_endpoint_gateway_binding", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - - return -} - -// PermitPrivatePathServiceGatewayEndpointGatewayBinding : Permit an endpoint gateway binding for a private path service gateway -// This request permits a `pending` endpoint gateway request, and optionally sets the policy to permit future requests -// from the same account. -func (vpc *VpcV1) PermitPrivatePathServiceGatewayEndpointGatewayBinding(permitPrivatePathServiceGatewayEndpointGatewayBindingOptions *PermitPrivatePathServiceGatewayEndpointGatewayBindingOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.PermitPrivatePathServiceGatewayEndpointGatewayBindingWithContext(context.Background(), permitPrivatePathServiceGatewayEndpointGatewayBindingOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// PermitPrivatePathServiceGatewayEndpointGatewayBindingWithContext is an alternate form of the PermitPrivatePathServiceGatewayEndpointGatewayBinding method which supports a Context parameter -func (vpc *VpcV1) PermitPrivatePathServiceGatewayEndpointGatewayBindingWithContext(ctx context.Context, permitPrivatePathServiceGatewayEndpointGatewayBindingOptions *PermitPrivatePathServiceGatewayEndpointGatewayBindingOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(permitPrivatePathServiceGatewayEndpointGatewayBindingOptions, "permitPrivatePathServiceGatewayEndpointGatewayBindingOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(permitPrivatePathServiceGatewayEndpointGatewayBindingOptions, "permitPrivatePathServiceGatewayEndpointGatewayBindingOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.PrivatePathServiceGatewayID, - "id": *permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.ID, - } - - builder := core.NewRequestBuilder(core.POST) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/endpoint_gateway_bindings/{id}/permit`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "PermitPrivatePathServiceGatewayEndpointGatewayBinding") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Content-Type", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.SetAccountPolicy != nil { - body["set_account_policy"] = permitPrivatePathServiceGatewayEndpointGatewayBindingOptions.SetAccountPolicy - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - response, err = vpc.Service.Request(request, nil) - if err != nil { - core.EnrichHTTPProblem(err, "permit_private_path_service_gateway_endpoint_gateway_binding", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - - return -} - -// PublishPrivatePathServiceGateway : Publish a private path service gateway -// This request publishes a private path service gateway, allowing any account to request access to it. -func (vpc *VpcV1) PublishPrivatePathServiceGateway(publishPrivatePathServiceGatewayOptions *PublishPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.PublishPrivatePathServiceGatewayWithContext(context.Background(), publishPrivatePathServiceGatewayOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// PublishPrivatePathServiceGatewayWithContext is an alternate form of the PublishPrivatePathServiceGateway method which supports a Context parameter -func (vpc *VpcV1) PublishPrivatePathServiceGatewayWithContext(ctx context.Context, publishPrivatePathServiceGatewayOptions *PublishPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(publishPrivatePathServiceGatewayOptions, "publishPrivatePathServiceGatewayOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(publishPrivatePathServiceGatewayOptions, "publishPrivatePathServiceGatewayOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *publishPrivatePathServiceGatewayOptions.PrivatePathServiceGatewayID, - } - - builder := core.NewRequestBuilder(core.POST) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/publish`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range publishPrivatePathServiceGatewayOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "PublishPrivatePathServiceGateway") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - response, err = vpc.Service.Request(request, nil) - if err != nil { - core.EnrichHTTPProblem(err, "publish_private_path_service_gateway", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - - return -} - -// RevokeAccountForPrivatePathServiceGateway : Revoke access to a private path service gateway for an account -// This request revokes a consumer account. This operation cannot be reversed. The `status` of all endpoint gateway -// bindings associated with the specified private path service gateway become `denied`. If the specified account has an -// existing access policy, that policy will be updated to `denied`. Otherwise, a new `deny` access policy will be -// created for the account. -func (vpc *VpcV1) RevokeAccountForPrivatePathServiceGateway(revokeAccountForPrivatePathServiceGatewayOptions *RevokeAccountForPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.RevokeAccountForPrivatePathServiceGatewayWithContext(context.Background(), revokeAccountForPrivatePathServiceGatewayOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// RevokeAccountForPrivatePathServiceGatewayWithContext is an alternate form of the RevokeAccountForPrivatePathServiceGateway method which supports a Context parameter -func (vpc *VpcV1) RevokeAccountForPrivatePathServiceGatewayWithContext(ctx context.Context, revokeAccountForPrivatePathServiceGatewayOptions *RevokeAccountForPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(revokeAccountForPrivatePathServiceGatewayOptions, "revokeAccountForPrivatePathServiceGatewayOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(revokeAccountForPrivatePathServiceGatewayOptions, "revokeAccountForPrivatePathServiceGatewayOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *revokeAccountForPrivatePathServiceGatewayOptions.PrivatePathServiceGatewayID, - } - - builder := core.NewRequestBuilder(core.POST) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/revoke_account`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range revokeAccountForPrivatePathServiceGatewayOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "RevokeAccountForPrivatePathServiceGateway") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - builder.AddHeader("Content-Type", "application/json") - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - body := make(map[string]interface{}) - if revokeAccountForPrivatePathServiceGatewayOptions.Account != nil { - body["account"] = revokeAccountForPrivatePathServiceGatewayOptions.Account - } - _, err = builder.SetBodyContentJSON(body) - if err != nil { - err = core.SDKErrorf(err, "", "set-json-body-error", common.GetComponentInfo()) - return - } - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - response, err = vpc.Service.Request(request, nil) - if err != nil { - core.EnrichHTTPProblem(err, "revoke_account_for_private_path_service_gateway", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - - return -} - -// UnpublishPrivatePathServiceGateway : Unpublish a private path service gateway -// This request unpublishes a private path service gateway. For this request to succeed, any existing access from other -// accounts must first be revoked. Once unpublished, access will again be restricted to the account that created this -// private path service gateway. -func (vpc *VpcV1) UnpublishPrivatePathServiceGateway(unpublishPrivatePathServiceGatewayOptions *UnpublishPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { - response, err = vpc.UnpublishPrivatePathServiceGatewayWithContext(context.Background(), unpublishPrivatePathServiceGatewayOptions) - err = core.RepurposeSDKProblem(err, "") - return -} - -// UnpublishPrivatePathServiceGatewayWithContext is an alternate form of the UnpublishPrivatePathServiceGateway method which supports a Context parameter -func (vpc *VpcV1) UnpublishPrivatePathServiceGatewayWithContext(ctx context.Context, unpublishPrivatePathServiceGatewayOptions *UnpublishPrivatePathServiceGatewayOptions) (response *core.DetailedResponse, err error) { - err = core.ValidateNotNil(unpublishPrivatePathServiceGatewayOptions, "unpublishPrivatePathServiceGatewayOptions cannot be nil") - if err != nil { - err = core.SDKErrorf(err, "", "unexpected-nil-param", common.GetComponentInfo()) - return - } - err = core.ValidateStruct(unpublishPrivatePathServiceGatewayOptions, "unpublishPrivatePathServiceGatewayOptions") - if err != nil { - err = core.SDKErrorf(err, "", "struct-validation-error", common.GetComponentInfo()) - return - } - - pathParamsMap := map[string]string{ - "private_path_service_gateway_id": *unpublishPrivatePathServiceGatewayOptions.PrivatePathServiceGatewayID, - } - - builder := core.NewRequestBuilder(core.POST) - builder = builder.WithContext(ctx) - builder.EnableGzipCompression = vpc.GetEnableGzipCompression() - _, err = builder.ResolveRequestURL(vpc.Service.Options.URL, `/private_path_service_gateways/{private_path_service_gateway_id}/unpublish`, pathParamsMap) - if err != nil { - err = core.SDKErrorf(err, "", "url-resolve-error", common.GetComponentInfo()) - return - } - - for headerName, headerValue := range unpublishPrivatePathServiceGatewayOptions.Headers { - builder.AddHeader(headerName, headerValue) - } - - sdkHeaders := common.GetSdkHeaders("vpc", "V1", "UnpublishPrivatePathServiceGateway") - for headerName, headerValue := range sdkHeaders { - builder.AddHeader(headerName, headerValue) - } - - builder.AddQuery("version", fmt.Sprint(*vpc.Version)) - builder.AddQuery("generation", fmt.Sprint(*vpc.Generation)) - - request, err := builder.Build() - if err != nil { - err = core.SDKErrorf(err, "", "build-error", common.GetComponentInfo()) - return - } - - response, err = vpc.Service.Request(request, nil) - if err != nil { - core.EnrichHTTPProblem(err, "unpublish_private_path_service_gateway", getServiceComponentInfo()) - err = core.SDKErrorf(err, "", "http-request-err", common.GetComponentInfo()) - return - } - - return -} func getServiceComponentInfo() *core.ProblemComponent { - return core.NewProblemComponent(DefaultServiceName, "2025-04-22") + return core.NewProblemComponent(DefaultServiceName, "2025-08-26") } // AccountIdentity : Identifies an account by a unique property. @@ -34943,7 +35695,7 @@ type BackupPolicyHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -35308,7 +36060,7 @@ type BackupPolicyJobStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -35929,7 +36681,7 @@ type BackupPolicyPlanPrototype struct { // Indicates whether the plan is active. Active *bool `json:"active,omitempty"` - // User tags to attach to each backup (snapshot) created by this plan. If unspecified, no user tags will be attached. + // The user tags to attach to each backup (snapshot) created by this plan. AttachUserTags []string `json:"attach_user_tags,omitempty"` ClonePolicy *BackupPolicyPlanClonePolicyPrototype `json:"clone_policy,omitempty"` @@ -36534,6 +37286,9 @@ type BareMetalServer struct { // The amount of memory, truncated to whole gibibytes. Memory *int64 `json:"memory" validate:"required"` + // The metadata service configuration for the bare metal server. + MetadataService *BareMetalServerMetadataService `json:"metadata_service" validate:"required"` + // The name for this bare metal server. The name is unique across all bare metal servers in the region. Name *string `json:"name" validate:"required"` @@ -36738,6 +37493,11 @@ func UnmarshalBareMetalServer(m map[string]json.RawMessage, result interface{}) err = core.SDKErrorf(err, "", "memory-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "metadata_service", &obj.MetadataService, UnmarshalBareMetalServerMetadataService) + if err != nil { + err = core.SDKErrorf(err, "", "metadata_service-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) @@ -37076,6 +37836,13 @@ func UnmarshalBareMetalServerConsoleAccessToken(m map[string]json.RawMessage, re // BareMetalServerDisk : BareMetalServerDisk struct type BareMetalServerDisk struct { + // The usage constraints to be matched against the requested bare metal server + // properties to determine compatibility. + // + // Only present for disks which are referenced in a bare metal server's `boot_target` + // property. The value of this property will be inherited from the source image at creation. + AllowedUse *BareMetalServerDiskAllowedUse `json:"allowed_use,omitempty"` + // The date and time that the disk was created. CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` @@ -37127,6 +37894,11 @@ const ( // UnmarshalBareMetalServerDisk unmarshals an instance of BareMetalServerDisk from the specified map of raw messages. func UnmarshalBareMetalServerDisk(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(BareMetalServerDisk) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalBareMetalServerDiskAllowedUse) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) if err != nil { err = core.SDKErrorf(err, "", "created_at-error", common.GetComponentInfo()) @@ -37166,6 +37938,41 @@ func UnmarshalBareMetalServerDisk(m map[string]json.RawMessage, result interface return } +// BareMetalServerDiskAllowedUse : BareMetalServerDiskAllowedUse struct +type BareMetalServerDiskAllowedUse struct { + // The API version with which to evaluate the expressions. + // + // If specified, the value must be between `2019-01-01` and today's date (in UTC). If unspecified, the `version` query + // parameter value will be used. + ApiVersion *string `json:"api_version" validate:"required"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using the image data in + // this disk. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server" validate:"required"` +} + +// UnmarshalBareMetalServerDiskAllowedUse unmarshals an instance of BareMetalServerDiskAllowedUse from the specified map of raw messages. +func UnmarshalBareMetalServerDiskAllowedUse(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(BareMetalServerDiskAllowedUse) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // BareMetalServerDiskCollection : BareMetalServerDiskCollection struct type BareMetalServerDiskCollection struct { // The disks for the bare metal server. @@ -37252,7 +38059,7 @@ type BareMetalServerHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -37289,6 +38096,10 @@ func UnmarshalBareMetalServerHealthReason(m map[string]json.RawMessage, result i // BareMetalServerInitialization : BareMetalServerInitialization struct type BareMetalServerInitialization struct { + // The default trusted profile configuration specified at bare metal server + // initialization. If absent, no default trusted profile was specified. + DefaultTrustedProfile *BareMetalServerInitializationDefaultTrustedProfile `json:"default_trusted_profile,omitempty"` + // The image the bare metal server was provisioned from. Image *ImageReference `json:"image" validate:"required"` @@ -37303,6 +38114,11 @@ type BareMetalServerInitialization struct { // UnmarshalBareMetalServerInitialization unmarshals an instance of BareMetalServerInitialization from the specified map of raw messages. func UnmarshalBareMetalServerInitialization(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(BareMetalServerInitialization) + err = core.UnmarshalModel(m, "default_trusted_profile", &obj.DefaultTrustedProfile, UnmarshalBareMetalServerInitializationDefaultTrustedProfile) + if err != nil { + err = core.SDKErrorf(err, "", "default_trusted_profile-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "image", &obj.Image, UnmarshalImageReference) if err != nil { err = core.SDKErrorf(err, "", "image-error", common.GetComponentInfo()) @@ -37322,8 +38138,81 @@ func UnmarshalBareMetalServerInitialization(m map[string]json.RawMessage, result return } +// BareMetalServerInitializationDefaultTrustedProfile : BareMetalServerInitializationDefaultTrustedProfile struct +type BareMetalServerInitializationDefaultTrustedProfile struct { + // If set to `true`, the system created a link to the specified `target` trusted profile during server initialization. + // Regardless of whether a link was created by the system or manually using the IAM Identity service, the link will be + // automatically deleted when the server is deleted. + AutoLink *bool `json:"auto_link" validate:"required"` + + // The default IAM trusted profile to use for this bare metal server. + Target *TrustedProfileReference `json:"target" validate:"required"` +} + +// UnmarshalBareMetalServerInitializationDefaultTrustedProfile unmarshals an instance of BareMetalServerInitializationDefaultTrustedProfile from the specified map of raw messages. +func UnmarshalBareMetalServerInitializationDefaultTrustedProfile(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(BareMetalServerInitializationDefaultTrustedProfile) + err = core.UnmarshalPrimitive(m, "auto_link", &obj.AutoLink) + if err != nil { + err = core.SDKErrorf(err, "", "auto_link-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "target", &obj.Target, UnmarshalTrustedProfileReference) + if err != nil { + err = core.SDKErrorf(err, "", "target-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// BareMetalServerInitializationDefaultTrustedProfilePrototype : BareMetalServerInitializationDefaultTrustedProfilePrototype struct +type BareMetalServerInitializationDefaultTrustedProfilePrototype struct { + // If set to `true`, the system will create a link to the specified `target` trusted profile during server creation. + // Regardless of whether a link is created by the system or manually using the IAM Identity service, it will be + // automatically deleted when the server is deleted. + AutoLink *bool `json:"auto_link,omitempty"` + + // The default IAM trusted profile to use for this bare metal server. + Target TrustedProfileIdentityIntf `json:"target" validate:"required"` +} + +// NewBareMetalServerInitializationDefaultTrustedProfilePrototype : Instantiate BareMetalServerInitializationDefaultTrustedProfilePrototype (Generic Model Constructor) +func (*VpcV1) NewBareMetalServerInitializationDefaultTrustedProfilePrototype(target TrustedProfileIdentityIntf) (_model *BareMetalServerInitializationDefaultTrustedProfilePrototype, err error) { + _model = &BareMetalServerInitializationDefaultTrustedProfilePrototype{ + Target: target, + } + err = core.ValidateStruct(_model, "required parameters") + if err != nil { + err = core.SDKErrorf(err, "", "model-missing-required", common.GetComponentInfo()) + } + return +} + +// UnmarshalBareMetalServerInitializationDefaultTrustedProfilePrototype unmarshals an instance of BareMetalServerInitializationDefaultTrustedProfilePrototype from the specified map of raw messages. +func UnmarshalBareMetalServerInitializationDefaultTrustedProfilePrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(BareMetalServerInitializationDefaultTrustedProfilePrototype) + err = core.UnmarshalPrimitive(m, "auto_link", &obj.AutoLink) + if err != nil { + err = core.SDKErrorf(err, "", "auto_link-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "target", &obj.Target, UnmarshalTrustedProfileIdentity) + if err != nil { + err = core.SDKErrorf(err, "", "target-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // BareMetalServerInitializationPrototype : BareMetalServerInitializationPrototype struct type BareMetalServerInitializationPrototype struct { + // The default trusted profile to be used when initializing the bare metal server. + // + // If unspecified, no default trusted profile will be made available. + DefaultTrustedProfile *BareMetalServerInitializationDefaultTrustedProfilePrototype `json:"default_trusted_profile,omitempty"` + // The image to be used when provisioning the bare metal server. Image ImageIdentityIntf `json:"image" validate:"required"` @@ -37336,9 +38225,7 @@ type BareMetalServerInitializationPrototype struct { // inaccessible unless the specified image provides another means of access. Keys []KeyIdentityIntf `json:"keys" validate:"required"` - // User data to be made available when initializing the bare metal server. - // - // If unspecified, no user data will be made available. + // The user data to be made available when initializing the bare metal server. UserData *string `json:"user_data,omitempty"` } @@ -37358,6 +38245,11 @@ func (*VpcV1) NewBareMetalServerInitializationPrototype(image ImageIdentityIntf, // UnmarshalBareMetalServerInitializationPrototype unmarshals an instance of BareMetalServerInitializationPrototype from the specified map of raw messages. func UnmarshalBareMetalServerInitializationPrototype(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(BareMetalServerInitializationPrototype) + err = core.UnmarshalModel(m, "default_trusted_profile", &obj.DefaultTrustedProfile, UnmarshalBareMetalServerInitializationDefaultTrustedProfilePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "default_trusted_profile-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "image", &obj.Image, UnmarshalImageIdentity) if err != nil { err = core.SDKErrorf(err, "", "image-error", common.GetComponentInfo()) @@ -37381,7 +38273,7 @@ func UnmarshalBareMetalServerInitializationPrototype(m map[string]json.RawMessag // Models which "extend" this model: // - BareMetalServerInitializationUserAccountBareMetalServerInitializationHostUserAccount type BareMetalServerInitializationUserAccount struct { - // The password at initialization, encrypted using `encryption_key`, and returned base64-encoded. + // The administrator password at initialization, encrypted using `encryption_key`, and returned base64-encoded. EncryptedPassword *[]byte `json:"encrypted_password,omitempty"` // The public SSH key used to encrypt the password. @@ -37449,7 +38341,7 @@ type BareMetalServerLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -37488,6 +38380,136 @@ func UnmarshalBareMetalServerLifecycleReason(m map[string]json.RawMessage, resul return } +// BareMetalServerMetadataService : The metadata service configuration for the bare metal server. +type BareMetalServerMetadataService struct { + // Indicates whether the metadata service endpoint is available to the bare metal server. + Enabled *bool `json:"enabled" validate:"required"` + + // The communication protocol to use for the metadata service endpoint. Applies only when the metadata service is + // enabled. + // - `http`: HTTP protocol (unencrypted) + // - `https`: HTTP Secure protocol. + Protocol *string `json:"protocol" validate:"required"` +} + +// Constants associated with the BareMetalServerMetadataService.Protocol property. +// The communication protocol to use for the metadata service endpoint. Applies only when the metadata service is +// enabled. +// - `http`: HTTP protocol (unencrypted) +// - `https`: HTTP Secure protocol. +const ( + BareMetalServerMetadataServiceProtocolHTTPConst = "http" + BareMetalServerMetadataServiceProtocolHTTPSConst = "https" +) + +// UnmarshalBareMetalServerMetadataService unmarshals an instance of BareMetalServerMetadataService from the specified map of raw messages. +func UnmarshalBareMetalServerMetadataService(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(BareMetalServerMetadataService) + err = core.UnmarshalPrimitive(m, "enabled", &obj.Enabled) + if err != nil { + err = core.SDKErrorf(err, "", "enabled-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "protocol", &obj.Protocol) + if err != nil { + err = core.SDKErrorf(err, "", "protocol-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// BareMetalServerMetadataServicePatch : The metadata service configuration for the bare metal server. +type BareMetalServerMetadataServicePatch struct { + // Indicates whether the metadata service endpoint will be available to the bare metal server. + Enabled *bool `json:"enabled,omitempty"` + + // The communication protocol to use for the metadata service endpoint. Applies only when the metadata service is + // enabled. + // - `http`: HTTP protocol (unencrypted) + // - `https`: HTTP Secure protocol. + Protocol *string `json:"protocol,omitempty"` +} + +// Constants associated with the BareMetalServerMetadataServicePatch.Protocol property. +// The communication protocol to use for the metadata service endpoint. Applies only when the metadata service is +// enabled. +// - `http`: HTTP protocol (unencrypted) +// - `https`: HTTP Secure protocol. +const ( + BareMetalServerMetadataServicePatchProtocolHTTPConst = "http" + BareMetalServerMetadataServicePatchProtocolHTTPSConst = "https" +) + +// UnmarshalBareMetalServerMetadataServicePatch unmarshals an instance of BareMetalServerMetadataServicePatch from the specified map of raw messages. +func UnmarshalBareMetalServerMetadataServicePatch(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(BareMetalServerMetadataServicePatch) + err = core.UnmarshalPrimitive(m, "enabled", &obj.Enabled) + if err != nil { + err = core.SDKErrorf(err, "", "enabled-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "protocol", &obj.Protocol) + if err != nil { + err = core.SDKErrorf(err, "", "protocol-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// asPatch returns a generic map representation of the BareMetalServerMetadataServicePatch +func (bareMetalServerMetadataServicePatch *BareMetalServerMetadataServicePatch) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(bareMetalServerMetadataServicePatch.Enabled) { + _patch["enabled"] = bareMetalServerMetadataServicePatch.Enabled + } + if !core.IsNil(bareMetalServerMetadataServicePatch.Protocol) { + _patch["protocol"] = bareMetalServerMetadataServicePatch.Protocol + } + + return +} + +// BareMetalServerMetadataServicePrototype : The metadata service configuration for the bare metal server. +type BareMetalServerMetadataServicePrototype struct { + // Indicates whether the metadata service endpoint will be available to the bare metal server. + Enabled *bool `json:"enabled,omitempty"` + + // The communication protocol to use for the metadata service endpoint. Applies only when the metadata service is + // enabled. + // - `http`: HTTP protocol (unencrypted) + // - `https`: HTTP Secure protocol. + Protocol *string `json:"protocol,omitempty"` +} + +// Constants associated with the BareMetalServerMetadataServicePrototype.Protocol property. +// The communication protocol to use for the metadata service endpoint. Applies only when the metadata service is +// enabled. +// - `http`: HTTP protocol (unencrypted) +// - `https`: HTTP Secure protocol. +const ( + BareMetalServerMetadataServicePrototypeProtocolHTTPConst = "http" + BareMetalServerMetadataServicePrototypeProtocolHTTPSConst = "https" +) + +// UnmarshalBareMetalServerMetadataServicePrototype unmarshals an instance of BareMetalServerMetadataServicePrototype from the specified map of raw messages. +func UnmarshalBareMetalServerMetadataServicePrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(BareMetalServerMetadataServicePrototype) + err = core.UnmarshalPrimitive(m, "enabled", &obj.Enabled) + if err != nil { + err = core.SDKErrorf(err, "", "enabled-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "protocol", &obj.Protocol) + if err != nil { + err = core.SDKErrorf(err, "", "protocol-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // BareMetalServerNetworkAttachment : BareMetalServerNetworkAttachment struct // Models which "extend" this model: // - BareMetalServerNetworkAttachmentByPci @@ -37949,9 +38971,9 @@ type BareMetalServerNetworkAttachmentPrototypeVirtualNetworkInterface struct { // `bare_metal_server_network_attachment`. EnableInfrastructureNat *bool `json:"enable_infrastructure_nat,omitempty"` - // Additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP identity, or - // a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be in the - // primary IP's subnet. + // The additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP + // identity, or a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be + // in the primary IP's subnet. // // If reserved IP identities are provided, the specified reserved IPs must be unbound. // @@ -38793,6 +39815,9 @@ type BareMetalServerPatch struct { // `stopped`. EnableSecureBoot *bool `json:"enable_secure_boot,omitempty"` + // The metadata service configuration for the bare metal server. + MetadataService *BareMetalServerMetadataServicePatch `json:"metadata_service,omitempty"` + // The name for this bare metal server. The name must not be used by another bare metal server in the region. Changing // the name will not affect the system hostname. Name *string `json:"name,omitempty"` @@ -38815,6 +39840,11 @@ func UnmarshalBareMetalServerPatch(m map[string]json.RawMessage, result interfac err = core.SDKErrorf(err, "", "enable_secure_boot-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "metadata_service", &obj.MetadataService, UnmarshalBareMetalServerMetadataServicePatch) + if err != nil { + err = core.SDKErrorf(err, "", "metadata_service-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) @@ -38843,6 +39873,9 @@ func (bareMetalServerPatch *BareMetalServerPatch) AsPatch() (_patch map[string]i if !core.IsNil(bareMetalServerPatch.EnableSecureBoot) { _patch["enable_secure_boot"] = bareMetalServerPatch.EnableSecureBoot } + if !core.IsNil(bareMetalServerPatch.MetadataService) { + _patch["metadata_service"] = bareMetalServerPatch.MetadataService.asPatch() + } if !core.IsNil(bareMetalServerPatch.Name) { _patch["name"] = bareMetalServerPatch.Name } @@ -39303,9 +40336,6 @@ func UnmarshalBareMetalServerProfileBandwidth(m map[string]json.RawMessage, resu // BareMetalServerProfileCpuArchitecture : BareMetalServerProfileCpuArchitecture struct type BareMetalServerProfileCpuArchitecture struct { - // The default CPU architecture for a bare metal server with this profile. - Default *string `json:"default,omitempty"` - // The type for this profile field. Type *string `json:"type" validate:"required"` @@ -39313,13 +40343,6 @@ type BareMetalServerProfileCpuArchitecture struct { Value *string `json:"value" validate:"required"` } -// Constants associated with the BareMetalServerProfileCpuArchitecture.Default property. -// The default CPU architecture for a bare metal server with this profile. -const ( - BareMetalServerProfileCpuArchitectureDefaultAmd64Const = "amd64" - BareMetalServerProfileCpuArchitectureDefaultS390xConst = "s390x" -) - // Constants associated with the BareMetalServerProfileCpuArchitecture.Type property. // The type for this profile field. const ( @@ -39336,11 +40359,6 @@ const ( // UnmarshalBareMetalServerProfileCpuArchitecture unmarshals an instance of BareMetalServerProfileCpuArchitecture from the specified map of raw messages. func UnmarshalBareMetalServerProfileCpuArchitecture(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(BareMetalServerProfileCpuArchitecture) - err = core.UnmarshalPrimitive(m, "default", &obj.Default) - if err != nil { - err = core.SDKErrorf(err, "", "default-error", common.GetComponentInfo()) - return - } err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { err = core.SDKErrorf(err, "", "type-error", common.GetComponentInfo()) @@ -40342,6 +41360,9 @@ type BareMetalServerPrototype struct { Initialization *BareMetalServerInitializationPrototype `json:"initialization" validate:"required"` + // The metadata service configuration for the bare metal server. + MetadataService *BareMetalServerMetadataServicePrototype `json:"metadata_service,omitempty"` + // The name for this bare metal server. The name must not be used by another bare metal server in the region. If // unspecified, the name will be a hyphenated list of randomly-selected words. // @@ -40408,6 +41429,11 @@ func UnmarshalBareMetalServerPrototype(m map[string]json.RawMessage, result inte err = core.SDKErrorf(err, "", "initialization-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "metadata_service", &obj.MetadataService, UnmarshalBareMetalServerMetadataServicePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "metadata_service-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) @@ -40652,7 +41678,7 @@ type BareMetalServerStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -41658,7 +42684,7 @@ type ClusterNetworkInterfaceLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -41954,7 +42980,7 @@ type ClusterNetworkLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -42556,7 +43582,7 @@ type ClusterNetworkSubnetLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -43032,7 +44058,7 @@ type ClusterNetworkSubnetReservedIPLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -43296,7 +44322,7 @@ type CreateBackupPolicyPlanOptions struct { // Indicates whether the plan is active. Active *bool `json:"active,omitempty"` - // User tags to attach to each backup (snapshot) created by this plan. If unspecified, no user tags will be attached. + // The user tags to attach to each backup (snapshot) created by this plan. AttachUserTags []string `json:"attach_user_tags,omitempty"` ClonePolicy *BackupPolicyPlanClonePolicyPrototype `json:"clone_policy,omitempty"` @@ -43554,8 +44580,8 @@ type CreateClusterNetworkAttachmentOptions struct { InstanceID *string `json:"instance_id" validate:"required,ne="` // A cluster network interface for the instance cluster network attachment. This can be - // specified using an existing cluster network interface that does not already have a `target`, - // or a prototype object for a new cluster network interface. + // specified using an existing cluster network interface that does not already have a + // `target`, or a prototype object for a new cluster network interface. // // This instance must reside in the same VPC as the specified cluster network interface. The // cluster network interface must reside in the same cluster network as the @@ -43968,8 +44994,15 @@ func (options *CreateDedicatedHostOptions) SetHeaders(param map[string]string) * type CreateEndpointGatewayOptions struct { // The target to use for this endpoint gateway. The target: // - Must not already be the target of another endpoint gateway in the VPC - // - Must not have a service endpoint that duplicates or overlaps with any `service_endpoints` - // of another endpoint gateway in the VPC. + // - Must not have a service endpoint that overlaps with any `service_endpoints` of + // another endpoint gateway in the VPC. + // + // If `allow_dns_resolution_binding` is `true`, then there must not be another endpoint + // gateway with `allow_dns_resolution_binding` set to `true` in the [DNS + // sharing](/docs/vpc?topic=vpc-vpe-dns-sharing) connected topology that: + // - Has the same `target` as this endpoint gateway + // - Has `service_endpoints` that overlap with the `service_endpoints` for this endpoint + // gateway. Target EndpointGatewayTargetPrototypeIntf `json:"target" validate:"required"` // The VPC this endpoint gateway will reside in. @@ -43978,6 +45011,13 @@ type CreateEndpointGatewayOptions struct { // Indicates whether to allow DNS resolution for this endpoint gateway when the VPC this endpoint gateway resides in // has a DNS resolution binding to a VPC with `dns.enable_hub` set to `true`. // + // If `true`, then there must not be another endpoint gateway with + // `allow_dns_resolution_binding` set to `true` in the [DNS sharing](/docs/vpc?topic=vpc-vpe-dns-sharing) connected + // topology that: + // - Has the same `target` as this endpoint gateway + // - Has `service_endpoints` that overlap with the `service_endpoints` for this endpoint + // gateway. + // // Must be `true` if the VPC this endpoint gateway resides in has `dns.enable_hub` set to // `true`. AllowDnsResolutionBinding *bool `json:"allow_dns_resolution_binding,omitempty"` @@ -44609,10 +45649,9 @@ func (options *CreateInstanceGroupManagerPolicyOptions) SetHeaders(param map[str // CreateInstanceGroupOptions : The CreateInstanceGroup options. type CreateInstanceGroupOptions struct { - // Instance template to use when creating new instances. + // The instance template to use when creating new instances. // - // Instance groups are not compatible with instance templates that specify `true` for - // `default_trusted_profile.auto_link`. + // The specified template must not have `default_trusted_profile.auto_link` set to `true`. InstanceTemplate InstanceTemplateIdentityIntf `json:"instance_template" validate:"required"` // The subnets to use when creating new instances. @@ -45411,7 +46450,7 @@ type CreateLoadBalancerListenerPolicyOptions struct { // - `reject`: Requests will be rejected with a `403` status code. Action *string `json:"action" validate:"required"` - // Priority of the policy. The priority is unique across all policies for this load balancer listener. Lower value + // The priority of the policy. The priority is unique across all policies for this load balancer listener. Lower value // indicates higher priority. Priority *int64 `json:"priority" validate:"required"` @@ -45833,7 +46872,7 @@ type CreateLoadBalancerPoolMemberOptions struct { // be shared by a pool member of any other load balancer in the same VPC. Target LoadBalancerPoolMemberTargetPrototypeIntf `json:"target" validate:"required"` - // The weight of the server member. + // The weight of the member. // // If specified, the pool algorithm must be `weighted_round_robin` and the load balancer must be in the `application` // family. @@ -46353,6 +47392,64 @@ func (options *CreatePrivatePathServiceGatewayOptions) SetHeaders(param map[stri return options } +// CreatePublicAddressRangeOptions : The CreatePublicAddressRange options. +type CreatePublicAddressRangeOptions struct { + // The total number of public IPv4 addresses required. Must be a power of 2. + Ipv4AddressCount *int64 `json:"ipv4_address_count" validate:"required"` + + // The name for this public address range. The name must not be used by another public address range in the region. If + // unspecified, the name will be a hyphenated list of randomly-selected words. + Name *string `json:"name,omitempty"` + + // The resource group to use. If unspecified, the account's [default resource + // group](https://cloud.ibm.com/apidocs/resource-manager#introduction) will be used. + ResourceGroup ResourceGroupIdentityIntf `json:"resource_group,omitempty"` + + // The target to bind this public address range to. If unspecified, the public address + // range will not be bound to a target at creation. + Target *PublicAddressRangeTargetPrototype `json:"target,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewCreatePublicAddressRangeOptions : Instantiate CreatePublicAddressRangeOptions +func (*VpcV1) NewCreatePublicAddressRangeOptions(ipv4AddressCount int64) *CreatePublicAddressRangeOptions { + return &CreatePublicAddressRangeOptions{ + Ipv4AddressCount: core.Int64Ptr(ipv4AddressCount), + } +} + +// SetIpv4AddressCount : Allow user to set Ipv4AddressCount +func (_options *CreatePublicAddressRangeOptions) SetIpv4AddressCount(ipv4AddressCount int64) *CreatePublicAddressRangeOptions { + _options.Ipv4AddressCount = core.Int64Ptr(ipv4AddressCount) + return _options +} + +// SetName : Allow user to set Name +func (_options *CreatePublicAddressRangeOptions) SetName(name string) *CreatePublicAddressRangeOptions { + _options.Name = core.StringPtr(name) + return _options +} + +// SetResourceGroup : Allow user to set ResourceGroup +func (_options *CreatePublicAddressRangeOptions) SetResourceGroup(resourceGroup ResourceGroupIdentityIntf) *CreatePublicAddressRangeOptions { + _options.ResourceGroup = resourceGroup + return _options +} + +// SetTarget : Allow user to set Target +func (_options *CreatePublicAddressRangeOptions) SetTarget(target *PublicAddressRangeTargetPrototype) *CreatePublicAddressRangeOptions { + _options.Target = target + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *CreatePublicAddressRangeOptions) SetHeaders(param map[string]string) *CreatePublicAddressRangeOptions { + options.Headers = param + return options +} + // CreatePublicGatewayOptions : The CreatePublicGateway options. type CreatePublicGatewayOptions struct { // The VPC this public gateway will reside in. @@ -46986,9 +48083,9 @@ type CreateVirtualNetworkInterfaceOptions struct { // `bare_metal_server_network_attachment`. EnableInfrastructureNat *bool `json:"enable_infrastructure_nat,omitempty"` - // Additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP identity, or - // a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be in the - // primary IP's subnet. + // The additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP + // identity, or a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be + // in the primary IP's subnet. // // If reserved IP identities are provided, the specified reserved IPs must be unbound. // @@ -47241,12 +48338,12 @@ type CreateVPCDnsResolutionBindingOptions struct { // The VPC identifier. VPCID *string `json:"vpc_id" validate:"required,ne="` - // Another VPC to bind this VPC to for DNS resolution. The VPC must have - // `dns.enable_hub` set to `true`, and may be in a different account (subject to - // IAM policies). + // The VPC to bind this VPC to for DNS resolution. The VPC must be different from the VPC + // specified in the URL, must have `dns.enable_hub` set to `true`, and may be in a + // different account (subject to IAM policies). // - // Additionally, the VPC specified in the URL (this VPC) must have `dns.enable_hub` - // set to `false` and a `dns.resolution_binding_count` of zero. + // Additionally, the VPC specified in the URL (this VPC) must have `dns.enable_hub` set + // to `false` and a `dns.resolution_binding_count` of zero. VPC VPCIdentityIntf `json:"vpc" validate:"required"` // The name for this DNS resolution binding. The name must not be used by another DNS resolution binding for the VPC. @@ -47303,9 +48400,9 @@ type CreateVPCOptions struct { // private network connectivity to the account's Classic Infrastructure resources. Only one VPC, per region, may be // connected in this way. This value is set at creation and subsequently immutable. // - // This property has been deprecated. Instead, use a [Transit Gateway](https://cloud.ibm.com/docs/transit-gateway) to - // connect this VPC to Classic Infrastructure. For more information, see [upcoming - // changes](https://cloud.ibm.com/docs/vpc?topic=vpc-api-change-log#upcoming-changes). + // Setting this property to `true` is supported only for accounts that have been + // [granted approval](https://cloud.ibm.com/docs/vpc?topic=vpc-setting-up-access-to-classic-infrastructure). Instead, + // use a [Transit Gateway](https://cloud.ibm.com/docs/transit-gateway) to connect this VPC to Classic Infrastructure. // Deprecated: this field is deprecated and may be removed in a future release. ClassicAccess *bool `json:"classic_access,omitempty"` @@ -48187,7 +49284,8 @@ type DnsServerPrototype struct { // The DNS server IPv4 address. Address *string `json:"address,omitempty"` - // DHCP configuration for the specified zone will have this DNS server listed first. + // If specified, DHCP configuration for the specified zone will have this DNS server listed + // first. ZoneAffinity ZoneIdentityIntf `json:"zone_affinity,omitempty"` } @@ -48584,7 +49682,7 @@ type DedicatedHostDisk struct { // The unique identifier for this disk. ID *string `json:"id" validate:"required"` - // Instance disks that are on this dedicated host disk. + // The instance disks that are on this dedicated host disk. InstanceDisks []InstanceDiskReference `json:"instance_disks" validate:"required"` // The disk interface used for attaching the disk. @@ -50156,8 +51254,12 @@ type DefaultNetworkACL struct { // resource group at creation. ResourceGroup *ResourceGroupReference `json:"resource_group" validate:"required"` - // The ordered rules for the default network ACL for a VPC. Defaults to two rules which allow ICMP, TCP and UDP inbound - // and outbound traffic, respectively. Rules for the default network ACL may be changed, added, or removed. + // The ordered rules for the default network ACL for a VPC. Created with: + // - The first rule, named `allow-inbound`, allowing ICMP, TCP and UDP inbound traffic. + // - The second rule, named `allow-outbound`, allowing ICMP, TCP, and UDP outbound + // traffic. + // + // Rules for the default network ACL may be changed, added, or removed. Rules []NetworkACLRuleItemIntf `json:"rules" validate:"required"` // The subnets to which this network ACL is attached. @@ -50223,6 +51325,9 @@ func UnmarshalDefaultNetworkACL(m map[string]json.RawMessage, result interface{} type DefaultRoutingTable struct { // The filters specifying the resources that may create routes in this routing table. // + // Created with filters allowing `vpn_gateway` and `vpn_server` resources to create routes, but filters may be added or + // removed with subsequent requests. + // // The resources and types of filters supported by this property is expected to // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. AcceptRoutesFrom []ResourceFilter `json:"accept_routes_from" validate:"required"` @@ -50265,6 +51370,8 @@ type DefaultRoutingTable struct { // Indicates whether this routing table is used to route traffic that originates from // [Direct Link](https://cloud.ibm.com/docs/dl) to this VPC. // + // Set to `false` at VPC creation, but may be updated with subsequent requests. + // // Incoming traffic will be routed according to the routing table with one exception: routes with an `action` of // `deliver` are treated as `drop` unless the `next_hop` is an IP address in a subnet in the route's `zone` that is // able to accept traffic. Therefore, if an incoming packet matches a route with a `next_hop` of a VPN gateway @@ -50273,18 +51380,22 @@ type DefaultRoutingTable struct { // Indicates whether this routing table is used to route traffic that originates from the internet. // + // Set to `false` at VPC creation, but may be updated with subsequent requests. + // // Incoming traffic will be routed according to the routing table with two exceptions: // - Traffic destined for IP addresses associated with public gateways will not be // subject to routes in this routing table. - // - Routes with an `action` of `deliver` are treated as `drop` unless the `next_hop` is - // an IP address in a subnet in the route's `zone` that is able to accept traffic. - // Therefore, if an incoming packet matches a route with a `next_hop` of a VPN gateway - // connection, the packet will be dropped. + // - Routes with an `action` of `deliver` are treated as `drop` unless the `next_hop` + // is an IP address in a subnet in the route's `zone` that is able to accept traffic. + // Therefore, if an incoming packet matches a route with a `next_hop` of a VPN + // gateway connection, the packet will be dropped. RouteInternetIngress *bool `json:"route_internet_ingress" validate:"required"` // Indicates whether this routing table is used to route traffic that originates from from [Transit // Gateway](https://cloud.ibm.com/docs/transit-gateway) to this VPC. // + // Set to `false` at VPC creation, but may be updated with subsequent requests. + // // Incoming traffic will be routed according to the routing table with one exception: routes with an `action` of // `deliver` are treated as `drop` unless the `next_hop` is an IP address in a subnet in the route's `zone` that is // able to accept traffic. Therefore, if an incoming packet matches a route with a `next_hop` of a VPN gateway @@ -50294,6 +51405,8 @@ type DefaultRoutingTable struct { // Indicates whether this routing table is used to route traffic that originates from subnets in other zones in this // VPC. // + // Set to `false` at VPC creation, but may be updated with subsequent requests. + // // Incoming traffic will be routed according to the routing table with one exception: routes with an `action` of // `deliver` are treated as `drop` unless the `next_hop` is an IP address in a subnet in the route's `zone` that is // able to accept traffic. Therefore, if an incoming packet matches a route with a `next_hop` of a VPN gateway @@ -50449,9 +51562,12 @@ type DefaultSecurityGroup struct { // The resource group for this security group. ResourceGroup *ResourceGroupReference `json:"resource_group" validate:"required"` - // The rules for the default security group for a VPC. Defaults to allowing ICMP, TCP and UDP outbound traffic, and - // allowing ICMP, TCP and UDP inbound traffic from other interfaces in the VPC's default security group. Rules for the - // default security group may be changed, added or removed. + // The rules for the default security group for a VPC. Created with: + // - A rule allowing inbound ICMP, TCP and UDP traffic from other interfaces in the + // VPC's default security group + // - A rule allowing outbound ICMP, TCP and UDP traffic to any destination + // + // Rules for the default security group may be changed, added or removed. Rules []SecurityGroupRuleIntf `json:"rules" validate:"required"` // The targets for this security group. @@ -52079,6 +53195,34 @@ func (options *DeletePrivatePathServiceGatewayOptions) SetHeaders(param map[stri return options } +// DeletePublicAddressRangeOptions : The DeletePublicAddressRange options. +type DeletePublicAddressRangeOptions struct { + // The public address range identifier. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewDeletePublicAddressRangeOptions : Instantiate DeletePublicAddressRangeOptions +func (*VpcV1) NewDeletePublicAddressRangeOptions(id string) *DeletePublicAddressRangeOptions { + return &DeletePublicAddressRangeOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *DeletePublicAddressRangeOptions) SetID(id string) *DeletePublicAddressRangeOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *DeletePublicAddressRangeOptions) SetHeaders(param map[string]string) *DeletePublicAddressRangeOptions { + options.Headers = param + return options +} + // DeletePublicGatewayOptions : The DeletePublicGateway options. type DeletePublicGatewayOptions struct { // The public gateway identifier. @@ -53108,7 +54252,7 @@ func (options *DeleteVPNServerRouteOptions) SetHeaders(param map[string]string) // Deleted : If present, this property indicates the referenced resource has been deleted, and provides some supplementary // information. type Deleted struct { - // Link to documentation about deleted resources. + // A link to documentation about deleted resources. MoreInfo *string `json:"more_info" validate:"required"` } @@ -53579,7 +54723,7 @@ type EndpointGatewayLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -53631,6 +54775,13 @@ type EndpointGatewayPatch struct { // Indicates whether to allow DNS resolution for this endpoint gateway when the VPC this endpoint gateway resides in // has a DNS resolution binding to a VPC with `dns.enable_hub` set to `true`. // + // If `true`, then there must not be another endpoint gateway with + // `allow_dns_resolution_binding` set to `true` in the [DNS sharing](/docs/vpc?topic=vpc-vpe-dns-sharing) connected + // topology that: + // - Has the same `target` as this endpoint gateway + // - Has `service_endpoints` that overlap with the `service_endpoints` for this endpoint + // gateway. + // // Must be `true` if the VPC this endpoint gateway resides in has `dns.enable_hub` set to // `true`. AllowDnsResolutionBinding *bool `json:"allow_dns_resolution_binding,omitempty"` @@ -53930,8 +55081,15 @@ func UnmarshalEndpointGatewayTarget(m map[string]json.RawMessage, result interfa // EndpointGatewayTargetPrototype : The target to use for this endpoint gateway. The target: // - Must not already be the target of another endpoint gateway in the VPC -// - Must not have a service endpoint that duplicates or overlaps with any `service_endpoints` -// of another endpoint gateway in the VPC. +// - Must not have a service endpoint that overlaps with any `service_endpoints` of +// another endpoint gateway in the VPC. +// +// If `allow_dns_resolution_binding` is `true`, then there must not be another endpoint gateway with +// `allow_dns_resolution_binding` set to `true` in the [DNS sharing](/docs/vpc?topic=vpc-vpe-dns-sharing) connected +// topology that: +// - Has the same `target` as this endpoint gateway +// - Has `service_endpoints` that overlap with the `service_endpoints` for this endpoint +// gateway. // // Models which "extend" this model: // - EndpointGatewayTargetPrototypeEndpointGatewayTargetResourceTypePrivatePathServiceGatewayPrototype @@ -57313,6 +58471,34 @@ func (options *GetPrivatePathServiceGatewayOptions) SetHeaders(param map[string] return options } +// GetPublicAddressRangeOptions : The GetPublicAddressRange options. +type GetPublicAddressRangeOptions struct { + // The public address range identifier. + ID *string `json:"id" validate:"required,ne="` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewGetPublicAddressRangeOptions : Instantiate GetPublicAddressRangeOptions +func (*VpcV1) NewGetPublicAddressRangeOptions(id string) *GetPublicAddressRangeOptions { + return &GetPublicAddressRangeOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *GetPublicAddressRangeOptions) SetID(id string) *GetPublicAddressRangeOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *GetPublicAddressRangeOptions) SetHeaders(param map[string]string) *GetPublicAddressRangeOptions { + options.Headers = param + return options +} + // GetPublicGatewayOptions : The GetPublicGateway options. type GetPublicGatewayOptions struct { // The public gateway identifier. @@ -59659,6 +60845,10 @@ func UnmarshalIPsecPolicyReference(m map[string]json.RawMessage, result interfac // Image : Image struct type Image struct { + // The usage constraints to match against the requested instance or bare metal server + // properties to determine compatibility. + AllowedUse *ImageAllowedUse `json:"allowed_use" validate:"required"` + CatalogOffering *ImageCatalogOffering `json:"catalog_offering" validate:"required"` // The date and time that the image was created. @@ -59681,7 +60871,7 @@ type Image struct { // This property will be present for images with an `encryption` type of `user_managed`. EncryptionKey *EncryptionKeyReference `json:"encryption_key,omitempty"` - // Details for the stored image file. + // The metadata for the imported image file. File *ImageFile `json:"file" validate:"required"` // The URL for this image. @@ -59706,10 +60896,9 @@ type Image struct { // The operating system included in this image. OperatingSystem *OperatingSystem `json:"operating_system" validate:"required"` - // The owner type of this image: - // - `user`: Owned by this account - // - `provider`: Owned by a different account. - OwnerType *string `json:"owner_type" validate:"required"` + // If present, this property indicates that the resource associated with this reference + // is remote and therefore may not be directly retrievable. + Remote *ImageRemote `json:"remote,omitempty"` // The resource group for this image. ResourceGroup *ResourceGroupReference `json:"resource_group" validate:"required"` @@ -59723,19 +60912,23 @@ type Image struct { SourceVolume *VolumeReference `json:"source_volume,omitempty"` // The status of this image: - // - available: image can be used (provisionable) - // - deleting: image is being deleted, and can no longer be used to provision new + // - available: image can be used to create resources + // - deleting: image is being deleted, and can no longer be used to create // resources - // - deprecated: image is administratively slated to become `obsolete` - // - failed: image is corrupt or did not pass validation - // - obsolete: image administratively set to not be used for new resources - // - pending: image is being imported and is not yet `available` + // - deprecated: image is slated to be deleted, but can still be used to create + // resources + // - failed: image was not created successfully, and cannot be used to create + // resources + // - obsolete: image is slated to be deleted, and can no longer be used to create + // resources + // - pending: image is being imported, and cannot yet be used to create resources // - unusable: image cannot be used (see `status_reasons[]` for possible remediation) // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. Status *string `json:"status" validate:"required"` + // The reasons for the current status (if any). StatusReasons []ImageStatusReason `json:"status_reasons" validate:"required"` // The user data format for this image: @@ -59760,15 +60953,6 @@ const ( ImageEncryptionUserManagedConst = "user_managed" ) -// Constants associated with the Image.OwnerType property. -// The owner type of this image: -// - `user`: Owned by this account -// - `provider`: Owned by a different account. -const ( - ImageOwnerTypeProviderConst = "provider" - ImageOwnerTypeUserConst = "user" -) - // Constants associated with the Image.ResourceType property. // The resource type. const ( @@ -59777,13 +60961,16 @@ const ( // Constants associated with the Image.Status property. // The status of this image: -// - available: image can be used (provisionable) -// - deleting: image is being deleted, and can no longer be used to provision new +// - available: image can be used to create resources +// - deleting: image is being deleted, and can no longer be used to create +// resources +// - deprecated: image is slated to be deleted, but can still be used to create // resources -// - deprecated: image is administratively slated to become `obsolete` -// - failed: image is corrupt or did not pass validation -// - obsolete: image administratively set to not be used for new resources -// - pending: image is being imported and is not yet `available` +// - failed: image was not created successfully, and cannot be used to create +// resources +// - obsolete: image is slated to be deleted, and can no longer be used to create +// resources +// - pending: image is being imported, and cannot yet be used to create resources // - unusable: image cannot be used (see `status_reasons[]` for possible remediation) // // The enumerated values for this property may @@ -59824,6 +61011,11 @@ const ( // UnmarshalImage unmarshals an instance of Image from the specified map of raw messages. func UnmarshalImage(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Image) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalImageAllowedUse) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "catalog_offering", &obj.CatalogOffering, UnmarshalImageCatalogOffering) if err != nil { err = core.SDKErrorf(err, "", "catalog_offering-error", common.GetComponentInfo()) @@ -59889,9 +61081,9 @@ func UnmarshalImage(m map[string]json.RawMessage, result interface{}) (err error err = core.SDKErrorf(err, "", "operating_system-error", common.GetComponentInfo()) return } - err = core.UnmarshalPrimitive(m, "owner_type", &obj.OwnerType) + err = core.UnmarshalModel(m, "remote", &obj.Remote, UnmarshalImageRemote) if err != nil { - err = core.SDKErrorf(err, "", "owner_type-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "remote-error", common.GetComponentInfo()) return } err = core.UnmarshalModel(m, "resource_group", &obj.ResourceGroup, UnmarshalResourceGroupReference) @@ -59933,6 +61125,241 @@ func UnmarshalImage(m map[string]json.RawMessage, result interface{}) (err error return } +// ImageAllowedUse : ImageAllowedUse struct +type ImageAllowedUse struct { + // The API version with which to evaluate the expressions. + ApiVersion *string `json:"api_version" validate:"required"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using this image. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `BareMetalServer` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server" validate:"required"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this image. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance" validate:"required"` +} + +// UnmarshalImageAllowedUse unmarshals an instance of ImageAllowedUse from the specified map of raw messages. +func UnmarshalImageAllowedUse(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ImageAllowedUse) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ImageAllowedUsePatch : ImageAllowedUsePatch struct +type ImageAllowedUsePatch struct { + // The API version with which to evaluate the expressions. + // + // If specified, the value must be between `2019-01-01` and today's date (in UTC). + ApiVersion *string `json:"api_version,omitempty"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using this image. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server,omitempty"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this image. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance,omitempty"` +} + +// UnmarshalImageAllowedUsePatch unmarshals an instance of ImageAllowedUsePatch from the specified map of raw messages. +func UnmarshalImageAllowedUsePatch(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ImageAllowedUsePatch) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// asPatch returns a generic map representation of the ImageAllowedUsePatch +func (imageAllowedUsePatch *ImageAllowedUsePatch) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(imageAllowedUsePatch.ApiVersion) { + _patch["api_version"] = imageAllowedUsePatch.ApiVersion + } + if !core.IsNil(imageAllowedUsePatch.BareMetalServer) { + _patch["bare_metal_server"] = imageAllowedUsePatch.BareMetalServer + } + if !core.IsNil(imageAllowedUsePatch.Instance) { + _patch["instance"] = imageAllowedUsePatch.Instance + } + + return +} + +// ImageAllowedUsePrototype : ImageAllowedUsePrototype struct +type ImageAllowedUsePrototype struct { + // The API version with which to evaluate the expressions. + // + // If specified, the value must be between `2019-01-01` and today's date (in UTC). If unspecified, the `version` query + // parameter value will be used. + ApiVersion *string `json:"api_version,omitempty"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using this image. + // + // If unspecified, the expression will be set to `true`. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server,omitempty"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this image. + // + // If unspecified, the expression will be set to `true`. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance,omitempty"` +} + +// UnmarshalImageAllowedUsePrototype unmarshals an instance of ImageAllowedUsePrototype from the specified map of raw messages. +func UnmarshalImageAllowedUsePrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ImageAllowedUsePrototype) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ImageBareMetalServerProfileCollection : ImageBareMetalServerProfileCollection struct +type ImageBareMetalServerProfileCollection struct { + // A page of bare metal server profiles compatible with the image. + BareMetalServerProfiles []BareMetalServerProfileReference `json:"bare_metal_server_profiles" validate:"required"` + + // A link to the first page of resources. + First *PageLink `json:"first" validate:"required"` + + // The maximum number of resources that can be returned by the request. + Limit *int64 `json:"limit" validate:"required"` + + // A link to the next page of resources. This property is present for all pages + // except the last page. + Next *PageLink `json:"next,omitempty"` + + // The total number of resources across all pages. + TotalCount *int64 `json:"total_count" validate:"required"` +} + +// UnmarshalImageBareMetalServerProfileCollection unmarshals an instance of ImageBareMetalServerProfileCollection from the specified map of raw messages. +func UnmarshalImageBareMetalServerProfileCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ImageBareMetalServerProfileCollection) + err = core.UnmarshalModel(m, "bare_metal_server_profiles", &obj.BareMetalServerProfiles, UnmarshalBareMetalServerProfileReference) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server_profiles-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "first", &obj.First, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "first-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "limit", &obj.Limit) + if err != nil { + err = core.SDKErrorf(err, "", "limit-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "next", &obj.Next, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "next-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) + if err != nil { + err = core.SDKErrorf(err, "", "total_count-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// Retrieve the value to be passed to a request to access the next page of results +func (resp *ImageBareMetalServerProfileCollection) GetNextStart() (*string, error) { + if core.IsNil(resp.Next) { + return nil, nil + } + start, err := core.GetQueryParam(resp.Next.Href, "start") + if err != nil { + err = core.SDKErrorf(err, "", "read-query-param-error", common.GetComponentInfo()) + return nil, err + } else if start == nil { + return nil, nil + } + return start, nil +} + // ImageCatalogOffering : ImageCatalogOffering struct type ImageCatalogOffering struct { // Indicates whether this image is managed as part of a @@ -60252,7 +61679,7 @@ type ImageExportJobStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -60308,13 +61735,13 @@ func UnmarshalImageExportJobUnpaginatedCollection(m map[string]json.RawMessage, // ImageFile : ImageFile struct type ImageFile struct { - // Checksums for this image file. + // The checksums for the imported image file. // // This property may be absent if the associated image has a `status` of `pending` or // `failed`. Checksums *ImageFileChecksums `json:"checksums,omitempty"` - // The size of the stored image file rounded up to the next gigabyte. + // The size of the imported image file, rounded up to the next gigabyte. // // This property may be absent if the associated image has a `status` of `pending` or // `failed`. @@ -60435,8 +61862,78 @@ func UnmarshalImageIdentity(m map[string]json.RawMessage, result interface{}) (e return } +// ImageInstanceProfileCollection : ImageInstanceProfileCollection struct +type ImageInstanceProfileCollection struct { + // A link to the first page of resources. + First *PageLink `json:"first" validate:"required"` + + // A page of instance profiles compatible with the image. + InstanceProfiles []InstanceProfileReference `json:"instance_profiles" validate:"required"` + + // The maximum number of resources that can be returned by the request. + Limit *int64 `json:"limit" validate:"required"` + + // A link to the next page of resources. This property is present for all pages + // except the last page. + Next *PageLink `json:"next,omitempty"` + + // The total number of resources across all pages. + TotalCount *int64 `json:"total_count" validate:"required"` +} + +// UnmarshalImageInstanceProfileCollection unmarshals an instance of ImageInstanceProfileCollection from the specified map of raw messages. +func UnmarshalImageInstanceProfileCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ImageInstanceProfileCollection) + err = core.UnmarshalModel(m, "first", &obj.First, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "first-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "instance_profiles", &obj.InstanceProfiles, UnmarshalInstanceProfileReference) + if err != nil { + err = core.SDKErrorf(err, "", "instance_profiles-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "limit", &obj.Limit) + if err != nil { + err = core.SDKErrorf(err, "", "limit-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "next", &obj.Next, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "next-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) + if err != nil { + err = core.SDKErrorf(err, "", "total_count-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// Retrieve the value to be passed to a request to access the next page of results +func (resp *ImageInstanceProfileCollection) GetNextStart() (*string, error) { + if core.IsNil(resp.Next) { + return nil, nil + } + start, err := core.GetQueryParam(resp.Next.Href, "start") + if err != nil { + err = core.SDKErrorf(err, "", "read-query-param-error", common.GetComponentInfo()) + return nil, err + } else if start == nil { + return nil, nil + } + return start, nil +} + // ImagePatch : ImagePatch struct type ImagePatch struct { + // The usage constraints to be matched against the requested instance or bare metal server + // properties to determine compatibility. + AllowedUse *ImageAllowedUsePatch `json:"allowed_use,omitempty"` + // The deprecation date and time to set for this image. // // This cannot be set if the image has a `status` of `failed` or `deleting`, or if @@ -60478,6 +61975,11 @@ type ImagePatch struct { // UnmarshalImagePatch unmarshals an instance of ImagePatch from the specified map of raw messages. func UnmarshalImagePatch(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ImagePatch) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalImageAllowedUsePatch) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "deprecation_at", &obj.DeprecationAt) if err != nil { err = core.SDKErrorf(err, "", "deprecation_at-error", common.GetComponentInfo()) @@ -60500,6 +62002,9 @@ func UnmarshalImagePatch(m map[string]json.RawMessage, result interface{}) (err // AsPatch returns a generic map representation of the ImagePatch func (imagePatch *ImagePatch) AsPatch() (_patch map[string]interface{}, err error) { _patch = map[string]interface{}{} + if !core.IsNil(imagePatch.AllowedUse) { + _patch["allowed_use"] = imagePatch.AllowedUse.asPatch() + } if !core.IsNil(imagePatch.DeprecationAt) { _patch["deprecation_at"] = imagePatch.DeprecationAt } @@ -60518,6 +62023,10 @@ func (imagePatch *ImagePatch) AsPatch() (_patch map[string]interface{}, err erro // - ImagePrototypeImageByFile // - ImagePrototypeImageBySourceVolume type ImagePrototype struct { + // The usage constraints to match against the requested instance or bare metal server + // properties to determine compatibility. + AllowedUse *ImageAllowedUsePrototype `json:"allowed_use,omitempty"` + // The deprecation date and time to set for this image. // // The date and time must not be in the past, and must be earlier than `obsolescence_at` @@ -60595,6 +62104,11 @@ type ImagePrototypeIntf interface { // UnmarshalImagePrototype unmarshals an instance of ImagePrototype from the specified map of raw messages. func UnmarshalImagePrototype(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ImagePrototype) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalImageAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "deprecation_at", &obj.DeprecationAt) if err != nil { err = core.SDKErrorf(err, "", "deprecation_at-error", common.GetComponentInfo()) @@ -60718,6 +62232,26 @@ func UnmarshalImageReference(m map[string]json.RawMessage, result interface{}) ( return } +// ImageRemote : If present, this property indicates that the resource associated with this reference is remote and therefore may not +// be directly retrievable. +type ImageRemote struct { + // If present, this property indicates that the referenced resource is remote to this + // account, and identifies the owning account. + Account *AccountReference `json:"account,omitempty"` +} + +// UnmarshalImageRemote unmarshals an instance of ImageRemote from the specified map of raw messages. +func UnmarshalImageRemote(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ImageRemote) + err = core.UnmarshalModel(m, "account", &obj.Account, UnmarshalAccountReference) + if err != nil { + err = core.SDKErrorf(err, "", "account-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // ImageRemoteContextImageReference : If present, this property indicates that the resource associated with this reference is remote and therefore may not // be directly retrievable. type ImageRemoteContextImageReference struct { @@ -60769,7 +62303,7 @@ type ImageStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -60830,7 +62364,7 @@ type Instance struct { // interfaces and storage volumes of the virtual server instance. Bandwidth *int64 `json:"bandwidth" validate:"required"` - // Boot volume attachment. + // The boot volume attachment for this virtual server instance. BootVolumeAttachment *VolumeAttachmentReferenceInstanceContext `json:"boot_volume_attachment" validate:"required"` // If present, this virtual server instance was provisioned from a @@ -61360,11 +62894,13 @@ func UnmarshalInstanceAction(m map[string]json.RawMessage, result interface{}) ( return } -// InstanceAvailabilityPolicy : InstanceAvailabilityPolicy struct +// InstanceAvailabilityPolicy : The availability policy for this virtual server instance. type InstanceAvailabilityPolicy struct { // The action to perform if the compute host experiences a failure: - // - `restart`: Automatically restart the virtual server instance after host failure - // - `stop`: Leave the virtual server instance stopped after host failure + // - `restart`: Restart the virtual server instance + // - `stop`: Leave the virtual server instance stopped + // + // See [handling host failures](https://cloud.ibm.com/docs/vpc?topic=vpc-host-failure-recovery-policies) for details. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -61373,8 +62909,10 @@ type InstanceAvailabilityPolicy struct { // Constants associated with the InstanceAvailabilityPolicy.HostFailure property. // The action to perform if the compute host experiences a failure: -// - `restart`: Automatically restart the virtual server instance after host failure -// - `stop`: Leave the virtual server instance stopped after host failure +// - `restart`: Restart the virtual server instance +// - `stop`: Leave the virtual server instance stopped +// +// See [handling host failures](https://cloud.ibm.com/docs/vpc?topic=vpc-host-failure-recovery-policies) for details. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -61397,16 +62935,16 @@ func UnmarshalInstanceAvailabilityPolicy(m map[string]json.RawMessage, result in // InstanceAvailabilityPolicyPatch : InstanceAvailabilityPolicyPatch struct type InstanceAvailabilityPolicyPatch struct { - // The action to perform if the compute host experiences a failure. - // - `restart`: Automatically restart the virtual server instance after host failure - // - `stop`: Leave the virtual server instance stopped after host failure. + // The action to perform if the compute host experiences a failure: + // - `restart`: Restart the virtual server instance + // - `stop`: Leave the virtual server instance stopped. HostFailure *string `json:"host_failure,omitempty"` } // Constants associated with the InstanceAvailabilityPolicyPatch.HostFailure property. -// The action to perform if the compute host experiences a failure. -// - `restart`: Automatically restart the virtual server instance after host failure -// - `stop`: Leave the virtual server instance stopped after host failure. +// The action to perform if the compute host experiences a failure: +// - `restart`: Restart the virtual server instance +// - `stop`: Leave the virtual server instance stopped. const ( InstanceAvailabilityPolicyPatchHostFailureRestartConst = "restart" InstanceAvailabilityPolicyPatchHostFailureStopConst = "stop" @@ -61434,18 +62972,22 @@ func (instanceAvailabilityPolicyPatch *InstanceAvailabilityPolicyPatch) asPatch( return } -// InstanceAvailabilityPolicyPrototype : InstanceAvailabilityPolicyPrototype struct +// InstanceAvailabilityPolicyPrototype : The availability policy to use for this virtual server instance. type InstanceAvailabilityPolicyPrototype struct { - // The action to perform if the compute host experiences a failure. - // - `restart`: Automatically restart the virtual server instance after host failure - // - `stop`: Leave the virtual server instance stopped after host failure. + // The action to perform if the compute host experiences a failure: + // - `restart`: Restart the virtual server instance + // - `stop`: Leave the virtual server instance stopped + // + // See [handling host failures](https://cloud.ibm.com/docs/vpc?topic=vpc-host-failure-recovery-policies) for details. HostFailure *string `json:"host_failure,omitempty"` } // Constants associated with the InstanceAvailabilityPolicyPrototype.HostFailure property. -// The action to perform if the compute host experiences a failure. -// - `restart`: Automatically restart the virtual server instance after host failure -// - `stop`: Leave the virtual server instance stopped after host failure. +// The action to perform if the compute host experiences a failure: +// - `restart`: Restart the virtual server instance +// - `stop`: Leave the virtual server instance stopped +// +// See [handling host failures](https://cloud.ibm.com/docs/vpc?topic=vpc-host-failure-recovery-policies) for details. const ( InstanceAvailabilityPolicyPrototypeHostFailureRestartConst = "restart" InstanceAvailabilityPolicyPrototypeHostFailureStopConst = "stop" @@ -61816,7 +63358,7 @@ type InstanceClusterNetworkAttachmentLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -61885,8 +63427,8 @@ func (instanceClusterNetworkAttachmentPatch *InstanceClusterNetworkAttachmentPat } // InstanceClusterNetworkAttachmentPrototypeClusterNetworkInterface : A cluster network interface for the instance cluster network attachment. This can be specified using an existing -// cluster network interface that does not already have a `target`, or a prototype object for a new cluster network -// interface. +// cluster network interface that does not already have a +// `target`, or a prototype object for a new cluster network interface. // // This instance must reside in the same VPC as the specified cluster network interface. The cluster network interface // must reside in the same cluster network as the @@ -61975,8 +63517,8 @@ func UnmarshalInstanceClusterNetworkAttachmentPrototypeClusterNetworkInterface(m // InstanceClusterNetworkAttachmentPrototypeInstanceContext : InstanceClusterNetworkAttachmentPrototypeInstanceContext struct type InstanceClusterNetworkAttachmentPrototypeInstanceContext struct { // A cluster network interface for the instance cluster network attachment. This can be - // specified using an existing cluster network interface that does not already have a `target`, - // or a prototype object for a new cluster network interface. + // specified using an existing cluster network interface that does not already have a + // `target`, or a prototype object for a new cluster network interface. // // This instance must reside in the same VPC as the specified cluster network interface. The // cluster network interface must reside in the same cluster network as the @@ -62451,6 +63993,7 @@ type InstanceGpu struct { // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. const ( + InstanceGpuManufacturerAmdConst = "amd" InstanceGpuManufacturerIntelConst = "intel" InstanceGpuManufacturerNvidiaConst = "nvidia" ) @@ -62747,7 +64290,7 @@ type InstanceGroupLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -64466,10 +66009,9 @@ type InstanceGroupPatch struct { // This property must be set if and only if `load_balancer_pool` has been set. ApplicationPort *int64 `json:"application_port,omitempty"` - // Instance template to use when creating new instances. + // The instance template to use when creating new instances. // - // Instance groups are not compatible with instance templates that specify `true` for - // `default_trusted_profile.auto_link`. + // The specified template must not have `default_trusted_profile.auto_link` set to `true`. InstanceTemplate InstanceTemplateIdentityIntf `json:"instance_template,omitempty"` // The load balancer associated with `load_balancer_pool`. @@ -64637,7 +66179,7 @@ type InstanceHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -64788,7 +66330,7 @@ type InstanceLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -65237,9 +66779,9 @@ type InstanceNetworkAttachmentPrototypeVirtualNetworkInterface struct { // `bare_metal_server_network_attachment`. EnableInfrastructureNat *bool `json:"enable_infrastructure_nat,omitempty"` - // Additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP identity, or - // a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be in the - // primary IP's subnet. + // The additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP + // identity, or a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be + // in the primary IP's subnet. // // If reserved IP identities are provided, the specified reserved IPs must be unbound. // @@ -65481,7 +67023,6 @@ func UnmarshalInstanceNetworkAttachmentReference(m map[string]json.RawMessage, r // InstancePatch : InstancePatch struct type InstancePatch struct { - // The availability policy for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPatch `json:"availability_policy,omitempty"` // The confidential compute mode to use for this virtual server instance. @@ -65503,8 +67044,10 @@ type InstancePatch struct { // region. Changing the name will not affect the system hostname. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. For the placement restrictions to be changed, the - // instance `status` must be `stopping` or `stopped`. + // The placement restrictions to use for the virtual server instance. For the + // placement restrictions to be changed, the instance `status` must be `stopping` or + // `stopped`. + // // If set, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPatchIntf `json:"placement_target,omitempty"` @@ -65689,7 +67232,7 @@ func (instancePatchProfile *InstancePatchProfile) asPatch() (_patch map[string]i return } -// InstancePlacementTarget : InstancePlacementTarget struct +// InstancePlacementTarget : The placement restrictions for the virtual server instance. // Models which "extend" this model: // - InstancePlacementTargetDedicatedHostGroupReference // - InstancePlacementTargetDedicatedHostReference @@ -65766,7 +67309,11 @@ func UnmarshalInstancePlacementTarget(m map[string]json.RawMessage, result inter return } -// InstancePlacementTargetPatch : InstancePlacementTargetPatch struct +// InstancePlacementTargetPatch : The placement restrictions to use for the virtual server instance. For the placement restrictions to be changed, the +// instance `status` must be `stopping` or +// `stopped`. +// +// If set, `reservation_affinity.policy` must be `disabled`. // Models which "extend" this model: // - InstancePlacementTargetPatchDedicatedHostIdentity // - InstancePlacementTargetPatchDedicatedHostGroupIdentity @@ -65828,7 +67375,9 @@ func (instancePlacementTargetPatch *InstancePlacementTargetPatch) asPatch() (_pa return } -// InstancePlacementTargetPrototype : InstancePlacementTargetPrototype struct +// InstancePlacementTargetPrototype : The placement restrictions to use for the virtual server instance. +// +// If specified, `reservation_affinity.policy` must be `disabled`. // Models which "extend" this model: // - InstancePlacementTargetPrototypeDedicatedHostIdentity // - InstancePlacementTargetPrototypeDedicatedHostGroupIdentity @@ -65943,7 +67492,7 @@ type InstanceProfile struct { VcpuCount InstanceProfileVcpuIntf `json:"vcpu_count" validate:"required"` - VcpuManufacturer *InstanceProfileVcpuManufacturer `json:"vcpu_manufacturer" validate:"required"` + VcpuManufacturer InstanceProfileVcpuManufacturerIntf `json:"vcpu_manufacturer" validate:"required"` } // Constants associated with the InstanceProfile.ResourceType property. @@ -66653,6 +68202,7 @@ const ( // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. const ( + InstanceProfileGpuManufacturerValuesAmdConst = "amd" InstanceProfileGpuManufacturerValuesIntelConst = "intel" InstanceProfileGpuManufacturerValuesNvidiaConst = "nvidia" ) @@ -67446,12 +68996,15 @@ func UnmarshalInstanceProfileVcpuArchitecture(m map[string]json.RawMessage, resu } // InstanceProfileVcpuManufacturer : InstanceProfileVcpuManufacturer struct +// Models which "extend" this model: +// - InstanceProfileVcpuManufacturerFixed +// - InstanceProfileVcpuManufacturerDependent type InstanceProfileVcpuManufacturer struct { // The type for this profile field. - Type *string `json:"type" validate:"required"` + Type *string `json:"type,omitempty"` // The VCPU manufacturer for an instance with this profile. - Value *string `json:"value" validate:"required"` + Value *string `json:"value,omitempty"` } // Constants associated with the InstanceProfileVcpuManufacturer.Type property. @@ -67468,6 +69021,14 @@ const ( InstanceProfileVcpuManufacturerValueIntelConst = "intel" ) +func (*InstanceProfileVcpuManufacturer) isaInstanceProfileVcpuManufacturer() bool { + return true +} + +type InstanceProfileVcpuManufacturerIntf interface { + isaInstanceProfileVcpuManufacturer() bool +} + // UnmarshalInstanceProfileVcpuManufacturer unmarshals an instance of InstanceProfileVcpuManufacturer from the specified map of raw messages. func UnmarshalInstanceProfileVcpuManufacturer(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(InstanceProfileVcpuManufacturer) @@ -67639,6 +69200,8 @@ type InstancePrototype struct { // in the future. Profile InstanceProfileIdentityIntf `json:"profile,omitempty"` + // The reservation affinity settings for this virtual server instance. If specified, + // `vcpu.tenancy` must be `dedicated`, and `vcpu.percentage` must be `100`. ReservationAffinity *InstanceReservationAffinityPrototype `json:"reservation_affinity,omitempty"` // The resource group to use. If unspecified, the account's [default resource @@ -67650,8 +69213,8 @@ type InstancePrototype struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -68016,7 +69579,8 @@ func (instanceReservationAffinityPatch *InstanceReservationAffinityPatch) asPatc return } -// InstanceReservationAffinityPrototype : InstanceReservationAffinityPrototype struct +// InstanceReservationAffinityPrototype : The reservation affinity settings for this virtual server instance. If specified, +// `vcpu.tenancy` must be `dedicated`, and `vcpu.percentage` must be `100`. type InstanceReservationAffinityPrototype struct { // The reservation affinity policy to use for this virtual server instance: // - `disabled`: Reservations will not be used @@ -68086,7 +69650,7 @@ type InstanceStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -68208,6 +69772,8 @@ type InstanceTemplate struct { // in the future. Profile InstanceProfileIdentityIntf `json:"profile,omitempty"` + // The reservation affinity settings for this virtual server instance. If specified, + // `vcpu.tenancy` must be `dedicated`, and `vcpu.percentage` must be `100`. ReservationAffinity *InstanceReservationAffinityPrototype `json:"reservation_affinity,omitempty"` // The resource group for this instance template. @@ -68218,8 +69784,8 @@ type InstanceTemplate struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -68635,6 +70201,8 @@ type InstanceTemplatePrototype struct { // in the future. Profile InstanceProfileIdentityIntf `json:"profile,omitempty"` + // The reservation affinity settings for this virtual server instance. If specified, + // `vcpu.tenancy` must be `dedicated`, and `vcpu.percentage` must be `100`. ReservationAffinity *InstanceReservationAffinityPrototype `json:"reservation_affinity,omitempty"` // The resource group to use. If unspecified, the account's [default resource @@ -68646,8 +70214,8 @@ type InstanceTemplatePrototype struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -68965,8 +70533,11 @@ type Key struct { // The CRN for this key. CRN *string `json:"crn" validate:"required"` - // The fingerprint for this key. The value is returned base64-encoded and prefixed with the hash algorithm (always + // The fingerprint for this key. The value is returned base64-encoded and prefixed with the hash algorithm (such as // `SHA256`). + // + // The length of this property may + // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. Fingerprint *string `json:"fingerprint" validate:"required"` // The URL for this key. @@ -69144,8 +70715,11 @@ type KeyIdentity struct { // The URL for this key. Href *string `json:"href,omitempty"` - // The fingerprint for this key. The value is returned base64-encoded and prefixed with the hash algorithm (always + // The fingerprint for this key. The value is returned base64-encoded and prefixed with the hash algorithm (such as // `SHA256`). + // + // The length of this property may + // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. Fingerprint *string `json:"fingerprint,omitempty"` } @@ -69221,8 +70795,11 @@ type KeyReference struct { // some supplementary information. Deleted *Deleted `json:"deleted,omitempty"` - // The fingerprint for this key. The value is returned base64-encoded and prefixed with the hash algorithm (always + // The fingerprint for this key. The value is returned base64-encoded and prefixed with the hash algorithm (such as // `SHA256`). + // + // The length of this property may + // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. Fingerprint *string `json:"fingerprint" validate:"required"` // The URL for this key. @@ -70901,6 +72478,52 @@ func (options *ListIkePolicyConnectionsOptions) SetHeaders(param map[string]stri return options } +// ListImageBareMetalServerProfilesOptions : The ListImageBareMetalServerProfiles options. +type ListImageBareMetalServerProfilesOptions struct { + // The image identifier. + ID *string `json:"id" validate:"required,ne="` + + // A server-provided token determining what resource to start the page on. + Start *string `json:"start,omitempty"` + + // The number of resources to return on a page. + Limit *int64 `json:"limit,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewListImageBareMetalServerProfilesOptions : Instantiate ListImageBareMetalServerProfilesOptions +func (*VpcV1) NewListImageBareMetalServerProfilesOptions(id string) *ListImageBareMetalServerProfilesOptions { + return &ListImageBareMetalServerProfilesOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *ListImageBareMetalServerProfilesOptions) SetID(id string) *ListImageBareMetalServerProfilesOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetStart : Allow user to set Start +func (_options *ListImageBareMetalServerProfilesOptions) SetStart(start string) *ListImageBareMetalServerProfilesOptions { + _options.Start = core.StringPtr(start) + return _options +} + +// SetLimit : Allow user to set Limit +func (_options *ListImageBareMetalServerProfilesOptions) SetLimit(limit int64) *ListImageBareMetalServerProfilesOptions { + _options.Limit = core.Int64Ptr(limit) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *ListImageBareMetalServerProfilesOptions) SetHeaders(param map[string]string) *ListImageBareMetalServerProfilesOptions { + options.Headers = param + return options +} + // ListImageExportJobsOptions : The ListImageExportJobs options. type ListImageExportJobsOptions struct { // The image identifier. @@ -70938,6 +72561,52 @@ func (options *ListImageExportJobsOptions) SetHeaders(param map[string]string) * return options } +// ListImageInstanceProfilesOptions : The ListImageInstanceProfiles options. +type ListImageInstanceProfilesOptions struct { + // The image identifier. + ID *string `json:"id" validate:"required,ne="` + + // A server-provided token determining what resource to start the page on. + Start *string `json:"start,omitempty"` + + // The number of resources to return on a page. + Limit *int64 `json:"limit,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewListImageInstanceProfilesOptions : Instantiate ListImageInstanceProfilesOptions +func (*VpcV1) NewListImageInstanceProfilesOptions(id string) *ListImageInstanceProfilesOptions { + return &ListImageInstanceProfilesOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *ListImageInstanceProfilesOptions) SetID(id string) *ListImageInstanceProfilesOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetStart : Allow user to set Start +func (_options *ListImageInstanceProfilesOptions) SetStart(start string) *ListImageInstanceProfilesOptions { + _options.Start = core.StringPtr(start) + return _options +} + +// SetLimit : Allow user to set Limit +func (_options *ListImageInstanceProfilesOptions) SetLimit(limit int64) *ListImageInstanceProfilesOptions { + _options.Limit = core.Int64Ptr(limit) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *ListImageInstanceProfilesOptions) SetHeaders(param map[string]string) *ListImageInstanceProfilesOptions { + options.Headers = param + return options +} + // ListImagesOptions : The ListImages options. type ListImagesOptions struct { // A server-provided token determining what resource to start the page on. @@ -70962,8 +72631,11 @@ type ListImagesOptions struct { // values. UserDataFormat []string `json:"user_data_format,omitempty"` - // Filters the collection to images with an `owner_type` property matching the specified value. - OwnerType *string `json:"owner_type,omitempty"` + // Filters the collection to images with a `remote.account.id` property matching the specified account identifier. + // + // This parameter also supports the values null and not:null which filter the collection to resources which have no + // remote account identifier or any remote account identifier, respectively. + RemoteAccountID *string `json:"remote.account.id,omitempty"` // Allows users to set headers on API requests. Headers map[string]string @@ -70994,13 +72666,6 @@ const ( ListImagesOptionsUserDataFormatIpxeConst = "ipxe" ) -// Constants associated with the ListImagesOptions.OwnerType property. -// Filters the collection to images with an `owner_type` property matching the specified value. -const ( - ListImagesOptionsOwnerTypeProviderConst = "provider" - ListImagesOptionsOwnerTypeUserConst = "user" -) - // NewListImagesOptions : Instantiate ListImagesOptions func (*VpcV1) NewListImagesOptions() *ListImagesOptions { return &ListImagesOptions{} @@ -71048,9 +72713,9 @@ func (_options *ListImagesOptions) SetUserDataFormat(userDataFormat []string) *L return _options } -// SetOwnerType : Allow user to set OwnerType -func (_options *ListImagesOptions) SetOwnerType(ownerType string) *ListImagesOptions { - _options.OwnerType = core.StringPtr(ownerType) +// SetRemoteAccountID : Allow user to set RemoteAccountID +func (_options *ListImagesOptions) SetRemoteAccountID(remoteAccountID string) *ListImagesOptions { + _options.RemoteAccountID = core.StringPtr(remoteAccountID) return _options } @@ -72587,6 +74252,50 @@ func (options *ListPrivatePathServiceGatewaysOptions) SetHeaders(param map[strin return options } +// ListPublicAddressRangesOptions : The ListPublicAddressRanges options. +type ListPublicAddressRangesOptions struct { + // A server-provided token determining what resource to start the page on. + Start *string `json:"start,omitempty"` + + // The number of resources to return on a page. + Limit *int64 `json:"limit,omitempty"` + + // Filters the collection to resources with a `resource_group.id` property matching the specified identifier. + ResourceGroupID *string `json:"resource_group.id,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewListPublicAddressRangesOptions : Instantiate ListPublicAddressRangesOptions +func (*VpcV1) NewListPublicAddressRangesOptions() *ListPublicAddressRangesOptions { + return &ListPublicAddressRangesOptions{} +} + +// SetStart : Allow user to set Start +func (_options *ListPublicAddressRangesOptions) SetStart(start string) *ListPublicAddressRangesOptions { + _options.Start = core.StringPtr(start) + return _options +} + +// SetLimit : Allow user to set Limit +func (_options *ListPublicAddressRangesOptions) SetLimit(limit int64) *ListPublicAddressRangesOptions { + _options.Limit = core.Int64Ptr(limit) + return _options +} + +// SetResourceGroupID : Allow user to set ResourceGroupID +func (_options *ListPublicAddressRangesOptions) SetResourceGroupID(resourceGroupID string) *ListPublicAddressRangesOptions { + _options.ResourceGroupID = core.StringPtr(resourceGroupID) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *ListPublicAddressRangesOptions) SetHeaders(param map[string]string) *ListPublicAddressRangesOptions { + options.Headers = param + return options +} + // ListPublicGatewaysOptions : The ListPublicGateways options. type ListPublicGatewaysOptions struct { // A server-provided token determining what resource to start the page on. @@ -73351,6 +75060,52 @@ func (options *ListSnapshotConsistencyGroupsOptions) SetHeaders(param map[string return options } +// ListSnapshotInstanceProfilesOptions : The ListSnapshotInstanceProfiles options. +type ListSnapshotInstanceProfilesOptions struct { + // The snapshot identifier. + ID *string `json:"id" validate:"required,ne="` + + // A server-provided token determining what resource to start the page on. + Start *string `json:"start,omitempty"` + + // The number of resources to return on a page. + Limit *int64 `json:"limit,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewListSnapshotInstanceProfilesOptions : Instantiate ListSnapshotInstanceProfilesOptions +func (*VpcV1) NewListSnapshotInstanceProfilesOptions(id string) *ListSnapshotInstanceProfilesOptions { + return &ListSnapshotInstanceProfilesOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *ListSnapshotInstanceProfilesOptions) SetID(id string) *ListSnapshotInstanceProfilesOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetStart : Allow user to set Start +func (_options *ListSnapshotInstanceProfilesOptions) SetStart(start string) *ListSnapshotInstanceProfilesOptions { + _options.Start = core.StringPtr(start) + return _options +} + +// SetLimit : Allow user to set Limit +func (_options *ListSnapshotInstanceProfilesOptions) SetLimit(limit int64) *ListSnapshotInstanceProfilesOptions { + _options.Limit = core.Int64Ptr(limit) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *ListSnapshotInstanceProfilesOptions) SetHeaders(param map[string]string) *ListSnapshotInstanceProfilesOptions { + options.Headers = param + return options +} + // ListSnapshotsOptions : The ListSnapshots options. type ListSnapshotsOptions struct { // A server-provided token determining what resource to start the page on. @@ -73907,6 +75662,52 @@ func (options *ListVirtualNetworkInterfacesOptions) SetHeaders(param map[string] return options } +// ListVolumeInstanceProfilesOptions : The ListVolumeInstanceProfiles options. +type ListVolumeInstanceProfilesOptions struct { + // The volume identifier. + ID *string `json:"id" validate:"required,ne="` + + // A server-provided token determining what resource to start the page on. + Start *string `json:"start,omitempty"` + + // The number of resources to return on a page. + Limit *int64 `json:"limit,omitempty"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewListVolumeInstanceProfilesOptions : Instantiate ListVolumeInstanceProfilesOptions +func (*VpcV1) NewListVolumeInstanceProfilesOptions(id string) *ListVolumeInstanceProfilesOptions { + return &ListVolumeInstanceProfilesOptions{ + ID: core.StringPtr(id), + } +} + +// SetID : Allow user to set ID +func (_options *ListVolumeInstanceProfilesOptions) SetID(id string) *ListVolumeInstanceProfilesOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetStart : Allow user to set Start +func (_options *ListVolumeInstanceProfilesOptions) SetStart(start string) *ListVolumeInstanceProfilesOptions { + _options.Start = core.StringPtr(start) + return _options +} + +// SetLimit : Allow user to set Limit +func (_options *ListVolumeInstanceProfilesOptions) SetLimit(limit int64) *ListVolumeInstanceProfilesOptions { + _options.Limit = core.Int64Ptr(limit) + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *ListVolumeInstanceProfilesOptions) SetHeaders(param map[string]string) *ListVolumeInstanceProfilesOptions { + options.Headers = param + return options +} + // ListVolumeProfilesOptions : The ListVolumeProfiles options. type ListVolumeProfilesOptions struct { // A server-provided token determining what resource to start the page on. @@ -74893,7 +76694,7 @@ type LoadBalancer struct { // The supported `failsafe_policy.action` values for this load balancer's pools. FailsafePolicyActions []string `json:"failsafe_policy_actions" validate:"required"` - // Fully qualified domain name assigned to this load balancer. + // The fully qualified domain name assigned to this load balancer. Hostname *string `json:"hostname" validate:"required"` // The URL for this load balancer. @@ -76161,7 +77962,7 @@ type LoadBalancerListenerPolicy struct { // listener. Name *string `json:"name" validate:"required"` - // Priority of the policy. The priority is unique across all policies for this load balancer listener. Lower value + // The priority of the policy. The priority is unique across all policies for this load balancer listener. Lower value // indicates higher priority. Priority *int64 `json:"priority" validate:"required"` @@ -76291,7 +78092,7 @@ type LoadBalancerListenerPolicyPatch struct { // The name for this policy. The name must not be used by another policy for the load balancer listener. Name *string `json:"name,omitempty"` - // Priority of the policy. The priority is unique across all policies for this load balancer listener. Lower value + // The priority of the policy. The priority is unique across all policies for this load balancer listener. Lower value // indicates higher priority. Priority *int64 `json:"priority,omitempty"` @@ -76361,7 +78162,7 @@ type LoadBalancerListenerPolicyPrototype struct { // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // Priority of the policy. The priority is unique across all policies for this load balancer listener. Lower value + // The priority of the policy. The priority is unique across all policies for this load balancer listener. Lower value // indicates higher priority. Priority *int64 `json:"priority" validate:"required"` @@ -78464,7 +80265,7 @@ type LoadBalancerPoolMember struct { // The date and time that this member was created. CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` - // Health of the server member in the pool. + // The health of the member. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -78493,14 +80294,14 @@ type LoadBalancerPoolMember struct { // The pool member target. Target LoadBalancerPoolMemberTargetIntf `json:"target" validate:"required"` - // The weight of the server member. + // The weight of the member. // // This property will be present if the pool algorithm is `weighted_round_robin`. Weight *int64 `json:"weight,omitempty"` } // Constants associated with the LoadBalancerPoolMember.Health property. -// Health of the server member in the pool. +// The health of the member. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -78612,7 +80413,7 @@ type LoadBalancerPoolMemberPatch struct { // be shared by a pool member of any other load balancer in the same VPC. Target LoadBalancerPoolMemberTargetPrototypeIntf `json:"target,omitempty"` - // The weight of the server member. + // The weight of the member. // // If specified, the pool algorithm must be `weighted_round_robin`. Weight *int64 `json:"weight,omitempty"` @@ -78680,7 +80481,7 @@ type LoadBalancerPoolMemberPrototype struct { // be shared by a pool member of any other load balancer in the same VPC. Target LoadBalancerPoolMemberTargetPrototypeIntf `json:"target" validate:"required"` - // The weight of the server member. + // The weight of the member. // // If specified, the pool algorithm must be `weighted_round_robin` and the load balancer must be in the `application` // family. @@ -80188,16 +81989,16 @@ func UnmarshalLoadBalancerReference(m map[string]json.RawMessage, result interfa // LoadBalancerStatistics : LoadBalancerStatistics struct type LoadBalancerStatistics struct { - // Number of active connections of this load balancer. + // The number of active connections for this load balancer. ActiveConnections *int64 `json:"active_connections" validate:"required"` - // Current connection rate (connections per second) of this load balancer. + // The current connection rate (connections per second) for this load balancer. ConnectionRate *float32 `json:"connection_rate" validate:"required"` - // Total number of data processed (bytes) of this load balancer within current calendar month. + // The total number of bytes processed for this load balancer for the current calendar month. DataProcessedThisMonth *int64 `json:"data_processed_this_month" validate:"required"` - // Current throughput (Mbps) of this load balancer. + // The current throughput (in Mbps) for this load balancer. Throughput *float32 `json:"throughput" validate:"required"` } @@ -80615,7 +82416,7 @@ type NetworkACLRule struct { // The name for this network ACL rule. The name is unique across all rules for the network ACL. Name *string `json:"name" validate:"required"` - // The name of the network protocol. + // The network protocol. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -80668,7 +82469,7 @@ const ( ) // Constants associated with the NetworkACLRule.Protocol property. -// The name of the network protocol. +// The network protocol. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -80920,7 +82721,7 @@ type NetworkACLRuleItem struct { // The name for this network ACL rule. The name is unique across all rules for the network ACL. Name *string `json:"name" validate:"required"` - // The name of the network protocol. + // The network protocol. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -80973,7 +82774,7 @@ const ( ) // Constants associated with the NetworkACLRuleItem.Protocol property. -// The name of the network protocol. +// The network protocol. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -81237,7 +83038,7 @@ type NetworkACLRulePrototype struct { // the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The source IP address or CIDR block to match. The CIDR block `0.0.0.0/0` matches all source addresses. @@ -81299,7 +83100,7 @@ const ( ) // Constants associated with the NetworkACLRulePrototype.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRulePrototypeProtocolAllConst = "all" NetworkACLRulePrototypeProtocolIcmpConst = "icmp" @@ -81317,42 +83118,78 @@ type NetworkACLRulePrototypeIntf interface { // UnmarshalNetworkACLRulePrototype unmarshals an instance of NetworkACLRulePrototype from the specified map of raw messages. func UnmarshalNetworkACLRulePrototype(m map[string]json.RawMessage, result interface{}) (err error) { - // Retrieve discriminator value to determine correct "subclass". - var discValue string - err = core.UnmarshalPrimitive(m, "protocol", &discValue) + obj := new(NetworkACLRulePrototype) + err = core.UnmarshalPrimitive(m, "action", &obj.Action) if err != nil { - errMsg := fmt.Sprintf("error unmarshalling discriminator property 'protocol': %s", err.Error()) - err = core.SDKErrorf(err, errMsg, "discriminator-unmarshal-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "action-error", common.GetComponentInfo()) return } - if discValue == "" { - err = core.SDKErrorf(err, "required discriminator property 'protocol' not found in JSON object", "missing-discriminator", common.GetComponentInfo()) + err = core.UnmarshalModel(m, "before", &obj.Before, UnmarshalNetworkACLRuleBeforePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "before-error", common.GetComponentInfo()) return } - if discValue == "all" { - err = core.UnmarshalModel(m, "", result, UnmarshalNetworkACLRulePrototypeNetworkACLRuleProtocolAllPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-NetworkACLRulePrototypeNetworkACLRuleProtocolAllPrototype-error", common.GetComponentInfo()) - } - } else if discValue == "icmp" { - err = core.UnmarshalModel(m, "", result, UnmarshalNetworkACLRulePrototypeNetworkACLRuleProtocolIcmpPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-NetworkACLRulePrototypeNetworkACLRuleProtocolIcmpPrototype-error", common.GetComponentInfo()) - } - } else if discValue == "tcp" { - err = core.UnmarshalModel(m, "", result, UnmarshalNetworkACLRulePrototypeNetworkACLRuleProtocolTcpudpPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-NetworkACLRulePrototypeNetworkACLRuleProtocolTcpudpPrototype-error", common.GetComponentInfo()) - } - } else if discValue == "udp" { - err = core.UnmarshalModel(m, "", result, UnmarshalNetworkACLRulePrototypeNetworkACLRuleProtocolTcpudpPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-NetworkACLRulePrototypeNetworkACLRuleProtocolTcpudpPrototype-error", common.GetComponentInfo()) - } - } else { - errMsg := fmt.Sprintf("unrecognized value for discriminator property 'protocol': %s", discValue) - err = core.SDKErrorf(err, errMsg, "invalid-discriminator", common.GetComponentInfo()) + err = core.UnmarshalPrimitive(m, "destination", &obj.Destination) + if err != nil { + err = core.SDKErrorf(err, "", "destination-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "direction", &obj.Direction) + if err != nil { + err = core.SDKErrorf(err, "", "direction-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "ip_version", &obj.IPVersion) + if err != nil { + err = core.SDKErrorf(err, "", "ip_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "protocol", &obj.Protocol) + if err != nil { + err = core.SDKErrorf(err, "", "protocol-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "source", &obj.Source) + if err != nil { + err = core.SDKErrorf(err, "", "source-error", common.GetComponentInfo()) + return } + err = core.UnmarshalPrimitive(m, "code", &obj.Code) + if err != nil { + err = core.SDKErrorf(err, "", "code-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "type", &obj.Type) + if err != nil { + err = core.SDKErrorf(err, "", "type-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "destination_port_max", &obj.DestinationPortMax) + if err != nil { + err = core.SDKErrorf(err, "", "destination_port_max-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "destination_port_min", &obj.DestinationPortMin) + if err != nil { + err = core.SDKErrorf(err, "", "destination_port_min-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "source_port_max", &obj.SourcePortMax) + if err != nil { + err = core.SDKErrorf(err, "", "source_port_max-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "source_port_min", &obj.SourcePortMin) + if err != nil { + err = core.SDKErrorf(err, "", "source_port_min-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } @@ -81378,7 +83215,7 @@ type NetworkACLRulePrototypeNetworkACLContext struct { // the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The source IP address or CIDR block to match. The CIDR block `0.0.0.0/0` matches all source addresses. @@ -81440,7 +83277,7 @@ const ( ) // Constants associated with the NetworkACLRulePrototypeNetworkACLContext.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRulePrototypeNetworkACLContextProtocolAllConst = "all" NetworkACLRulePrototypeNetworkACLContextProtocolIcmpConst = "icmp" @@ -81458,42 +83295,73 @@ type NetworkACLRulePrototypeNetworkACLContextIntf interface { // UnmarshalNetworkACLRulePrototypeNetworkACLContext unmarshals an instance of NetworkACLRulePrototypeNetworkACLContext from the specified map of raw messages. func UnmarshalNetworkACLRulePrototypeNetworkACLContext(m map[string]json.RawMessage, result interface{}) (err error) { - // Retrieve discriminator value to determine correct "subclass". - var discValue string - err = core.UnmarshalPrimitive(m, "protocol", &discValue) + obj := new(NetworkACLRulePrototypeNetworkACLContext) + err = core.UnmarshalPrimitive(m, "action", &obj.Action) if err != nil { - errMsg := fmt.Sprintf("error unmarshalling discriminator property 'protocol': %s", err.Error()) - err = core.SDKErrorf(err, errMsg, "discriminator-unmarshal-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "action-error", common.GetComponentInfo()) return } - if discValue == "" { - err = core.SDKErrorf(err, "required discriminator property 'protocol' not found in JSON object", "missing-discriminator", common.GetComponentInfo()) + err = core.UnmarshalPrimitive(m, "destination", &obj.Destination) + if err != nil { + err = core.SDKErrorf(err, "", "destination-error", common.GetComponentInfo()) return } - if discValue == "all" { - err = core.UnmarshalModel(m, "", result, UnmarshalNetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolAllPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolAllPrototype-error", common.GetComponentInfo()) - } - } else if discValue == "icmp" { - err = core.UnmarshalModel(m, "", result, UnmarshalNetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolIcmpPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolIcmpPrototype-error", common.GetComponentInfo()) - } - } else if discValue == "tcp" { - err = core.UnmarshalModel(m, "", result, UnmarshalNetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolTcpudpPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolTcpudpPrototype-error", common.GetComponentInfo()) - } - } else if discValue == "udp" { - err = core.UnmarshalModel(m, "", result, UnmarshalNetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolTcpudpPrototype) - if err != nil { - err = core.SDKErrorf(err, "", "unmarshal-NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolTcpudpPrototype-error", common.GetComponentInfo()) - } - } else { - errMsg := fmt.Sprintf("unrecognized value for discriminator property 'protocol': %s", discValue) - err = core.SDKErrorf(err, errMsg, "invalid-discriminator", common.GetComponentInfo()) + err = core.UnmarshalPrimitive(m, "direction", &obj.Direction) + if err != nil { + err = core.SDKErrorf(err, "", "direction-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "ip_version", &obj.IPVersion) + if err != nil { + err = core.SDKErrorf(err, "", "ip_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "protocol", &obj.Protocol) + if err != nil { + err = core.SDKErrorf(err, "", "protocol-error", common.GetComponentInfo()) + return } + err = core.UnmarshalPrimitive(m, "source", &obj.Source) + if err != nil { + err = core.SDKErrorf(err, "", "source-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "code", &obj.Code) + if err != nil { + err = core.SDKErrorf(err, "", "code-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "type", &obj.Type) + if err != nil { + err = core.SDKErrorf(err, "", "type-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "destination_port_max", &obj.DestinationPortMax) + if err != nil { + err = core.SDKErrorf(err, "", "destination_port_max-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "destination_port_min", &obj.DestinationPortMin) + if err != nil { + err = core.SDKErrorf(err, "", "destination_port_min-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "source_port_max", &obj.SourcePortMax) + if err != nil { + err = core.SDKErrorf(err, "", "source_port_max-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "source_port_min", &obj.SourcePortMin) + if err != nil { + err = core.SDKErrorf(err, "", "source_port_min-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } @@ -82129,13 +83997,13 @@ func (options *ObsoleteImageOptions) SetHeaders(param map[string]string) *Obsole // OperatingSystem : OperatingSystem struct type OperatingSystem struct { - // Users may create new images with this operating system. + // Indicates that users may create new images with this operating system. AllowUserImageCreation *bool `json:"allow_user_image_creation" validate:"required"` // The operating system architecture. Architecture *string `json:"architecture" validate:"required"` - // Images with this operating system can only be used on dedicated hosts or dedicated host groups. + // Indicates that images with this operating system can only be used on dedicated hosts and dedicated host groups. DedicatedHostOnly *bool `json:"dedicated_host_only" validate:"required"` // A unique, display-friendly name for the operating system. @@ -83288,6 +85156,8 @@ type PrivatePathServiceGatewayPatch struct { // the VPC. Name *string `json:"name,omitempty"` + // Indicates whether this private path service gateway has zonal affinity. + // // Updating the value of `zonal_affinity` changes how traffic for existing and future endpoint gateway bindings will be // routed: // - `true`: Traffic to the service from a zone the service resides in will remain in @@ -83380,60 +85250,74 @@ func UnmarshalPrivatePathServiceGatewayRemote(m map[string]json.RawMessage, resu return } -// PublicGateway : PublicGateway struct -type PublicGateway struct { - // The date and time that the public gateway was created. +// PublicAddressRange : PublicAddressRange struct +type PublicAddressRange struct { + // The public IPv4 range, expressed in CIDR format. + CIDR *string `json:"cidr" validate:"required"` + + // The date and time that the public address range was created. CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` - // The CRN for this public gateway. + // The CRN for this public address range. CRN *string `json:"crn" validate:"required"` - // The floating IP bound to this public gateway. - FloatingIP *PublicGatewayFloatingIP `json:"floating_ip" validate:"required"` - - // The URL for this public gateway. + // The URL for this public address range. Href *string `json:"href" validate:"required"` - // The unique identifier for this public gateway. + // The unique identifier for this public address range. ID *string `json:"id" validate:"required"` - // The name for this public gateway. The name is unique across all public gateways in the VPC. + // The number of IPv4 addresses in this public address range. + Ipv4AddressCount *int64 `json:"ipv4_address_count" validate:"required"` + + // The lifecycle state of the public address range. + LifecycleState *string `json:"lifecycle_state" validate:"required"` + + // The name for this public address range. The name is unique across all public address ranges in the region. Name *string `json:"name" validate:"required"` - // The resource group for this public gateway. + // The resource group for this public address range. ResourceGroup *ResourceGroupReference `json:"resource_group" validate:"required"` // The resource type. ResourceType *string `json:"resource_type" validate:"required"` - // The status of this public gateway. - Status *string `json:"status" validate:"required"` - - // The VPC this public gateway resides in. - VPC *VPCReference `json:"vpc" validate:"required"` - - // The zone this public gateway resides in. - Zone *ZoneReference `json:"zone" validate:"required"` + // The target this public address range is bound to. + // + // If absent, this pubic address range is not bound to a target. + // + // The target resources supported by this property is expected to + // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. Future + // targets may omit the `vpc` property. + Target *PublicAddressRangeTarget `json:"target,omitempty"` } -// Constants associated with the PublicGateway.ResourceType property. -// The resource type. +// Constants associated with the PublicAddressRange.LifecycleState property. +// The lifecycle state of the public address range. const ( - PublicGatewayResourceTypePublicGatewayConst = "public_gateway" + PublicAddressRangeLifecycleStateDeletingConst = "deleting" + PublicAddressRangeLifecycleStateFailedConst = "failed" + PublicAddressRangeLifecycleStatePendingConst = "pending" + PublicAddressRangeLifecycleStateStableConst = "stable" + PublicAddressRangeLifecycleStateSuspendedConst = "suspended" + PublicAddressRangeLifecycleStateUpdatingConst = "updating" + PublicAddressRangeLifecycleStateWaitingConst = "waiting" ) -// Constants associated with the PublicGateway.Status property. -// The status of this public gateway. +// Constants associated with the PublicAddressRange.ResourceType property. +// The resource type. const ( - PublicGatewayStatusAvailableConst = "available" - PublicGatewayStatusDeletingConst = "deleting" - PublicGatewayStatusFailedConst = "failed" - PublicGatewayStatusPendingConst = "pending" + PublicAddressRangeResourceTypePublicAddressRangeConst = "public_address_range" ) -// UnmarshalPublicGateway unmarshals an instance of PublicGateway from the specified map of raw messages. -func UnmarshalPublicGateway(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(PublicGateway) +// UnmarshalPublicAddressRange unmarshals an instance of PublicAddressRange from the specified map of raw messages. +func UnmarshalPublicAddressRange(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicAddressRange) + err = core.UnmarshalPrimitive(m, "cidr", &obj.CIDR) + if err != nil { + err = core.SDKErrorf(err, "", "cidr-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) if err != nil { err = core.SDKErrorf(err, "", "created_at-error", common.GetComponentInfo()) @@ -83444,11 +85328,6 @@ func UnmarshalPublicGateway(m map[string]json.RawMessage, result interface{}) (e err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "floating_ip", &obj.FloatingIP, UnmarshalPublicGatewayFloatingIP) - if err != nil { - err = core.SDKErrorf(err, "", "floating_ip-error", common.GetComponentInfo()) - return - } err = core.UnmarshalPrimitive(m, "href", &obj.Href) if err != nil { err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) @@ -83459,42 +85338,42 @@ func UnmarshalPublicGateway(m map[string]json.RawMessage, result interface{}) (e err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) return } - err = core.UnmarshalPrimitive(m, "name", &obj.Name) + err = core.UnmarshalPrimitive(m, "ipv4_address_count", &obj.Ipv4AddressCount) if err != nil { - err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "ipv4_address_count-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "resource_group", &obj.ResourceGroup, UnmarshalResourceGroupReference) + err = core.UnmarshalPrimitive(m, "lifecycle_state", &obj.LifecycleState) if err != nil { - err = core.SDKErrorf(err, "", "resource_group-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "lifecycle_state-error", common.GetComponentInfo()) return } - err = core.UnmarshalPrimitive(m, "resource_type", &obj.ResourceType) + err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { - err = core.SDKErrorf(err, "", "resource_type-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) return } - err = core.UnmarshalPrimitive(m, "status", &obj.Status) + err = core.UnmarshalModel(m, "resource_group", &obj.ResourceGroup, UnmarshalResourceGroupReference) if err != nil { - err = core.SDKErrorf(err, "", "status-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "resource_group-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "vpc", &obj.VPC, UnmarshalVPCReference) + err = core.UnmarshalPrimitive(m, "resource_type", &obj.ResourceType) if err != nil { - err = core.SDKErrorf(err, "", "vpc-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "resource_type-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalZoneReference) + err = core.UnmarshalModel(m, "target", &obj.Target, UnmarshalPublicAddressRangeTarget) if err != nil { - err = core.SDKErrorf(err, "", "zone-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "target-error", common.GetComponentInfo()) return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } -// PublicGatewayCollection : PublicGatewayCollection struct -type PublicGatewayCollection struct { +// PublicAddressRangeCollection : PublicAddressRangeCollection struct +type PublicAddressRangeCollection struct { // A link to the first page of resources. First *PageLink `json:"first" validate:"required"` @@ -83505,16 +85384,16 @@ type PublicGatewayCollection struct { // except the last page. Next *PageLink `json:"next,omitempty"` - // A page of public gateways. - PublicGateways []PublicGateway `json:"public_gateways" validate:"required"` + // A page of public address ranges. + PublicAddressRanges []PublicAddressRange `json:"public_address_ranges" validate:"required"` // The total number of resources across all pages. TotalCount *int64 `json:"total_count" validate:"required"` } -// UnmarshalPublicGatewayCollection unmarshals an instance of PublicGatewayCollection from the specified map of raw messages. -func UnmarshalPublicGatewayCollection(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(PublicGatewayCollection) +// UnmarshalPublicAddressRangeCollection unmarshals an instance of PublicAddressRangeCollection from the specified map of raw messages. +func UnmarshalPublicAddressRangeCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicAddressRangeCollection) err = core.UnmarshalModel(m, "first", &obj.First, UnmarshalPageLink) if err != nil { err = core.SDKErrorf(err, "", "first-error", common.GetComponentInfo()) @@ -83530,9 +85409,9 @@ func UnmarshalPublicGatewayCollection(m map[string]json.RawMessage, result inter err = core.SDKErrorf(err, "", "next-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "public_gateways", &obj.PublicGateways, UnmarshalPublicGateway) + err = core.UnmarshalModel(m, "public_address_ranges", &obj.PublicAddressRanges, UnmarshalPublicAddressRange) if err != nil { - err = core.SDKErrorf(err, "", "public_gateways-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "public_address_ranges-error", common.GetComponentInfo()) return } err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) @@ -83545,7 +85424,7 @@ func UnmarshalPublicGatewayCollection(m map[string]json.RawMessage, result inter } // Retrieve the value to be passed to a request to access the next page of results -func (resp *PublicGatewayCollection) GetNextStart() (*string, error) { +func (resp *PublicAddressRangeCollection) GetNextStart() (*string, error) { if core.IsNil(resp.Next) { return nil, nil } @@ -83559,241 +85438,645 @@ func (resp *PublicGatewayCollection) GetNextStart() (*string, error) { return start, nil } -// PublicGatewayFloatingIP : The floating IP bound to this public gateway. -type PublicGatewayFloatingIP struct { - // The globally unique IP address. - Address *string `json:"address" validate:"required"` - - // The CRN for this floating IP. - CRN *string `json:"crn" validate:"required"` - - // If present, this property indicates the referenced resource has been deleted, and provides - // some supplementary information. - Deleted *Deleted `json:"deleted,omitempty"` - - // The URL for this floating IP. - Href *string `json:"href" validate:"required"` - - // The unique identifier for this floating IP. - ID *string `json:"id" validate:"required"` - - // The name for this floating IP. The name is unique across all floating IPs in the region. - Name *string `json:"name" validate:"required"` -} - -// UnmarshalPublicGatewayFloatingIP unmarshals an instance of PublicGatewayFloatingIP from the specified map of raw messages. -func UnmarshalPublicGatewayFloatingIP(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(PublicGatewayFloatingIP) - err = core.UnmarshalPrimitive(m, "address", &obj.Address) - if err != nil { - err = core.SDKErrorf(err, "", "address-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) - if err != nil { - err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalModel(m, "deleted", &obj.Deleted, UnmarshalDeleted) - if err != nil { - err = core.SDKErrorf(err, "", "deleted-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "href", &obj.Href) - if err != nil { - err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "id", &obj.ID) - if err != nil { - err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "name", &obj.Name) - if err != nil { - err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - -// PublicGatewayFloatingIPPrototype : PublicGatewayFloatingIPPrototype struct -// Models which "extend" this model: -// - PublicGatewayFloatingIPPrototypeFloatingIPIdentity -// - PublicGatewayFloatingIPPrototypeFloatingIPPrototypeTargetContext -type PublicGatewayFloatingIPPrototype struct { - // The unique identifier for this floating IP. - ID *string `json:"id,omitempty"` - - // The CRN for this floating IP. - CRN *string `json:"crn,omitempty"` - - // The URL for this floating IP. - Href *string `json:"href,omitempty"` - - // The globally unique IP address. - Address *string `json:"address,omitempty"` - - // The name for this floating IP. The name must not be used by another floating IP in the region. If unspecified, the - // name will be a hyphenated list of randomly-selected words. +// PublicAddressRangePatch : PublicAddressRangePatch struct +type PublicAddressRangePatch struct { + // The name for this public address range. The name must not be used by another public address range in the region. Name *string `json:"name,omitempty"` - // The resource group to use. If unspecified, the account's [default resource - // group](https://cloud.ibm.com/apidocs/resource-manager#introduction) will be used. - ResourceGroup ResourceGroupIdentityIntf `json:"resource_group,omitempty"` -} - -func (*PublicGatewayFloatingIPPrototype) isaPublicGatewayFloatingIPPrototype() bool { - return true -} - -type PublicGatewayFloatingIPPrototypeIntf interface { - isaPublicGatewayFloatingIPPrototype() bool + // The target to bind this public address range to. + // + // If the public address range is not currently bound to a target, both `target.vpc` and + // `target.zone` must be specified. + // + // Specify `null` to unbind the public address range from any existing target. + Target *PublicAddressRangeTargetPatch `json:"target,omitempty"` } -// UnmarshalPublicGatewayFloatingIPPrototype unmarshals an instance of PublicGatewayFloatingIPPrototype from the specified map of raw messages. -func UnmarshalPublicGatewayFloatingIPPrototype(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(PublicGatewayFloatingIPPrototype) - err = core.UnmarshalPrimitive(m, "id", &obj.ID) - if err != nil { - err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) - if err != nil { - err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "href", &obj.Href) - if err != nil { - err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "address", &obj.Address) - if err != nil { - err = core.SDKErrorf(err, "", "address-error", common.GetComponentInfo()) - return - } +// UnmarshalPublicAddressRangePatch unmarshals an instance of PublicAddressRangePatch from the specified map of raw messages. +func UnmarshalPublicAddressRangePatch(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicAddressRangePatch) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) return } - err = core.UnmarshalModel(m, "resource_group", &obj.ResourceGroup, UnmarshalResourceGroupIdentity) - if err != nil { - err = core.SDKErrorf(err, "", "resource_group-error", common.GetComponentInfo()) - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - -// PublicGatewayIdentity : Identifies a public gateway by a unique property. -// Models which "extend" this model: -// - PublicGatewayIdentityPublicGatewayIdentityByID -// - PublicGatewayIdentityPublicGatewayIdentityByCRN -// - PublicGatewayIdentityPublicGatewayIdentityByHref -type PublicGatewayIdentity struct { - // The unique identifier for this public gateway. - ID *string `json:"id,omitempty"` - - // The CRN for this public gateway. - CRN *string `json:"crn,omitempty"` - - // The URL for this public gateway. - Href *string `json:"href,omitempty"` -} - -func (*PublicGatewayIdentity) isaPublicGatewayIdentity() bool { - return true -} - -type PublicGatewayIdentityIntf interface { - isaPublicGatewayIdentity() bool -} - -// UnmarshalPublicGatewayIdentity unmarshals an instance of PublicGatewayIdentity from the specified map of raw messages. -func UnmarshalPublicGatewayIdentity(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(PublicGatewayIdentity) - err = core.UnmarshalPrimitive(m, "id", &obj.ID) - if err != nil { - err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) - if err != nil { - err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) - return - } - err = core.UnmarshalPrimitive(m, "href", &obj.Href) + err = core.UnmarshalModel(m, "target", &obj.Target, UnmarshalPublicAddressRangeTargetPatch) if err != nil { - err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) - return - } - reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) - return -} - -// PublicGatewayPatch : PublicGatewayPatch struct -type PublicGatewayPatch struct { - // The name for this public gateway. The name must not be used by another public gateway in the VPC. - Name *string `json:"name,omitempty"` -} - -// UnmarshalPublicGatewayPatch unmarshals an instance of PublicGatewayPatch from the specified map of raw messages. -func UnmarshalPublicGatewayPatch(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(PublicGatewayPatch) - err = core.UnmarshalPrimitive(m, "name", &obj.Name) - if err != nil { - err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + err = core.SDKErrorf(err, "", "target-error", common.GetComponentInfo()) return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } -// AsPatch returns a generic map representation of the PublicGatewayPatch -func (publicGatewayPatch *PublicGatewayPatch) AsPatch() (_patch map[string]interface{}, err error) { +// AsPatch returns a generic map representation of the PublicAddressRangePatch +func (publicAddressRangePatch *PublicAddressRangePatch) AsPatch() (_patch map[string]interface{}, err error) { _patch = map[string]interface{}{} - if !core.IsNil(publicGatewayPatch.Name) { - _patch["name"] = publicGatewayPatch.Name + if !core.IsNil(publicAddressRangePatch.Name) { + _patch["name"] = publicAddressRangePatch.Name + } + if !core.IsNil(publicAddressRangePatch.Target) { + _patch["target"] = publicAddressRangePatch.Target.asPatch() } return } -// PublicGatewayReference : PublicGatewayReference struct -type PublicGatewayReference struct { - // The CRN for this public gateway. +// PublicAddressRangeReference : PublicAddressRangeReference struct +type PublicAddressRangeReference struct { + // The CRN for this public address range. CRN *string `json:"crn" validate:"required"` // If present, this property indicates the referenced resource has been deleted, and provides // some supplementary information. Deleted *Deleted `json:"deleted,omitempty"` - // The URL for this public gateway. + // The URL for this public address range. Href *string `json:"href" validate:"required"` - // The unique identifier for this public gateway. + // The unique identifier for this public address range. ID *string `json:"id" validate:"required"` - // The name for this public gateway. The name is unique across all public gateways in the VPC. + // The name for this public address range. The name is unique across all public address ranges in the region. Name *string `json:"name" validate:"required"` // The resource type. ResourceType *string `json:"resource_type" validate:"required"` } -// Constants associated with the PublicGatewayReference.ResourceType property. +// Constants associated with the PublicAddressRangeReference.ResourceType property. // The resource type. const ( - PublicGatewayReferenceResourceTypePublicGatewayConst = "public_gateway" + PublicAddressRangeReferenceResourceTypePublicAddressRangeConst = "public_address_range" ) -// UnmarshalPublicGatewayReference unmarshals an instance of PublicGatewayReference from the specified map of raw messages. -func UnmarshalPublicGatewayReference(m map[string]json.RawMessage, result interface{}) (err error) { - obj := new(PublicGatewayReference) +// UnmarshalPublicAddressRangeReference unmarshals an instance of PublicAddressRangeReference from the specified map of raw messages. +func UnmarshalPublicAddressRangeReference(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicAddressRangeReference) + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "deleted", &obj.Deleted, UnmarshalDeleted) + if err != nil { + err = core.SDKErrorf(err, "", "deleted-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "href", &obj.Href) + if err != nil { + err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "resource_type", &obj.ResourceType) + if err != nil { + err = core.SDKErrorf(err, "", "resource_type-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// PublicAddressRangeTarget : The target this public address range is bound to. +// +// If absent, this pubic address range is not bound to a target. +// +// The target resources supported by this property is expected to +// [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. Future targets may omit the `vpc` +// property. +type PublicAddressRangeTarget struct { + // The VPC this public address range is bound to. + VPC *VPCReference `json:"vpc,omitempty"` + + // The zone this public address range resides in. + Zone *ZoneReference `json:"zone" validate:"required"` +} + +// UnmarshalPublicAddressRangeTarget unmarshals an instance of PublicAddressRangeTarget from the specified map of raw messages. +func UnmarshalPublicAddressRangeTarget(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicAddressRangeTarget) + err = core.UnmarshalModel(m, "vpc", &obj.VPC, UnmarshalVPCReference) + if err != nil { + err = core.SDKErrorf(err, "", "vpc-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalZoneReference) + if err != nil { + err = core.SDKErrorf(err, "", "zone-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// PublicAddressRangeTargetPatch : The target to bind this public address range to. +// +// If the public address range is not currently bound to a target, both `target.vpc` and +// `target.zone` must be specified. +// +// Specify `null` to unbind the public address range from any existing target. +type PublicAddressRangeTargetPatch struct { + // The VPC to bind this public address range to, replacing any existing VPC. + VPC VPCIdentityIntf `json:"vpc,omitempty"` + + // The zone this public address range will reside in, replacing any existing zone. + Zone ZoneIdentityIntf `json:"zone,omitempty"` +} + +// UnmarshalPublicAddressRangeTargetPatch unmarshals an instance of PublicAddressRangeTargetPatch from the specified map of raw messages. +func UnmarshalPublicAddressRangeTargetPatch(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicAddressRangeTargetPatch) + err = core.UnmarshalModel(m, "vpc", &obj.VPC, UnmarshalVPCIdentity) + if err != nil { + err = core.SDKErrorf(err, "", "vpc-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalZoneIdentity) + if err != nil { + err = core.SDKErrorf(err, "", "zone-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// asPatch returns a generic map representation of the PublicAddressRangeTargetPatch +func (publicAddressRangeTargetPatch *PublicAddressRangeTargetPatch) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(publicAddressRangeTargetPatch.VPC) { + _patch["vpc"] = publicAddressRangeTargetPatch.VPC.asPatch() + } + if !core.IsNil(publicAddressRangeTargetPatch.Zone) { + _patch["zone"] = publicAddressRangeTargetPatch.Zone.asPatch() + } + + return +} + +// PublicAddressRangeTargetPrototype : The target to bind this public address range to. If unspecified, the public address range will not be bound to a +// target at creation. +type PublicAddressRangeTargetPrototype struct { + // The VPC to bind this public address range to. + VPC VPCIdentityIntf `json:"vpc" validate:"required"` + + // The zone this public address range will reside in. + Zone ZoneIdentityIntf `json:"zone" validate:"required"` +} + +// NewPublicAddressRangeTargetPrototype : Instantiate PublicAddressRangeTargetPrototype (Generic Model Constructor) +func (*VpcV1) NewPublicAddressRangeTargetPrototype(vpc VPCIdentityIntf, zone ZoneIdentityIntf) (_model *PublicAddressRangeTargetPrototype, err error) { + _model = &PublicAddressRangeTargetPrototype{ + VPC: vpc, + Zone: zone, + } + err = core.ValidateStruct(_model, "required parameters") + if err != nil { + err = core.SDKErrorf(err, "", "model-missing-required", common.GetComponentInfo()) + } + return +} + +// UnmarshalPublicAddressRangeTargetPrototype unmarshals an instance of PublicAddressRangeTargetPrototype from the specified map of raw messages. +func UnmarshalPublicAddressRangeTargetPrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicAddressRangeTargetPrototype) + err = core.UnmarshalModel(m, "vpc", &obj.VPC, UnmarshalVPCIdentity) + if err != nil { + err = core.SDKErrorf(err, "", "vpc-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalZoneIdentity) + if err != nil { + err = core.SDKErrorf(err, "", "zone-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// PublicGateway : PublicGateway struct +type PublicGateway struct { + // The date and time that the public gateway was created. + CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` + + // The CRN for this public gateway. + CRN *string `json:"crn" validate:"required"` + + // The floating IP bound to this public gateway. + FloatingIP *PublicGatewayFloatingIP `json:"floating_ip" validate:"required"` + + // The URL for this public gateway. + Href *string `json:"href" validate:"required"` + + // The unique identifier for this public gateway. + ID *string `json:"id" validate:"required"` + + // The name for this public gateway. The name is unique across all public gateways in the VPC. + Name *string `json:"name" validate:"required"` + + // The resource group for this public gateway. + ResourceGroup *ResourceGroupReference `json:"resource_group" validate:"required"` + + // The resource type. + ResourceType *string `json:"resource_type" validate:"required"` + + // The status of this public gateway. + Status *string `json:"status" validate:"required"` + + // The VPC this public gateway resides in. + VPC *VPCReference `json:"vpc" validate:"required"` + + // The zone this public gateway resides in. + Zone *ZoneReference `json:"zone" validate:"required"` +} + +// Constants associated with the PublicGateway.ResourceType property. +// The resource type. +const ( + PublicGatewayResourceTypePublicGatewayConst = "public_gateway" +) + +// Constants associated with the PublicGateway.Status property. +// The status of this public gateway. +const ( + PublicGatewayStatusAvailableConst = "available" + PublicGatewayStatusDeletingConst = "deleting" + PublicGatewayStatusFailedConst = "failed" + PublicGatewayStatusPendingConst = "pending" +) + +// UnmarshalPublicGateway unmarshals an instance of PublicGateway from the specified map of raw messages. +func UnmarshalPublicGateway(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicGateway) + err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) + if err != nil { + err = core.SDKErrorf(err, "", "created_at-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "floating_ip", &obj.FloatingIP, UnmarshalPublicGatewayFloatingIP) + if err != nil { + err = core.SDKErrorf(err, "", "floating_ip-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "href", &obj.Href) + if err != nil { + err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "resource_group", &obj.ResourceGroup, UnmarshalResourceGroupReference) + if err != nil { + err = core.SDKErrorf(err, "", "resource_group-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "resource_type", &obj.ResourceType) + if err != nil { + err = core.SDKErrorf(err, "", "resource_type-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "status", &obj.Status) + if err != nil { + err = core.SDKErrorf(err, "", "status-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "vpc", &obj.VPC, UnmarshalVPCReference) + if err != nil { + err = core.SDKErrorf(err, "", "vpc-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "zone", &obj.Zone, UnmarshalZoneReference) + if err != nil { + err = core.SDKErrorf(err, "", "zone-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// PublicGatewayCollection : PublicGatewayCollection struct +type PublicGatewayCollection struct { + // A link to the first page of resources. + First *PageLink `json:"first" validate:"required"` + + // The maximum number of resources that can be returned by the request. + Limit *int64 `json:"limit" validate:"required"` + + // A link to the next page of resources. This property is present for all pages + // except the last page. + Next *PageLink `json:"next,omitempty"` + + // A page of public gateways. + PublicGateways []PublicGateway `json:"public_gateways" validate:"required"` + + // The total number of resources across all pages. + TotalCount *int64 `json:"total_count" validate:"required"` +} + +// UnmarshalPublicGatewayCollection unmarshals an instance of PublicGatewayCollection from the specified map of raw messages. +func UnmarshalPublicGatewayCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicGatewayCollection) + err = core.UnmarshalModel(m, "first", &obj.First, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "first-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "limit", &obj.Limit) + if err != nil { + err = core.SDKErrorf(err, "", "limit-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "next", &obj.Next, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "next-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "public_gateways", &obj.PublicGateways, UnmarshalPublicGateway) + if err != nil { + err = core.SDKErrorf(err, "", "public_gateways-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) + if err != nil { + err = core.SDKErrorf(err, "", "total_count-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// Retrieve the value to be passed to a request to access the next page of results +func (resp *PublicGatewayCollection) GetNextStart() (*string, error) { + if core.IsNil(resp.Next) { + return nil, nil + } + start, err := core.GetQueryParam(resp.Next.Href, "start") + if err != nil { + err = core.SDKErrorf(err, "", "read-query-param-error", common.GetComponentInfo()) + return nil, err + } else if start == nil { + return nil, nil + } + return start, nil +} + +// PublicGatewayFloatingIP : The floating IP bound to this public gateway. +type PublicGatewayFloatingIP struct { + // The globally unique IP address. + Address *string `json:"address" validate:"required"` + + // The CRN for this floating IP. + CRN *string `json:"crn" validate:"required"` + + // If present, this property indicates the referenced resource has been deleted, and provides + // some supplementary information. + Deleted *Deleted `json:"deleted,omitempty"` + + // The URL for this floating IP. + Href *string `json:"href" validate:"required"` + + // The unique identifier for this floating IP. + ID *string `json:"id" validate:"required"` + + // The name for this floating IP. The name is unique across all floating IPs in the region. + Name *string `json:"name" validate:"required"` +} + +// UnmarshalPublicGatewayFloatingIP unmarshals an instance of PublicGatewayFloatingIP from the specified map of raw messages. +func UnmarshalPublicGatewayFloatingIP(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicGatewayFloatingIP) + err = core.UnmarshalPrimitive(m, "address", &obj.Address) + if err != nil { + err = core.SDKErrorf(err, "", "address-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "deleted", &obj.Deleted, UnmarshalDeleted) + if err != nil { + err = core.SDKErrorf(err, "", "deleted-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "href", &obj.Href) + if err != nil { + err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// PublicGatewayFloatingIPPrototype : PublicGatewayFloatingIPPrototype struct +// Models which "extend" this model: +// - PublicGatewayFloatingIPPrototypeFloatingIPIdentity +// - PublicGatewayFloatingIPPrototypeFloatingIPPrototypeTargetContext +type PublicGatewayFloatingIPPrototype struct { + // The unique identifier for this floating IP. + ID *string `json:"id,omitempty"` + + // The CRN for this floating IP. + CRN *string `json:"crn,omitempty"` + + // The URL for this floating IP. + Href *string `json:"href,omitempty"` + + // The globally unique IP address. + Address *string `json:"address,omitempty"` + + // The name for this floating IP. The name must not be used by another floating IP in the region. If unspecified, the + // name will be a hyphenated list of randomly-selected words. + Name *string `json:"name,omitempty"` + + // The resource group to use. If unspecified, the account's [default resource + // group](https://cloud.ibm.com/apidocs/resource-manager#introduction) will be used. + ResourceGroup ResourceGroupIdentityIntf `json:"resource_group,omitempty"` +} + +func (*PublicGatewayFloatingIPPrototype) isaPublicGatewayFloatingIPPrototype() bool { + return true +} + +type PublicGatewayFloatingIPPrototypeIntf interface { + isaPublicGatewayFloatingIPPrototype() bool +} + +// UnmarshalPublicGatewayFloatingIPPrototype unmarshals an instance of PublicGatewayFloatingIPPrototype from the specified map of raw messages. +func UnmarshalPublicGatewayFloatingIPPrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicGatewayFloatingIPPrototype) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "href", &obj.Href) + if err != nil { + err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "address", &obj.Address) + if err != nil { + err = core.SDKErrorf(err, "", "address-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "resource_group", &obj.ResourceGroup, UnmarshalResourceGroupIdentity) + if err != nil { + err = core.SDKErrorf(err, "", "resource_group-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// PublicGatewayIdentity : Identifies a public gateway by a unique property. +// Models which "extend" this model: +// - PublicGatewayIdentityPublicGatewayIdentityByID +// - PublicGatewayIdentityPublicGatewayIdentityByCRN +// - PublicGatewayIdentityPublicGatewayIdentityByHref +type PublicGatewayIdentity struct { + // The unique identifier for this public gateway. + ID *string `json:"id,omitempty"` + + // The CRN for this public gateway. + CRN *string `json:"crn,omitempty"` + + // The URL for this public gateway. + Href *string `json:"href,omitempty"` +} + +func (*PublicGatewayIdentity) isaPublicGatewayIdentity() bool { + return true +} + +type PublicGatewayIdentityIntf interface { + isaPublicGatewayIdentity() bool +} + +// UnmarshalPublicGatewayIdentity unmarshals an instance of PublicGatewayIdentity from the specified map of raw messages. +func UnmarshalPublicGatewayIdentity(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicGatewayIdentity) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) + if err != nil { + err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "href", &obj.Href) + if err != nil { + err = core.SDKErrorf(err, "", "href-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// PublicGatewayPatch : PublicGatewayPatch struct +type PublicGatewayPatch struct { + // The name for this public gateway. The name must not be used by another public gateway in the VPC. + Name *string `json:"name,omitempty"` +} + +// UnmarshalPublicGatewayPatch unmarshals an instance of PublicGatewayPatch from the specified map of raw messages. +func UnmarshalPublicGatewayPatch(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicGatewayPatch) + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// AsPatch returns a generic map representation of the PublicGatewayPatch +func (publicGatewayPatch *PublicGatewayPatch) AsPatch() (_patch map[string]interface{}, err error) { + _patch = map[string]interface{}{} + if !core.IsNil(publicGatewayPatch.Name) { + _patch["name"] = publicGatewayPatch.Name + } + + return +} + +// PublicGatewayReference : PublicGatewayReference struct +type PublicGatewayReference struct { + // The CRN for this public gateway. + CRN *string `json:"crn" validate:"required"` + + // If present, this property indicates the referenced resource has been deleted, and provides + // some supplementary information. + Deleted *Deleted `json:"deleted,omitempty"` + + // The URL for this public gateway. + Href *string `json:"href" validate:"required"` + + // The unique identifier for this public gateway. + ID *string `json:"id" validate:"required"` + + // The name for this public gateway. The name is unique across all public gateways in the VPC. + Name *string `json:"name" validate:"required"` + + // The resource type. + ResourceType *string `json:"resource_type" validate:"required"` +} + +// Constants associated with the PublicGatewayReference.ResourceType property. +// The resource type. +const ( + PublicGatewayReferenceResourceTypePublicGatewayConst = "public_gateway" +) + +// UnmarshalPublicGatewayReference unmarshals an instance of PublicGatewayReference from the specified map of raw messages. +func UnmarshalPublicGatewayReference(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(PublicGatewayReference) err = core.UnmarshalPrimitive(m, "crn", &obj.CRN) if err != nil { err = core.SDKErrorf(err, "", "crn-error", common.GetComponentInfo()) @@ -84329,9 +86612,12 @@ type ReplaceBareMetalServerInitializationOptions struct { // inaccessible unless the specified image provides another means of access. Keys []KeyIdentityIntf `json:"keys" validate:"required"` - // User data to be made available when initializing the bare metal server. + // The default trusted profile to be used when initializing the bare metal server. // - // If unspecified, no user data will be made available. + // If unspecified, no default trusted profile will be made available. + DefaultTrustedProfile *BareMetalServerInitializationDefaultTrustedProfilePrototype `json:"default_trusted_profile,omitempty"` + + // The user data to be made available when initializing the bare metal server. UserData *string `json:"user_data,omitempty"` // Allows users to set headers on API requests. @@ -84365,6 +86651,12 @@ func (_options *ReplaceBareMetalServerInitializationOptions) SetKeys(keys []KeyI return _options } +// SetDefaultTrustedProfile : Allow user to set DefaultTrustedProfile +func (_options *ReplaceBareMetalServerInitializationOptions) SetDefaultTrustedProfile(defaultTrustedProfile *BareMetalServerInitializationDefaultTrustedProfilePrototype) *ReplaceBareMetalServerInitializationOptions { + _options.DefaultTrustedProfile = defaultTrustedProfile + return _options +} + // SetUserData : Allow user to set UserData func (_options *ReplaceBareMetalServerInitializationOptions) SetUserData(userData string) *ReplaceBareMetalServerInitializationOptions { _options.UserData = core.StringPtr(userData) @@ -85450,7 +87742,7 @@ type ReservationStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -88025,7 +90317,7 @@ type SecurityGroupRule struct { // to all local IP addresses (or from all local IP addresses, for outbound rules). Local SecurityGroupRuleLocalIntf `json:"local" validate:"required"` - // The name of the network protocol to allow. + // The network protocol. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -88067,7 +90359,7 @@ const ( ) // Constants associated with the SecurityGroupRule.Protocol property. -// The name of the network protocol to allow. +// The network protocol. // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. @@ -88465,7 +90757,7 @@ type SecurityGroupRulePrototype struct { // addresses (or from all local IP addresses, for outbound rules). Local SecurityGroupRuleLocalPrototypeIntf `json:"local,omitempty"` - // The name of the network protocol to allow. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The remote IP addresses or security groups from which this rule will allow traffic (or to @@ -88517,7 +90809,7 @@ const ( ) // Constants associated with the SecurityGroupRulePrototype.Protocol property. -// The name of the network protocol to allow. +// The network protocol. const ( SecurityGroupRulePrototypeProtocolAllConst = "all" SecurityGroupRulePrototypeProtocolIcmpConst = "icmp" @@ -89101,6 +91393,9 @@ type Share struct { // The unique identifier for this file share. ID *string `json:"id" validate:"required"` + // The owner assigned to the file share at creation. + InitialOwner *ShareInitialOwner `json:"initial_owner" validate:"required"` + // The maximum input/output operations per second (IOPS) for the file share. In addition, each client accessing the // share will be restricted to 48,000 IOPS. // @@ -89182,8 +91477,6 @@ type Share struct { ResourceType *string `json:"resource_type" validate:"required"` // The size of the file share (in gigabytes), excluding share snapshots. - // - // The maximum size for a share may increase in the future. Size *int64 `json:"size" validate:"required"` // The total number of snapshots for this share. @@ -89197,7 +91490,7 @@ type Share struct { // This property will be present when the `replication_role` is `replica`. SourceShare *ShareReference `json:"source_share,omitempty"` - // The snapshot this share was created from. + // The snapshot this file share was cloned from. // // This property will be present when the share was created from a snapshot. // @@ -89206,7 +91499,7 @@ type Share struct { // future. SourceSnapshot ShareSourceSnapshotIntf `json:"source_snapshot,omitempty"` - // Tags for this resource. + // The tags for this resource. UserTags []string `json:"user_tags" validate:"required"` // The zone this file share resides in. @@ -89360,6 +91653,11 @@ func UnmarshalShare(m map[string]json.RawMessage, result interface{}) (err error err = core.SDKErrorf(err, "", "id-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "initial_owner", &obj.InitialOwner, UnmarshalShareInitialOwner) + if err != nil { + err = core.SDKErrorf(err, "", "initial_owner-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "iops", &obj.Iops) if err != nil { err = core.SDKErrorf(err, "", "iops-error", common.GetComponentInfo()) @@ -89975,7 +92273,7 @@ type ShareJobStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -90052,8 +92350,11 @@ func UnmarshalShareLatestSync(m map[string]json.RawMessage, result interface{}) // ShareLifecycleReason : ShareLifecycleReason struct type ShareLifecycleReason struct { // A reason code for this lifecycle state: - // - `origin_share_access_revoked`: The resource has been revoked by the share owner + // - `cloning_failed`: The file share could not be cloned from the snapshot + // (contact IBM support) + // - `cloning_in_progress`: The file share is currently being cloned from the snapshot // - `internal_error`: internal error (contact IBM support) + // - `origin_share_access_revoked`: The resource has been revoked by the share owner // - `resource_suspended_by_provider`: The resource has been suspended (contact IBM // support) // @@ -90064,20 +92365,25 @@ type ShareLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } // Constants associated with the ShareLifecycleReason.Code property. // A reason code for this lifecycle state: -// - `origin_share_access_revoked`: The resource has been revoked by the share owner +// - `cloning_failed`: The file share could not be cloned from the snapshot +// (contact IBM support) +// - `cloning_in_progress`: The file share is currently being cloned from the snapshot // - `internal_error`: internal error (contact IBM support) +// - `origin_share_access_revoked`: The resource has been revoked by the share owner // - `resource_suspended_by_provider`: The resource has been suspended (contact IBM // support) // // The enumerated values for this property may // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. const ( + ShareLifecycleReasonCodeCloningFailedConst = "cloning_failed" + ShareLifecycleReasonCodeCloningInProgressConst = "cloning_in_progress" ShareLifecycleReasonCodeInternalErrorConst = "internal_error" ShareLifecycleReasonCodeOriginShareAccessRevokedConst = "origin_share_access_revoked" ShareLifecycleReasonCodeResourceSuspendedByProviderConst = "resource_suspended_by_provider" @@ -90545,9 +92851,9 @@ type ShareMountTargetVirtualNetworkInterfacePrototype struct { // `bare_metal_server_network_attachment`. EnableInfrastructureNat *bool `json:"enable_infrastructure_nat,omitempty"` - // Additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP identity, or - // a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be in the - // primary IP's subnet. + // The additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP + // identity, or a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be + // in the primary IP's subnet. // // If reserved IP identities are provided, the specified reserved IPs must be unbound. // @@ -90755,7 +93061,7 @@ type SharePatch struct { // - The share `accessor_binding_role` must not be `accessor`. Size *int64 `json:"size,omitempty"` - // Tags for this resource. + // The tags for this resource. UserTags []string `json:"user_tags,omitempty"` } @@ -91286,7 +93592,7 @@ type SharePrototype struct { // `source_share` referencing this file share. ReplicaShare *SharePrototypeShareContext `json:"replica_share,omitempty"` - // Tags for this resource. + // The tags for this resource. UserTags []string `json:"user_tags,omitempty"` // The access control mode for the share: @@ -91328,8 +93634,6 @@ type SharePrototype struct { // // The specified value must be within the permitted `capacity` range of the share's profile and supported by the // share's specified IOPS. - // - // The maximum size for a share may increase in the future. Size *int64 `json:"size,omitempty"` // The zone this file share will reside in. For a replica share in the same region as @@ -91357,7 +93661,7 @@ type SharePrototype struct { // The specified share may be in a different account, subject to IAM policies. OriginShare ShareIdentityIntf `json:"origin_share,omitempty"` - // The source snapshot for this file share. + // The source snapshot to clone this file share from. // // This file share will reside in the same zone as the specified source snapshot. // The snapshot must have the `lifecycle_state` as `stable` and `status` as `available` @@ -91523,7 +93827,7 @@ type SharePrototypeShareContext struct { // the source share will be used. ResourceGroup ResourceGroupIdentityIntf `json:"resource_group,omitempty"` - // Tags for this resource. + // The tags for this resource. UserTags []string `json:"user_tags,omitempty"` // The zone this replica file share will reside in. For a replica share in the same @@ -91717,7 +94021,7 @@ type ShareReplicationStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -92046,7 +94350,7 @@ type ShareSnapshotLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -92087,6 +94391,11 @@ func UnmarshalShareSnapshotLifecycleReason(m map[string]json.RawMessage, result // ShareSnapshotPatch : ShareSnapshotPatch struct type ShareSnapshotPatch struct { + // The name for this share snapshot. The name must be unique among all snapshots for the file share. For this property + // to be changed, the share's `replication_role` must not be + // `replica`. + Name *string `json:"name,omitempty"` + // The [user tags](https://cloud.ibm.com/apidocs/tagging#types-of-tags) associated with this share snapshot. UserTags []string `json:"user_tags,omitempty"` } @@ -92094,6 +94403,11 @@ type ShareSnapshotPatch struct { // UnmarshalShareSnapshotPatch unmarshals an instance of ShareSnapshotPatch from the specified map of raw messages. func UnmarshalShareSnapshotPatch(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ShareSnapshotPatch) + err = core.UnmarshalPrimitive(m, "name", &obj.Name) + if err != nil { + err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "user_tags", &obj.UserTags) if err != nil { err = core.SDKErrorf(err, "", "user_tags-error", common.GetComponentInfo()) @@ -92106,6 +94420,9 @@ func UnmarshalShareSnapshotPatch(m map[string]json.RawMessage, result interface{ // AsPatch returns a generic map representation of the ShareSnapshotPatch func (shareSnapshotPatch *ShareSnapshotPatch) AsPatch() (_patch map[string]interface{}, err error) { _patch = map[string]interface{}{} + if !core.IsNil(shareSnapshotPatch.Name) { + _patch["name"] = shareSnapshotPatch.Name + } if !core.IsNil(shareSnapshotPatch.UserTags) { _patch["user_tags"] = shareSnapshotPatch.UserTags } @@ -92127,7 +94444,7 @@ type ShareSnapshotStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -92286,6 +94603,14 @@ func UnmarshalShareSourceSnapshotPrototype(m map[string]json.RawMessage, result // Snapshot : Snapshot struct type Snapshot struct { + // The usage constraints to be matched against the requested instance properties to + // determine compatibility. While bare metal servers cannot be provisioned from snapshots, + // an image or volume created from this snapshot will inherit its `allowed_use` value. + // + // Only present on bootable snapshots. The value of this property will be inherited from + // the source volume or source snapshot at snapshot creation, but can be changed. + AllowedUse *SnapshotAllowedUse `json:"allowed_use,omitempty"` + // If present, the backup policy plan which created this snapshot. BackupPolicyPlan *BackupPolicyPlanReference `json:"backup_policy_plan,omitempty"` @@ -92306,7 +94631,7 @@ type Snapshot struct { // If absent, this snapshot is not associated with a catalog offering. CatalogOffering *SnapshotCatalogOffering `json:"catalog_offering,omitempty"` - // Clones for this snapshot. + // The clones for this snapshot. Clones []SnapshotClone `json:"clones" validate:"required"` // The copies of this snapshot. @@ -92423,6 +94748,11 @@ const ( // UnmarshalSnapshot unmarshals an instance of Snapshot from the specified map of raw messages. func UnmarshalSnapshot(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Snapshot) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalSnapshotAllowedUse) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "backup_policy_plan", &obj.BackupPolicyPlan, UnmarshalBackupPolicyPlanReference) if err != nil { err = core.SDKErrorf(err, "", "backup_policy_plan-error", common.GetComponentInfo()) @@ -92567,6 +94897,181 @@ func UnmarshalSnapshot(m map[string]json.RawMessage, result interface{}) (err er return } +// SnapshotAllowedUse : SnapshotAllowedUse struct +type SnapshotAllowedUse struct { + // The API version with which to evaluate the expressions. + ApiVersion *string `json:"api_version" validate:"required"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using the image data in + // this snapshot. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server" validate:"required"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this + // snapshot. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance" validate:"required"` +} + +// UnmarshalSnapshotAllowedUse unmarshals an instance of SnapshotAllowedUse from the specified map of raw messages. +func UnmarshalSnapshotAllowedUse(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(SnapshotAllowedUse) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// SnapshotAllowedUsePatch : SnapshotAllowedUsePatch struct +type SnapshotAllowedUsePatch struct { + // The API version with which to evaluate the expressions. + // + // If specified, the value must be between `2019-01-01` and today's date (in UTC). + ApiVersion *string `json:"api_version,omitempty"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using the image data in + // this snapshot. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server,omitempty"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this + // snapshot. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance,omitempty"` +} + +// UnmarshalSnapshotAllowedUsePatch unmarshals an instance of SnapshotAllowedUsePatch from the specified map of raw messages. +func UnmarshalSnapshotAllowedUsePatch(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(SnapshotAllowedUsePatch) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// asPatch returns a generic map representation of the SnapshotAllowedUsePatch +func (snapshotAllowedUsePatch *SnapshotAllowedUsePatch) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(snapshotAllowedUsePatch.ApiVersion) { + _patch["api_version"] = snapshotAllowedUsePatch.ApiVersion + } + if !core.IsNil(snapshotAllowedUsePatch.BareMetalServer) { + _patch["bare_metal_server"] = snapshotAllowedUsePatch.BareMetalServer + } + if !core.IsNil(snapshotAllowedUsePatch.Instance) { + _patch["instance"] = snapshotAllowedUsePatch.Instance + } + + return +} + +// SnapshotAllowedUsePrototype : SnapshotAllowedUsePrototype struct +type SnapshotAllowedUsePrototype struct { + // The API version with which to evaluate the expressions. + // + // If specified, the value must be between `2019-01-01` and today's date (in UTC). If unspecified, the `version` query + // parameter value will be used. + ApiVersion *string `json:"api_version,omitempty"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using the image data in + // this snapshot. + // + // If unspecified, the expression will be set to `true`. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server,omitempty"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this + // snapshot. + // + // If unspecified, the expression will be set to `true`. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance,omitempty"` +} + +// UnmarshalSnapshotAllowedUsePrototype unmarshals an instance of SnapshotAllowedUsePrototype from the specified map of raw messages. +func UnmarshalSnapshotAllowedUsePrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(SnapshotAllowedUsePrototype) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // SnapshotCatalogOffering : SnapshotCatalogOffering struct type SnapshotCatalogOffering struct { // The billing plan associated with the catalog offering version. @@ -92997,8 +95502,9 @@ type SnapshotConsistencyGroupPrototype struct { // group](https://cloud.ibm.com/apidocs/resource-manager#introduction) will be used. ResourceGroup ResourceGroupIdentityIntf `json:"resource_group,omitempty"` - // The data-consistent member snapshots to create. All snapshots must specify a - // `source_volume` attached to the same virtual server instance. + // The data-consistent member snapshots to create. Each snapshot must specify a + // `source_volume` attached to the same virtual server instance, and all source volumes must have a + // `storage_generation` value of `1`. Snapshots []SnapshotPrototypeSnapshotConsistencyGroupContext `json:"snapshots,omitempty"` } @@ -93223,8 +95729,81 @@ func UnmarshalSnapshotIdentity(m map[string]json.RawMessage, result interface{}) return } +// SnapshotInstanceProfileCollection : SnapshotInstanceProfileCollection struct +type SnapshotInstanceProfileCollection struct { + // A link to the first page of resources. + First *PageLink `json:"first" validate:"required"` + + // A page of instance profiles compatible with the snapshot. + InstanceProfiles []InstanceProfileReference `json:"instance_profiles" validate:"required"` + + // The maximum number of resources that can be returned by the request. + Limit *int64 `json:"limit" validate:"required"` + + // A link to the next page of resources. This property is present for all pages + // except the last page. + Next *PageLink `json:"next,omitempty"` + + // The total number of resources across all pages. + TotalCount *int64 `json:"total_count" validate:"required"` +} + +// UnmarshalSnapshotInstanceProfileCollection unmarshals an instance of SnapshotInstanceProfileCollection from the specified map of raw messages. +func UnmarshalSnapshotInstanceProfileCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(SnapshotInstanceProfileCollection) + err = core.UnmarshalModel(m, "first", &obj.First, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "first-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "instance_profiles", &obj.InstanceProfiles, UnmarshalInstanceProfileReference) + if err != nil { + err = core.SDKErrorf(err, "", "instance_profiles-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "limit", &obj.Limit) + if err != nil { + err = core.SDKErrorf(err, "", "limit-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "next", &obj.Next, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "next-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) + if err != nil { + err = core.SDKErrorf(err, "", "total_count-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// Retrieve the value to be passed to a request to access the next page of results +func (resp *SnapshotInstanceProfileCollection) GetNextStart() (*string, error) { + if core.IsNil(resp.Next) { + return nil, nil + } + start, err := core.GetQueryParam(resp.Next.Href, "start") + if err != nil { + err = core.SDKErrorf(err, "", "read-query-param-error", common.GetComponentInfo()) + return nil, err + } else if start == nil { + return nil, nil + } + return start, nil +} + // SnapshotPatch : SnapshotPatch struct type SnapshotPatch struct { + // The usage constraints to be matched against the requested instance properties to + // determine compatibility. While bare metal servers cannot be provisioned from snapshots, + // an image or volume created from this snapshot will inherit its `allowed_use` value. + // + // Can only be specified for bootable snapshots. + AllowedUse *SnapshotAllowedUsePatch `json:"allowed_use,omitempty"` + // The name for this snapshot. The name must not be used by another snapshot in the region. Name *string `json:"name,omitempty"` @@ -93235,6 +95814,11 @@ type SnapshotPatch struct { // UnmarshalSnapshotPatch unmarshals an instance of SnapshotPatch from the specified map of raw messages. func UnmarshalSnapshotPatch(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SnapshotPatch) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalSnapshotAllowedUsePatch) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) @@ -93252,6 +95836,9 @@ func UnmarshalSnapshotPatch(m map[string]json.RawMessage, result interface{}) (e // AsPatch returns a generic map representation of the SnapshotPatch func (snapshotPatch *SnapshotPatch) AsPatch() (_patch map[string]interface{}, err error) { _patch = map[string]interface{}{} + if !core.IsNil(snapshotPatch.AllowedUse) { + _patch["allowed_use"] = snapshotPatch.AllowedUse.asPatch() + } if !core.IsNil(snapshotPatch.Name) { _patch["name"] = snapshotPatch.Name } @@ -93267,7 +95854,13 @@ func (snapshotPatch *SnapshotPatch) AsPatch() (_patch map[string]interface{}, er // - SnapshotPrototypeSnapshotBySourceVolume // - SnapshotPrototypeSnapshotBySourceSnapshot type SnapshotPrototype struct { - // Clones to create for this snapshot. + // The usage constraints to match against the requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified for bootable snapshots. + AllowedUse *SnapshotAllowedUsePrototype `json:"allowed_use,omitempty"` + + // The clones to create for this snapshot. Clones []SnapshotClonePrototype `json:"clones,omitempty"` // The name for this snapshot. The name must not be used by another snapshot in the region. If unspecified, the name @@ -93311,6 +95904,11 @@ type SnapshotPrototypeIntf interface { // UnmarshalSnapshotPrototype unmarshals an instance of SnapshotPrototype from the specified map of raw messages. func UnmarshalSnapshotPrototype(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SnapshotPrototype) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalSnapshotAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "clones", &obj.Clones, UnmarshalSnapshotClonePrototype) if err != nil { err = core.SDKErrorf(err, "", "clones-error", common.GetComponentInfo()) @@ -96508,6 +99106,44 @@ func (options *UpdatePrivatePathServiceGatewayOptions) SetHeaders(param map[stri return options } +// UpdatePublicAddressRangeOptions : The UpdatePublicAddressRange options. +type UpdatePublicAddressRangeOptions struct { + // The public address range identifier. + ID *string `json:"id" validate:"required,ne="` + + // The public address range patch. + PublicAddressRangePatch map[string]interface{} `json:"PublicAddressRange_patch" validate:"required"` + + // Allows users to set headers on API requests. + Headers map[string]string +} + +// NewUpdatePublicAddressRangeOptions : Instantiate UpdatePublicAddressRangeOptions +func (*VpcV1) NewUpdatePublicAddressRangeOptions(id string, publicAddressRangePatch map[string]interface{}) *UpdatePublicAddressRangeOptions { + return &UpdatePublicAddressRangeOptions{ + ID: core.StringPtr(id), + PublicAddressRangePatch: publicAddressRangePatch, + } +} + +// SetID : Allow user to set ID +func (_options *UpdatePublicAddressRangeOptions) SetID(id string) *UpdatePublicAddressRangeOptions { + _options.ID = core.StringPtr(id) + return _options +} + +// SetPublicAddressRangePatch : Allow user to set PublicAddressRangePatch +func (_options *UpdatePublicAddressRangeOptions) SetPublicAddressRangePatch(publicAddressRangePatch map[string]interface{}) *UpdatePublicAddressRangeOptions { + _options.PublicAddressRangePatch = publicAddressRangePatch + return _options +} + +// SetHeaders : Allow user to set Headers +func (options *UpdatePublicAddressRangeOptions) SetHeaders(param map[string]string) *UpdatePublicAddressRangeOptions { + options.Headers = param + return options +} + // UpdatePublicGatewayOptions : The UpdatePublicGateway options. type UpdatePublicGatewayOptions struct { // The public gateway identifier. @@ -97646,8 +100282,7 @@ func UnmarshalVcpu(m map[string]json.RawMessage, result interface{}) (err error) // VPC : VPC struct type VPC struct { // Indicates whether this VPC is connected to Classic Infrastructure. If true, this VPC's resources have private - // network connectivity to the account's Classic Infrastructure resources. Only one VPC, per region, may be connected - // in this way. This value is set at creation and subsequently immutable. + // network connectivity to the account's Classic Infrastructure resources. ClassicAccess *bool `json:"classic_access" validate:"required"` // The date and time that the VPC was created. @@ -97698,6 +100333,9 @@ type VPC struct { // The name for this VPC. The name is unique across all VPCs in the region. Name *string `json:"name" validate:"required"` + // The public address ranges attached to this VPC. + PublicAddressRanges []PublicAddressRangeReference `json:"public_address_ranges" validate:"required"` + // The resource group for this VPC. ResourceGroup *ResourceGroupReference `json:"resource_group" validate:"required"` @@ -97812,6 +100450,11 @@ func UnmarshalVPC(m map[string]json.RawMessage, result interface{}) (err error) err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "public_address_ranges", &obj.PublicAddressRanges, UnmarshalPublicAddressRangeReference) + if err != nil { + err = core.SDKErrorf(err, "", "public_address_ranges-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "resource_group", &obj.ResourceGroup, UnmarshalResourceGroupReference) if err != nil { err = core.SDKErrorf(err, "", "resource_group-error", common.GetComponentInfo()) @@ -98236,7 +100879,7 @@ type VpcdnsResolutionBindingHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -98693,7 +101336,7 @@ type VPCHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -98748,6 +101391,7 @@ func (*VPCIdentity) isaVPCIdentity() bool { type VPCIdentityIntf interface { isaVPCIdentity() bool + asPatch() map[string]interface{} } // UnmarshalVPCIdentity unmarshals an instance of VPCIdentity from the specified map of raw messages. @@ -98772,6 +101416,22 @@ func UnmarshalVPCIdentity(m map[string]json.RawMessage, result interface{}) (err return } +// asPatch returns a generic map representation of the VPCIdentity +func (vpcIdentity *VPCIdentity) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(vpcIdentity.ID) { + _patch["id"] = vpcIdentity.ID + } + if !core.IsNil(vpcIdentity.CRN) { + _patch["crn"] = vpcIdentity.CRN + } + if !core.IsNil(vpcIdentity.Href) { + _patch["href"] = vpcIdentity.Href + } + + return +} + // VPCPatch : VPCPatch struct type VPCPatch struct { // The DNS configuration for this VPC. @@ -99051,7 +101711,7 @@ func UnmarshalVPCRemote(m map[string]json.RawMessage, result interface{}) (err e // - VPNGatewayPolicyMode // - VPNGatewayRouteMode type VPNGateway struct { - // Connections for this VPN gateway. + // The connections for this VPN gateway. Connections []VPNGatewayConnectionReference `json:"connections" validate:"required"` // The date and time that this VPN gateway was created. @@ -99101,7 +101761,7 @@ type VPNGateway struct { // The VPC this VPN gateway resides in. VPC *VPCReference `json:"vpc" validate:"required"` - // Policy mode VPN gateway. + // The mode for this VPN gateway. Mode *string `json:"mode,omitempty"` } @@ -99139,7 +101799,7 @@ const ( ) // Constants associated with the VPNGateway.Mode property. -// Policy mode VPN gateway. +// The mode for this VPN gateway. const ( VPNGatewayModePolicyConst = "policy" ) @@ -99322,7 +101982,7 @@ type VPNGatewayConnection struct { // The date and time that this VPN gateway connection was created. CreatedAt *strfmt.DateTime `json:"created_at" validate:"required"` - // The Dead Peer Detection settings. + // The dead peer detection configuration. DeadPeerDetection *VPNGatewayConnectionDpd `json:"dead_peer_detection" validate:"required"` // The establish mode of the VPN gateway connection: @@ -99378,7 +102038,7 @@ type VPNGatewayConnection struct { Peer VPNGatewayConnectionStaticRouteModePeerIntf `json:"peer,omitempty"` - // Routing protocols are disabled for this VPN gateway connection. + // The routing protocol for this VPN gateway connection. RoutingProtocol *string `json:"routing_protocol,omitempty"` // The VPN tunnel configuration for this VPN gateway connection (in static route mode). @@ -99431,7 +102091,7 @@ const ( ) // Constants associated with the VPNGatewayConnection.RoutingProtocol property. -// Routing protocols are disabled for this VPN gateway connection. +// The routing protocol for this VPN gateway connection. const ( VPNGatewayConnectionRoutingProtocolNoneConst = "none" ) @@ -99559,20 +102219,20 @@ func (resp *VPNGatewayConnectionCollection) GetNextStart() (*string, error) { return start, nil } -// VPNGatewayConnectionDpd : The Dead Peer Detection settings. +// VPNGatewayConnectionDpd : The dead peer detection configuration. type VPNGatewayConnectionDpd struct { - // Dead Peer Detection actions. + // The dead peer detection action. Action *string `json:"action" validate:"required"` - // Dead Peer Detection interval in seconds. + // The dead peer detection interval in seconds. Must not be greater than `timeout`. Interval *int64 `json:"interval" validate:"required"` - // Dead Peer Detection timeout in seconds. Must be at least the interval. + // The dead peer detection timeout in seconds. Must not be less than `interval`. Timeout *int64 `json:"timeout" validate:"required"` } // Constants associated with the VPNGatewayConnectionDpd.Action property. -// Dead Peer Detection actions. +// The dead peer detection action. const ( VPNGatewayConnectionDpdActionClearConst = "clear" VPNGatewayConnectionDpdActionHoldConst = "hold" @@ -99602,20 +102262,20 @@ func UnmarshalVPNGatewayConnectionDpd(m map[string]json.RawMessage, result inter return } -// VPNGatewayConnectionDpdPatch : The Dead Peer Detection settings. +// VPNGatewayConnectionDpdPatch : The dead peer detection configuration. type VPNGatewayConnectionDpdPatch struct { - // Dead Peer Detection actions. + // The dead peer detection action. Action *string `json:"action,omitempty"` - // Dead Peer Detection interval in seconds. + // The dead peer detection interval in seconds. Must not be greater than `timeout`. Interval *int64 `json:"interval,omitempty"` - // Dead Peer Detection timeout in seconds. Must be at least the interval. + // The dead peer detection timeout in seconds. Must not be less than `interval`. Timeout *int64 `json:"timeout,omitempty"` } // Constants associated with the VPNGatewayConnectionDpdPatch.Action property. -// Dead Peer Detection actions. +// The dead peer detection action. const ( VPNGatewayConnectionDpdPatchActionClearConst = "clear" VPNGatewayConnectionDpdPatchActionHoldConst = "hold" @@ -99661,20 +102321,20 @@ func (vpnGatewayConnectionDpdPatch *VPNGatewayConnectionDpdPatch) asPatch() (_pa return } -// VPNGatewayConnectionDpdPrototype : The Dead Peer Detection settings. +// VPNGatewayConnectionDpdPrototype : The dead peer detection configuration. type VPNGatewayConnectionDpdPrototype struct { - // Dead Peer Detection actions. + // The dead peer detection action. Action *string `json:"action,omitempty"` - // Dead Peer Detection interval in seconds. + // The dead peer detection interval in seconds. Must not be greater than `timeout`. Interval *int64 `json:"interval,omitempty"` - // Dead Peer Detection timeout in seconds. Must be at least the interval. + // The dead peer detection timeout in seconds. Must not be less than `interval`. Timeout *int64 `json:"timeout,omitempty"` } // Constants associated with the VPNGatewayConnectionDpdPrototype.Action property. -// Dead Peer Detection actions. +// The dead peer detection action. const ( VPNGatewayConnectionDpdPrototypeActionClearConst = "clear" VPNGatewayConnectionDpdPrototypeActionHoldConst = "hold" @@ -99991,7 +102651,7 @@ type VPNGatewayConnectionPatch struct { // If set to false, the VPN gateway connection is shut down. AdminStateUp *bool `json:"admin_state_up,omitempty"` - // The Dead Peer Detection settings. + // The dead peer detection configuration. DeadPeerDetection *VPNGatewayConnectionDpdPatch `json:"dead_peer_detection,omitempty"` // Indicates whether the traffic is distributed between the `up` tunnels of the VPN gateway connection when the VPC @@ -100386,7 +103046,7 @@ type VPNGatewayConnectionPrototype struct { // If set to false, the VPN gateway connection is shut down. AdminStateUp *bool `json:"admin_state_up,omitempty"` - // The Dead Peer Detection settings. + // The dead peer detection configuration. DeadPeerDetection *VPNGatewayConnectionDpdPrototype `json:"dead_peer_detection,omitempty"` // The establish mode of the VPN gateway connection: @@ -100424,7 +103084,7 @@ type VPNGatewayConnectionPrototype struct { Peer VPNGatewayConnectionStaticRouteModePeerPrototypeIntf `json:"peer,omitempty"` - // Routing protocols are disabled for this VPN gateway connection. + // The routing protocol for this VPN gateway connection. RoutingProtocol *string `json:"routing_protocol,omitempty"` } @@ -100442,7 +103102,7 @@ const ( ) // Constants associated with the VPNGatewayConnectionPrototype.RoutingProtocol property. -// Routing protocols are disabled for this VPN gateway connection. +// The routing protocol for this VPN gateway connection. const ( VPNGatewayConnectionPrototypeRoutingProtocolNoneConst = "none" ) @@ -100788,7 +103448,7 @@ type VPNGatewayConnectionStatusReason struct { // An explanation of the reason for this VPN gateway connection's status. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -100854,7 +103514,7 @@ type VPNGatewayConnectionTunnelStatusReason struct { // An explanation of the reason for this VPN gateway connection tunnel's status. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -100924,7 +103584,7 @@ type VPNGatewayHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -100979,7 +103639,7 @@ type VPNGatewayLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -101146,7 +103806,7 @@ type VPNGatewayMemberHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -101199,7 +103859,7 @@ type VPNGatewayMemberLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -101282,12 +103942,12 @@ type VPNGatewayPrototype struct { // Identifies a subnet by a unique property. Subnet SubnetIdentityIntf `json:"subnet" validate:"required"` - // Route mode VPN gateway. + // The mode for this VPN gateway. Mode *string `json:"mode,omitempty"` } // Constants associated with the VPNGatewayPrototype.Mode property. -// Route mode VPN gateway. +// The mode for this VPN gateway. const ( VPNGatewayPrototypeModeRouteConst = "route" ) @@ -101376,7 +104036,7 @@ type VPNServer struct { // health state of `inapplicable`. A `pending` resource may also have this state. HealthState *string `json:"health_state" validate:"required"` - // Fully qualified domain name assigned to this VPN server. + // The fully qualified domain name assigned to this VPN server. Hostname *string `json:"hostname" validate:"required"` // The URL for this VPN server. @@ -102085,7 +104745,7 @@ type VPNServerHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -102148,7 +104808,7 @@ type VPNServerLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -102584,7 +105244,7 @@ type VPNServerRouteHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -102634,7 +105294,7 @@ type VPNServerRouteLifecycleReason struct { // An explanation of the reason for this lifecycle state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this lifecycle state. + // A link to documentation about the reason for this lifecycle state. MoreInfo *string `json:"more_info,omitempty"` } @@ -103386,6 +106046,12 @@ type Volume struct { // The attachment states that support adjustable IOPS for this volume. AdjustableIopsStates []string `json:"adjustable_iops_states" validate:"required"` + // The usage constraints to be matched against the requested instance or bare metal server + // properties to determine compatibility. + // + // Only present for boot volumes. + AllowedUse *VolumeAllowedUse `json:"allowed_use,omitempty"` + // The attachment state of the volume // - `unattached`: Not attached to any virtual server instances // - `attached`: Attached to a virtual server instance (even if the instance is stopped) @@ -103602,6 +106268,11 @@ func UnmarshalVolume(m map[string]json.RawMessage, result interface{}) (err erro err = core.SDKErrorf(err, "", "adjustable_iops_states-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUse) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "attachment_state", &obj.AttachmentState) if err != nil { err = core.SDKErrorf(err, "", "attachment_state-error", common.GetComponentInfo()) @@ -103741,6 +106412,178 @@ func UnmarshalVolume(m map[string]json.RawMessage, result interface{}) (err erro return } +// VolumeAllowedUse : VolumeAllowedUse struct +type VolumeAllowedUse struct { + // The API version with which to evaluate the expressions. + ApiVersion *string `json:"api_version" validate:"required"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using the image data in + // this volume. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server" validate:"required"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this volume. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance" validate:"required"` +} + +// UnmarshalVolumeAllowedUse unmarshals an instance of VolumeAllowedUse from the specified map of raw messages. +func UnmarshalVolumeAllowedUse(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(VolumeAllowedUse) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// VolumeAllowedUsePatch : VolumeAllowedUsePatch struct +type VolumeAllowedUsePatch struct { + // The API version with which to evaluate the expressions. + // + // If specified, the value must be between `2019-01-01` and today's date (in UTC). + ApiVersion *string `json:"api_version,omitempty"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using the image data in + // this volume. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server,omitempty"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this volume + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance,omitempty"` +} + +// UnmarshalVolumeAllowedUsePatch unmarshals an instance of VolumeAllowedUsePatch from the specified map of raw messages. +func UnmarshalVolumeAllowedUsePatch(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(VolumeAllowedUsePatch) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// asPatch returns a generic map representation of the VolumeAllowedUsePatch +func (volumeAllowedUsePatch *VolumeAllowedUsePatch) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(volumeAllowedUsePatch.ApiVersion) { + _patch["api_version"] = volumeAllowedUsePatch.ApiVersion + } + if !core.IsNil(volumeAllowedUsePatch.BareMetalServer) { + _patch["bare_metal_server"] = volumeAllowedUsePatch.BareMetalServer + } + if !core.IsNil(volumeAllowedUsePatch.Instance) { + _patch["instance"] = volumeAllowedUsePatch.Instance + } + + return +} + +// VolumeAllowedUsePrototype : VolumeAllowedUsePrototype struct +type VolumeAllowedUsePrototype struct { + // The API version with which to evaluate the expressions. + // + // If specified, the value must be between `2019-01-01` and today's date (in UTC). If unspecified, the `version` query + // parameter value will be used. + ApiVersion *string `json:"api_version,omitempty"` + + // The expression that must be satisfied by the properties of a bare metal server provisioned using the image data in + // this volume. + // + // If unspecified, the expression will be set to `true`. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variable is supported, corresponding + // to the `BareMetalServer` property: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled. + BareMetalServer *string `json:"bare_metal_server,omitempty"` + + // The expression that must be satisfied by the properties of a virtual server instance provisioned using this volume. + // + // If unspecified, the expression will be set to `true`. + // + // The expression follows [Common Expression Language](https://github.com/google/cel-spec/blob/master/doc/langdef.md), + // but does not support built-in functions and macros. In addition, the following variables are supported, + // corresponding to `Instance` properties: + // - `enable_secure_boot` (boolean): Indicates whether secure boot is enabled + // - `gpu.count` (integer): The number of GPUs + // - `gpu.manufacturer` (string): The GPU manufacturer + // - `gpu.memory` (integer): The overall amount of GPU memory in GiB (gibibytes) + // - `gpu.model` (string): The GPU model. + Instance *string `json:"instance,omitempty"` +} + +// UnmarshalVolumeAllowedUsePrototype unmarshals an instance of VolumeAllowedUsePrototype from the specified map of raw messages. +func UnmarshalVolumeAllowedUsePrototype(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(VolumeAllowedUsePrototype) + err = core.UnmarshalPrimitive(m, "api_version", &obj.ApiVersion) + if err != nil { + err = core.SDKErrorf(err, "", "api_version-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "bare_metal_server", &obj.BareMetalServer) + if err != nil { + err = core.SDKErrorf(err, "", "bare_metal_server-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "instance", &obj.Instance) + if err != nil { + err = core.SDKErrorf(err, "", "instance-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // VolumeAttachment : VolumeAttachment struct type VolumeAttachment struct { // The maximum bandwidth (in megabits per second) for the volume when attached to this instance. This may be lower than @@ -103753,7 +106596,7 @@ type VolumeAttachment struct { // Indicates whether deleting the instance will also delete the attached volume. DeleteVolumeOnInstanceDelete *bool `json:"delete_volume_on_instance_delete" validate:"required"` - // Information about how the volume is exposed to the instance operating system. + // The configuration for the volume as a device in the instance operating system. // // This property may be absent if the volume attachment's `status` is not `attached`. Device *VolumeAttachmentDevice `json:"device,omitempty"` @@ -104185,6 +107028,13 @@ type VolumeAttachmentPrototypeVolume struct { // If unspecified, the `encryption` type for the volume will be `provider_managed`. EncryptionKey EncryptionKeyIdentityIntf `json:"encryption_key,omitempty"` + // The usage constraints to be matched against requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified if `source_snapshot` is bootable. If not specified, the value of + // this property will be inherited from the `source_snapshot`. + AllowedUse *VolumeAllowedUsePrototype `json:"allowed_use,omitempty"` + // The snapshot to use as a source for the volume's data. // // The specified snapshot may be in a different account, subject to IAM policies. @@ -104260,6 +107110,11 @@ func UnmarshalVolumeAttachmentPrototypeVolume(m map[string]json.RawMessage, resu err = core.SDKErrorf(err, "", "encryption_key-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "source_snapshot", &obj.SourceSnapshot, UnmarshalSnapshotIdentity) if err != nil { err = core.SDKErrorf(err, "", "source_snapshot-error", common.GetComponentInfo()) @@ -104275,7 +107130,7 @@ type VolumeAttachmentReferenceInstanceContext struct { // some supplementary information. Deleted *Deleted `json:"deleted,omitempty"` - // Information about how the volume is exposed to the instance operating system. + // The configuration for the volume as a device in the instance operating system. // // This property may be absent if the volume attachment's `status` is not `attached`. Device *VolumeAttachmentDevice `json:"device,omitempty"` @@ -104341,7 +107196,7 @@ type VolumeAttachmentReferenceVolumeContext struct { // some supplementary information. Deleted *Deleted `json:"deleted,omitempty"` - // Information about how the volume is exposed to the instance operating system. + // The configuration for the volume as a device in the instance operating system. // // This property may be absent if the volume attachment's `status` is not `attached`. Device *VolumeAttachmentDevice `json:"device,omitempty"` @@ -104526,7 +107381,7 @@ type VolumeHealthReason struct { // An explanation of the reason for this health state. Message *string `json:"message" validate:"required"` - // Link to documentation about the reason for this health state. + // A link to documentation about the reason for this health state. MoreInfo *string `json:"more_info,omitempty"` } @@ -104605,8 +107460,80 @@ func UnmarshalVolumeIdentity(m map[string]json.RawMessage, result interface{}) ( return } +// VolumeInstanceProfileCollection : VolumeInstanceProfileCollection struct +type VolumeInstanceProfileCollection struct { + // A link to the first page of resources. + First *PageLink `json:"first" validate:"required"` + + // A page of instance profiles compatible with the volume. + InstanceProfiles []InstanceProfileReference `json:"instance_profiles" validate:"required"` + + // The maximum number of resources that can be returned by the request. + Limit *int64 `json:"limit" validate:"required"` + + // A link to the next page of resources. This property is present for all pages + // except the last page. + Next *PageLink `json:"next,omitempty"` + + // The total number of resources across all pages. + TotalCount *int64 `json:"total_count" validate:"required"` +} + +// UnmarshalVolumeInstanceProfileCollection unmarshals an instance of VolumeInstanceProfileCollection from the specified map of raw messages. +func UnmarshalVolumeInstanceProfileCollection(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(VolumeInstanceProfileCollection) + err = core.UnmarshalModel(m, "first", &obj.First, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "first-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "instance_profiles", &obj.InstanceProfiles, UnmarshalInstanceProfileReference) + if err != nil { + err = core.SDKErrorf(err, "", "instance_profiles-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "limit", &obj.Limit) + if err != nil { + err = core.SDKErrorf(err, "", "limit-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalModel(m, "next", &obj.Next, UnmarshalPageLink) + if err != nil { + err = core.SDKErrorf(err, "", "next-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) + if err != nil { + err = core.SDKErrorf(err, "", "total_count-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// Retrieve the value to be passed to a request to access the next page of results +func (resp *VolumeInstanceProfileCollection) GetNextStart() (*string, error) { + if core.IsNil(resp.Next) { + return nil, nil + } + start, err := core.GetQueryParam(resp.Next.Href, "start") + if err != nil { + err = core.SDKErrorf(err, "", "read-query-param-error", common.GetComponentInfo()) + return nil, err + } else if start == nil { + return nil, nil + } + return start, nil +} + // VolumePatch : VolumePatch struct type VolumePatch struct { + // The usage constraints to be matched against the requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified for boot volumes with an `attachment_state` of `unattached`. + AllowedUse *VolumeAllowedUsePatch `json:"allowed_use,omitempty"` + // The maximum bandwidth (in megabits per second) for the volume. // // If specified, the volume profile must not have a `bandwidth.type` of `dependent`. @@ -104649,6 +107576,11 @@ type VolumePatch struct { // UnmarshalVolumePatch unmarshals an instance of VolumePatch from the specified map of raw messages. func UnmarshalVolumePatch(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(VolumePatch) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUsePatch) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "bandwidth", &obj.Bandwidth) if err != nil { err = core.SDKErrorf(err, "", "bandwidth-error", common.GetComponentInfo()) @@ -104686,6 +107618,9 @@ func UnmarshalVolumePatch(m map[string]json.RawMessage, result interface{}) (err // AsPatch returns a generic map representation of the VolumePatch func (volumePatch *VolumePatch) AsPatch() (_patch map[string]interface{}, err error) { _patch = map[string]interface{}{} + if !core.IsNil(volumePatch.AllowedUse) { + _patch["allowed_use"] = volumePatch.AllowedUse.asPatch() + } if !core.IsNil(volumePatch.Bandwidth) { _patch["bandwidth"] = volumePatch.Bandwidth } @@ -105458,6 +108393,13 @@ type VolumePrototype struct { // If unspecified, the `encryption` type for the volume will be `provider_managed`. EncryptionKey EncryptionKeyIdentityIntf `json:"encryption_key,omitempty"` + // The usage constraints to be matched against requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified if `source_snapshot` is bootable. If not specified, the value of + // this property will be inherited from the `source_snapshot`. + AllowedUse *VolumeAllowedUsePrototype `json:"allowed_use,omitempty"` + // The snapshot to use as a source for the volume's data. // // The specified snapshot may be in a different account, subject to IAM policies. @@ -105523,6 +108465,11 @@ func UnmarshalVolumePrototype(m map[string]json.RawMessage, result interface{}) err = core.SDKErrorf(err, "", "encryption_key-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "source_snapshot", &obj.SourceSnapshot, UnmarshalSnapshotIdentity) if err != nil { err = core.SDKErrorf(err, "", "source_snapshot-error", common.GetComponentInfo()) @@ -105534,6 +108481,13 @@ func UnmarshalVolumePrototype(m map[string]json.RawMessage, result interface{}) // VolumePrototypeInstanceByImageContext : VolumePrototypeInstanceByImageContext struct type VolumePrototypeInstanceByImageContext struct { + // The usage constraints to be matched against requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified if `source_snapshot` is bootable. If not specified, the value of + // this property will be inherited from the `source_image`. + AllowedUse *VolumeAllowedUsePrototype `json:"allowed_use,omitempty"` + // The maximum bandwidth (in megabits per second) for the volume. // // If the volume profile has a `bandwidth.type` of `dependent`, this property is system-managed and must not be @@ -105595,6 +108549,11 @@ func (*VpcV1) NewVolumePrototypeInstanceByImageContext(profile VolumeProfileIden // UnmarshalVolumePrototypeInstanceByImageContext unmarshals an instance of VolumePrototypeInstanceByImageContext from the specified map of raw messages. func UnmarshalVolumePrototypeInstanceByImageContext(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(VolumePrototypeInstanceByImageContext) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "bandwidth", &obj.Bandwidth) if err != nil { err = core.SDKErrorf(err, "", "bandwidth-error", common.GetComponentInfo()) @@ -105641,6 +108600,13 @@ func UnmarshalVolumePrototypeInstanceByImageContext(m map[string]json.RawMessage // VolumePrototypeInstanceBySourceSnapshotContext : VolumePrototypeInstanceBySourceSnapshotContext struct type VolumePrototypeInstanceBySourceSnapshotContext struct { + // The usage constraints to be matched against requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified if `source_snapshot` is bootable. If not specified, the value of + // this property will be inherited from the `source_snapshot`. + AllowedUse *VolumeAllowedUsePrototype `json:"allowed_use,omitempty"` + // The maximum bandwidth (in megabits per second) for the volume. // // If the volume profile has a `bandwidth.type` of `dependent`, this property is system-managed and must not be @@ -105708,6 +108674,11 @@ func (*VpcV1) NewVolumePrototypeInstanceBySourceSnapshotContext(profile VolumePr // UnmarshalVolumePrototypeInstanceBySourceSnapshotContext unmarshals an instance of VolumePrototypeInstanceBySourceSnapshotContext from the specified map of raw messages. func UnmarshalVolumePrototypeInstanceBySourceSnapshotContext(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(VolumePrototypeInstanceBySourceSnapshotContext) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "bandwidth", &obj.Bandwidth) if err != nil { err = core.SDKErrorf(err, "", "bandwidth-error", common.GetComponentInfo()) @@ -105927,7 +108898,7 @@ type VolumeStatusReason struct { // An explanation of the status reason. Message *string `json:"message" validate:"required"` - // Link to documentation about this status reason. + // A link to documentation about this status reason. MoreInfo *string `json:"more_info,omitempty"` } @@ -107009,6 +109980,9 @@ type BackupPolicyPrototypeBackupPolicyMatchResourceTypeInstancePrototype struct // The resource type this backup policy will apply to. Resources that have both a matching type and a matching user tag // will be subject to the backup policy. + // + // A backup policy of type `instance` will create a backup of all volumes with a + // `storage_generation` value of `1` attached to the instance. MatchResourceType *string `json:"match_resource_type" validate:"required"` } @@ -107022,6 +109996,9 @@ const ( // Constants associated with the BackupPolicyPrototypeBackupPolicyMatchResourceTypeInstancePrototype.MatchResourceType property. // The resource type this backup policy will apply to. Resources that have both a matching type and a matching user tag // will be subject to the backup policy. +// +// A backup policy of type `instance` will create a backup of all volumes with a +// `storage_generation` value of `1` attached to the instance. const ( BackupPolicyPrototypeBackupPolicyMatchResourceTypeInstancePrototypeMatchResourceTypeInstanceConst = "instance" ) @@ -107583,7 +110560,7 @@ func UnmarshalBareMetalServerBootTargetBareMetalServerDiskReference(m map[string // BareMetalServerInitializationUserAccountBareMetalServerInitializationHostUserAccount : BareMetalServerInitializationUserAccountBareMetalServerInitializationHostUserAccount struct // This model "extends" BareMetalServerInitializationUserAccount type BareMetalServerInitializationUserAccountBareMetalServerInitializationHostUserAccount struct { - // The password at initialization, encrypted using `encryption_key`, and returned base64-encoded. + // The administrator password at initialization, encrypted using `encryption_key`, and returned base64-encoded. EncryptedPassword *[]byte `json:"encrypted_password" validate:"required"` // The public SSH key used to encrypt the password. @@ -107676,11 +110653,6 @@ type BareMetalServerNetworkAttachmentByPci struct { // The VLAN IDs allowed for `vlan` attachments using this PCI attachment. AllowedVlans []int64 `json:"allowed_vlans" validate:"required"` - // - `pci`: a physical PCI device which can only be created or deleted when the bare metal - // server is stopped - // - Has an `allowed_vlans` property which controls the VLANs that will be permitted - // to use the PCI attachment - // - Cannot directly use an IEEE 802.1Q tag. InterfaceType *string `json:"interface_type" validate:"required"` } @@ -107713,11 +110685,6 @@ const ( ) // Constants associated with the BareMetalServerNetworkAttachmentByPci.InterfaceType property. -// - `pci`: a physical PCI device which can only be created or deleted when the bare metal -// server is stopped -// - Has an `allowed_vlans` property which controls the VLANs that will be permitted -// to use the PCI attachment -// - Cannot directly use an IEEE 802.1Q tag. const ( BareMetalServerNetworkAttachmentByPciInterfaceTypePciConst = "pci" ) @@ -107851,9 +110818,6 @@ type BareMetalServerNetworkAttachmentByVlan struct { // this network attachment's `vlan`. AllowToFloat *bool `json:"allow_to_float" validate:"required"` - // - `vlan`: a virtual device, used through a `pci` device that has the `vlan` in its array - // of `allowed_vlans`. - // - Must use an IEEE 802.1Q tag. InterfaceType *string `json:"interface_type" validate:"required"` // The IEEE 802.1Q VLAN ID that must be used for all traffic on this attachment. @@ -107889,9 +110853,6 @@ const ( ) // Constants associated with the BareMetalServerNetworkAttachmentByVlan.InterfaceType property. -// - `vlan`: a virtual device, used through a `pci` device that has the `vlan` in its array -// of `allowed_vlans`. -// - Must use an IEEE 802.1Q tag. const ( BareMetalServerNetworkAttachmentByVlanInterfaceTypeVlanConst = "vlan" ) @@ -108052,9 +111013,9 @@ type BareMetalServerNetworkAttachmentPrototypeVirtualNetworkInterfaceVirtualNetw // `bare_metal_server_network_attachment`. EnableInfrastructureNat *bool `json:"enable_infrastructure_nat,omitempty"` - // Additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP identity, or - // a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be in the - // primary IP's subnet. + // The additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP + // identity, or a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be + // in the primary IP's subnet. // // If reserved IP identities are provided, the specified reserved IPs must be unbound. // @@ -108196,22 +111157,10 @@ type BareMetalServerNetworkAttachmentPrototypeBareMetalServerNetworkAttachmentBy // The VLAN IDs to allow for `vlan` attachments using this PCI attachment. AllowedVlans []int64 `json:"allowed_vlans,omitempty"` - // - `pci`: a physical PCI device which can only be created or deleted when the bare metal - // server is stopped - // - Has an `allowed_vlans` property which controls the VLANs that will be permitted - // to use the PCI attachment - // - Cannot directly use an IEEE 802.1Q tag. - // - Not supported on bare metal servers with a `cpu.architecture` of `s390x`. InterfaceType *string `json:"interface_type" validate:"required"` } // Constants associated with the BareMetalServerNetworkAttachmentPrototypeBareMetalServerNetworkAttachmentByPciPrototype.InterfaceType property. -// - `pci`: a physical PCI device which can only be created or deleted when the bare metal -// server is stopped -// - Has an `allowed_vlans` property which controls the VLANs that will be permitted -// to use the PCI attachment -// - Cannot directly use an IEEE 802.1Q tag. -// - Not supported on bare metal servers with a `cpu.architecture` of `s390x`. const ( BareMetalServerNetworkAttachmentPrototypeBareMetalServerNetworkAttachmentByPciPrototypeInterfaceTypePciConst = "pci" ) @@ -108282,9 +111231,6 @@ type BareMetalServerNetworkAttachmentPrototypeBareMetalServerNetworkAttachmentBy // this network attachment's `vlan`. AllowToFloat *bool `json:"allow_to_float,omitempty"` - // - `vlan`: a virtual device, used through a `pci` device that has the `vlan` in its array - // of `allowed_vlans`. - // - Must use an IEEE 802.1Q tag. InterfaceType *string `json:"interface_type" validate:"required"` // The IEEE 802.1Q VLAN ID that must be used for all traffic on this attachment. @@ -108292,9 +111238,6 @@ type BareMetalServerNetworkAttachmentPrototypeBareMetalServerNetworkAttachmentBy } // Constants associated with the BareMetalServerNetworkAttachmentPrototypeBareMetalServerNetworkAttachmentByVlanPrototype.InterfaceType property. -// - `vlan`: a virtual device, used through a `pci` device that has the `vlan` in its array -// of `allowed_vlans`. -// - Must use an IEEE 802.1Q tag. const ( BareMetalServerNetworkAttachmentPrototypeBareMetalServerNetworkAttachmentByVlanPrototypeInterfaceTypeVlanConst = "vlan" ) @@ -108463,8 +111406,6 @@ type BareMetalServerNetworkInterfaceByHiperSocket struct { // corresponding network attachment. Type *string `json:"type" validate:"required"` - // - `hipersocket`: a virtual network device that provides high-speed TCP/IP connectivity - // within a `s390x` based system. InterfaceType *string `json:"interface_type" validate:"required"` } @@ -108500,8 +111441,6 @@ const ( ) // Constants associated with the BareMetalServerNetworkInterfaceByHiperSocket.InterfaceType property. -// - `hipersocket`: a virtual network device that provides high-speed TCP/IP connectivity -// within a `s390x` based system. const ( BareMetalServerNetworkInterfaceByHiperSocketInterfaceTypeHipersocketConst = "hipersocket" ) @@ -108719,11 +111658,6 @@ type BareMetalServerNetworkInterfaceByPci struct { // `allow_vlans` of the corresponding network attachment. AllowedVlans []int64 `json:"allowed_vlans" validate:"required"` - // - `pci`: a physical PCI device which can only be created or deleted when the bare metal - // server is stopped - // - Has an `allowed_vlans` property which controls the VLANs that will be permitted - // to use the PCI interface - // - Cannot directly use an IEEE 802.1Q tag. InterfaceType *string `json:"interface_type" validate:"required"` } @@ -108759,11 +111693,6 @@ const ( ) // Constants associated with the BareMetalServerNetworkInterfaceByPci.InterfaceType property. -// - `pci`: a physical PCI device which can only be created or deleted when the bare metal -// server is stopped -// - Has an `allowed_vlans` property which controls the VLANs that will be permitted -// to use the PCI interface -// - Cannot directly use an IEEE 802.1Q tag. const ( BareMetalServerNetworkInterfaceByPciInterfaceTypePciConst = "pci" ) @@ -108995,11 +111924,6 @@ type BareMetalServerNetworkInterfaceByVlan struct { // that of the `allow_to_float` property of the corresponding network attachment. AllowInterfaceToFloat *bool `json:"allow_interface_to_float" validate:"required"` - // - `vlan`: a virtual device, used through a `pci` device that has the `vlan` in its array - // of `allowed_vlans`. - // - Must use an IEEE 802.1Q tag. - // - Has its own security groups and does not inherit those of the PCI device through - // which traffic flows. InterfaceType *string `json:"interface_type" validate:"required"` // The VLAN ID used in the IEEE 802.1Q tag present in all traffic on this interface. @@ -109043,11 +111967,6 @@ const ( ) // Constants associated with the BareMetalServerNetworkInterfaceByVlan.InterfaceType property. -// - `vlan`: a virtual device, used through a `pci` device that has the `vlan` in its array -// of `allowed_vlans`. -// - Must use an IEEE 802.1Q tag. -// - Has its own security groups and does not inherit those of the PCI device through -// which traffic flows. const ( BareMetalServerNetworkInterfaceByVlanInterfaceTypeVlanConst = "vlan" ) @@ -109199,16 +112118,10 @@ type BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByHi // The associated subnet. Subnet SubnetIdentityIntf `json:"subnet" validate:"required"` - // - `hipersocket`: a virtual network device that provides high-speed TCP/IP connectivity - // within a `s390x` based system. - // - Not supported on bare metal servers with a `cpu.architecture` of `amd64`. InterfaceType *string `json:"interface_type" validate:"required"` } // Constants associated with the BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByHiperSocketPrototype.InterfaceType property. -// - `hipersocket`: a virtual network device that provides high-speed TCP/IP connectivity -// within a `s390x` based system. -// - Not supported on bare metal servers with a `cpu.architecture` of `amd64`. const ( BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByHiperSocketPrototypeInterfaceTypeHipersocketConst = "hipersocket" ) @@ -109321,22 +112234,10 @@ type BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByPc // The VLAN IDs to allow for `vlan` interfaces using this PCI interface. AllowedVlans []int64 `json:"allowed_vlans,omitempty"` - // - `pci`: a physical PCI device which can only be created or deleted when the bare metal - // server is stopped - // - Has an `allowed_vlans` property which controls the VLANs that will be permitted - // to use the PCI interface - // - Cannot directly use an IEEE 802.1Q tag. - // - Not supported on bare metal servers with a `cpu.architecture` of `s390x`. InterfaceType *string `json:"interface_type" validate:"required"` } // Constants associated with the BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByPciPrototype.InterfaceType property. -// - `pci`: a physical PCI device which can only be created or deleted when the bare metal -// server is stopped -// - Has an `allowed_vlans` property which controls the VLANs that will be permitted -// to use the PCI interface -// - Cannot directly use an IEEE 802.1Q tag. -// - Not supported on bare metal servers with a `cpu.architecture` of `s390x`. const ( BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByPciPrototypeInterfaceTypePciConst = "pci" ) @@ -109468,12 +112369,6 @@ type BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByVl // that of the `allow_to_float` property of the corresponding network attachment. AllowInterfaceToFloat *bool `json:"allow_interface_to_float,omitempty"` - // - `vlan`: a virtual device, used through a `pci` device that has the `vlan` in its array - // of `allowed_vlans`. - // - Must use an IEEE 802.1Q tag. - // - Has its own security groups and does not inherit those of the PCI device through - // which traffic flows. - // - Not supported on bare metal servers with a `cpu.architecture` of `s390x`. InterfaceType *string `json:"interface_type" validate:"required"` // The VLAN ID used in the IEEE 802.1Q tag present in all traffic on this interface. @@ -109486,12 +112381,6 @@ type BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByVl } // Constants associated with the BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByVlanPrototype.InterfaceType property. -// - `vlan`: a virtual device, used through a `pci` device that has the `vlan` in its array -// of `allowed_vlans`. -// - Must use an IEEE 802.1Q tag. -// - Has its own security groups and does not inherit those of the PCI device through -// which traffic flows. -// - Not supported on bare metal servers with a `cpu.architecture` of `s390x`. const ( BareMetalServerNetworkInterfacePrototypeBareMetalServerNetworkInterfaceByVlanPrototypeInterfaceTypeVlanConst = "vlan" ) @@ -109578,22 +112467,10 @@ type BareMetalServerPrimaryNetworkAttachmentPrototypeBareMetalServerPrimaryNetwo // The VLAN IDs to allow for `vlan` attachments using this PCI attachment. AllowedVlans []int64 `json:"allowed_vlans,omitempty"` - // - `pci`: a physical PCI device which can only be created or deleted when the bare metal - // server is stopped - // - Has an `allowed_vlans` property which controls the VLANs that will be permitted - // to use the PCI attachment - // - Cannot directly use an IEEE 802.1Q tag. - // - Not supported on bare metal servers with a `cpu.architecture` of `s390x`. InterfaceType *string `json:"interface_type,omitempty"` } // Constants associated with the BareMetalServerPrimaryNetworkAttachmentPrototypeBareMetalServerPrimaryNetworkAttachmentByPciPrototype.InterfaceType property. -// - `pci`: a physical PCI device which can only be created or deleted when the bare metal -// server is stopped -// - Has an `allowed_vlans` property which controls the VLANs that will be permitted -// to use the PCI attachment -// - Cannot directly use an IEEE 802.1Q tag. -// - Not supported on bare metal servers with a `cpu.architecture` of `s390x`. const ( BareMetalServerPrimaryNetworkAttachmentPrototypeBareMetalServerPrimaryNetworkAttachmentByPciPrototypeInterfaceTypePciConst = "pci" ) @@ -110914,6 +113791,8 @@ type BareMetalServerPrototypeBareMetalServerByNetworkAttachment struct { Initialization *BareMetalServerInitializationPrototype `json:"initialization" validate:"required"` + MetadataService *BareMetalServerMetadataServicePrototype `json:"metadata_service,omitempty"` + // The name for this bare metal server. The name must not be used by another bare metal server in the region. If // unspecified, the name will be a hyphenated list of randomly-selected words. // @@ -110983,6 +113862,11 @@ func UnmarshalBareMetalServerPrototypeBareMetalServerByNetworkAttachment(m map[s err = core.SDKErrorf(err, "", "initialization-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "metadata_service", &obj.MetadataService, UnmarshalBareMetalServerMetadataServicePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "metadata_service-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) @@ -111046,6 +113930,8 @@ type BareMetalServerPrototypeBareMetalServerByNetworkInterface struct { Initialization *BareMetalServerInitializationPrototype `json:"initialization" validate:"required"` + MetadataService *BareMetalServerMetadataServicePrototype `json:"metadata_service,omitempty"` + // The name for this bare metal server. The name must not be used by another bare metal server in the region. If // unspecified, the name will be a hyphenated list of randomly-selected words. // @@ -111115,6 +114001,11 @@ func UnmarshalBareMetalServerPrototypeBareMetalServerByNetworkInterface(m map[st err = core.SDKErrorf(err, "", "initialization-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "metadata_service", &obj.MetadataService, UnmarshalBareMetalServerMetadataServicePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "metadata_service-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { err = core.SDKErrorf(err, "", "name-error", common.GetComponentInfo()) @@ -114848,6 +117739,10 @@ func UnmarshalImageIdentityByID(m map[string]json.RawMessage, result interface{} // ImagePrototypeImageByFile : ImagePrototypeImageByFile struct // This model "extends" ImagePrototype type ImagePrototypeImageByFile struct { + // The usage constraints to match against the requested instance or bare metal server properties to determine + // compatibility. + AllowedUse *ImageAllowedUsePrototype `json:"allowed_use,omitempty"` + // The deprecation date and time to set for this image. // // The date and time must not be in the past, and must be earlier than `obsolescence_at` @@ -114924,6 +117819,11 @@ func (*ImagePrototypeImageByFile) isaImagePrototype() bool { // UnmarshalImagePrototypeImageByFile unmarshals an instance of ImagePrototypeImageByFile from the specified map of raw messages. func UnmarshalImagePrototypeImageByFile(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ImagePrototypeImageByFile) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalImageAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "deprecation_at", &obj.DeprecationAt) if err != nil { err = core.SDKErrorf(err, "", "deprecation_at-error", common.GetComponentInfo()) @@ -114971,6 +117871,10 @@ func UnmarshalImagePrototypeImageByFile(m map[string]json.RawMessage, result int // ImagePrototypeImageBySourceVolume : ImagePrototypeImageBySourceVolume struct // This model "extends" ImagePrototype type ImagePrototypeImageBySourceVolume struct { + // The usage constraints to match against the requested instance or bare metal server properties to determine + // compatibility. + AllowedUse *ImageAllowedUsePrototype `json:"allowed_use,omitempty"` + // The deprecation date and time to set for this image. // // The date and time must not be in the past, and must be earlier than `obsolescence_at` @@ -115034,6 +117938,11 @@ func (*ImagePrototypeImageBySourceVolume) isaImagePrototype() bool { // UnmarshalImagePrototypeImageBySourceVolume unmarshals an instance of ImagePrototypeImageBySourceVolume from the specified map of raw messages. func UnmarshalImagePrototypeImageBySourceVolume(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ImagePrototypeImageBySourceVolume) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalImageAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "deprecation_at", &obj.DeprecationAt) if err != nil { err = core.SDKErrorf(err, "", "deprecation_at-error", common.GetComponentInfo()) @@ -116322,9 +119231,9 @@ type InstanceNetworkAttachmentPrototypeVirtualNetworkInterfaceVirtualNetworkInte // `bare_metal_server_network_attachment`. EnableInfrastructureNat *bool `json:"enable_infrastructure_nat,omitempty"` - // Additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP identity, or - // a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be in the - // primary IP's subnet. + // The additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP + // identity, or a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be + // in the primary IP's subnet. // // If reserved IP identities are provided, the specified reserved IPs must be unbound. // @@ -118671,6 +121580,80 @@ func UnmarshalInstanceProfileVcpuFixed(m map[string]json.RawMessage, result inte return } +// InstanceProfileVcpuManufacturerDependent : The VCPU Manufacturer for an instance with this profile depends on its configuration. +// This model "extends" InstanceProfileVcpuManufacturer +type InstanceProfileVcpuManufacturerDependent struct { + // The type for this profile field. + Type *string `json:"type" validate:"required"` +} + +// Constants associated with the InstanceProfileVcpuManufacturerDependent.Type property. +// The type for this profile field. +const ( + InstanceProfileVcpuManufacturerDependentTypeDependentConst = "dependent" +) + +func (*InstanceProfileVcpuManufacturerDependent) isaInstanceProfileVcpuManufacturer() bool { + return true +} + +// UnmarshalInstanceProfileVcpuManufacturerDependent unmarshals an instance of InstanceProfileVcpuManufacturerDependent from the specified map of raw messages. +func UnmarshalInstanceProfileVcpuManufacturerDependent(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(InstanceProfileVcpuManufacturerDependent) + err = core.UnmarshalPrimitive(m, "type", &obj.Type) + if err != nil { + err = core.SDKErrorf(err, "", "type-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// InstanceProfileVcpuManufacturerFixed : InstanceProfileVcpuManufacturerFixed struct +// This model "extends" InstanceProfileVcpuManufacturer +type InstanceProfileVcpuManufacturerFixed struct { + // The type for this profile field. + Type *string `json:"type" validate:"required"` + + // The VCPU manufacturer for an instance with this profile. + Value *string `json:"value" validate:"required"` +} + +// Constants associated with the InstanceProfileVcpuManufacturerFixed.Type property. +// The type for this profile field. +const ( + InstanceProfileVcpuManufacturerFixedTypeFixedConst = "fixed" +) + +// Constants associated with the InstanceProfileVcpuManufacturerFixed.Value property. +// The VCPU manufacturer for an instance with this profile. +const ( + InstanceProfileVcpuManufacturerFixedValueAmdConst = "amd" + InstanceProfileVcpuManufacturerFixedValueIBMConst = "ibm" + InstanceProfileVcpuManufacturerFixedValueIntelConst = "intel" +) + +func (*InstanceProfileVcpuManufacturerFixed) isaInstanceProfileVcpuManufacturer() bool { + return true +} + +// UnmarshalInstanceProfileVcpuManufacturerFixed unmarshals an instance of InstanceProfileVcpuManufacturerFixed from the specified map of raw messages. +func UnmarshalInstanceProfileVcpuManufacturerFixed(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(InstanceProfileVcpuManufacturerFixed) + err = core.UnmarshalPrimitive(m, "type", &obj.Type) + if err != nil { + err = core.SDKErrorf(err, "", "type-error", common.GetComponentInfo()) + return + } + err = core.UnmarshalPrimitive(m, "value", &obj.Value) + if err != nil { + err = core.SDKErrorf(err, "", "value-error", common.GetComponentInfo()) + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + // InstanceProfileVcpuRange : The permitted range for VCPU count for an instance with this profile. // This model "extends" InstanceProfileVcpu type InstanceProfileVcpuRange struct { @@ -118913,7 +121896,6 @@ func UnmarshalInstanceProfileVolumeBandwidthRange(m map[string]json.RawMessage, // - InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstanceByNetworkInterface // This model "extends" InstancePrototype type InstancePrototypeInstanceByCatalogOffering struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -118960,9 +121942,6 @@ type InstancePrototypeInstanceByCatalogOffering struct { // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -118979,8 +121958,8 @@ type InstancePrototypeInstanceByCatalogOffering struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -119173,7 +122152,6 @@ func UnmarshalInstancePrototypeInstanceByCatalogOffering(m map[string]json.RawMe // - InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkInterface // This model "extends" InstancePrototype type InstancePrototypeInstanceByImage struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -119220,9 +122198,6 @@ type InstancePrototypeInstanceByImage struct { // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -119239,8 +122214,8 @@ type InstancePrototypeInstanceByImage struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -119425,7 +122400,6 @@ func UnmarshalInstancePrototypeInstanceByImage(m map[string]json.RawMessage, res // - InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceByNetworkInterface // This model "extends" InstancePrototype type InstancePrototypeInstanceBySourceSnapshot struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -119472,9 +122446,6 @@ type InstancePrototypeInstanceBySourceSnapshot struct { // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -119491,8 +122462,8 @@ type InstancePrototypeInstanceBySourceSnapshot struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -119672,7 +122643,6 @@ func UnmarshalInstancePrototypeInstanceBySourceSnapshot(m map[string]json.RawMes // `primary_network_interface` is specified in the source template. // This model "extends" InstancePrototype type InstancePrototypeInstanceBySourceTemplate struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -119719,9 +122689,6 @@ type InstancePrototypeInstanceBySourceTemplate struct { // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -119738,8 +122705,8 @@ type InstancePrototypeInstanceBySourceTemplate struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -119951,7 +122918,6 @@ func UnmarshalInstancePrototypeInstanceBySourceTemplate(m map[string]json.RawMes // - InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkInterface // This model "extends" InstancePrototype type InstancePrototypeInstanceByVolume struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -119998,9 +122964,6 @@ type InstancePrototypeInstanceByVolume struct { // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -120017,8 +122980,8 @@ type InstancePrototypeInstanceByVolume struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -120330,7 +123293,6 @@ func (instanceTemplateIdentityByID *InstanceTemplateIdentityByID) asPatch() (_pa // - InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateByCatalogOfferingInstanceByNetworkInterface // This model "extends" InstanceTemplatePrototype type InstanceTemplatePrototypeInstanceTemplateByCatalogOffering struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -120375,9 +123337,6 @@ type InstanceTemplatePrototypeInstanceTemplateByCatalogOffering struct { // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -120394,8 +123353,8 @@ type InstanceTemplatePrototypeInstanceTemplateByCatalogOffering struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -120588,7 +123547,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateByCatalogOffering(m map[s // - InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInstanceByNetworkInterface // This model "extends" InstanceTemplatePrototype type InstanceTemplatePrototypeInstanceTemplateByImage struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -120633,9 +123591,6 @@ type InstanceTemplatePrototypeInstanceTemplateByImage struct { // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -120652,8 +123607,8 @@ type InstanceTemplatePrototypeInstanceTemplateByImage struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -120838,7 +123793,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateByImage(m map[string]json // - InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBySourceSnapshotInstanceByNetworkInterface // This model "extends" InstanceTemplatePrototype type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshot struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -120883,9 +123837,6 @@ type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshot struct { // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -120902,8 +123853,8 @@ type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshot struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -121083,7 +124034,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateBySourceSnapshot(m map[st // `primary_network_interface` is specified in the source template. // This model "extends" InstanceTemplatePrototype type InstanceTemplatePrototypeInstanceTemplateBySourceTemplate struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -121128,9 +124078,6 @@ type InstanceTemplatePrototypeInstanceTemplateBySourceTemplate struct { // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -121147,8 +124094,8 @@ type InstanceTemplatePrototypeInstanceTemplateBySourceTemplate struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -121360,7 +124307,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateBySourceTemplate(m map[st // - InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByCatalogOfferingInstanceTemplateContextInstanceByNetworkInterface // This model "extends" InstanceTemplate type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContext struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -121416,9 +124362,6 @@ type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContext struct { // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -121436,8 +124379,8 @@ type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContext struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -121648,7 +124591,6 @@ func UnmarshalInstanceTemplateInstanceByCatalogOfferingInstanceTemplateContext(m // - InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstanceTemplateContextInstanceByNetworkInterface // This model "extends" InstanceTemplate type InstanceTemplateInstanceByImageInstanceTemplateContext struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -121704,9 +124646,6 @@ type InstanceTemplateInstanceByImageInstanceTemplateContext struct { // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -121724,8 +124663,8 @@ type InstanceTemplateInstanceByImageInstanceTemplateContext struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -121930,7 +124869,6 @@ func UnmarshalInstanceTemplateInstanceByImageInstanceTemplateContext(m map[strin // - InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySourceSnapshotInstanceTemplateContextInstanceByNetworkInterface // This model "extends" InstanceTemplate type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContext struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -121986,9 +124924,6 @@ type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContext struct { // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -122006,8 +124941,8 @@ type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContext struct { // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -122236,8 +125171,11 @@ func UnmarshalKeyIdentityByCRN(m map[string]json.RawMessage, result interface{}) // KeyIdentityByFingerprint : KeyIdentityByFingerprint struct // This model "extends" KeyIdentity type KeyIdentityByFingerprint struct { - // The fingerprint for this key. The value is returned base64-encoded and prefixed with the hash algorithm (always + // The fingerprint for this key. The value is returned base64-encoded and prefixed with the hash algorithm (such as // `SHA256`). + // + // The length of this property may + // [expand](https://cloud.ibm.com/apidocs/vpc#property-value-expansion) in the future. Fingerprint *string `json:"fingerprint" validate:"required"` } @@ -125147,7 +128085,7 @@ type NetworkACLRuleItemNetworkACLRuleProtocolAll struct { // The source IP address or CIDR block to match. The CIDR block `0.0.0.0/0` matches all source addresses. Source *string `json:"source" validate:"required"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` } @@ -125172,7 +128110,7 @@ const ( ) // Constants associated with the NetworkACLRuleItemNetworkACLRuleProtocolAll.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRuleItemNetworkACLRuleProtocolAllProtocolAllConst = "all" ) @@ -125282,7 +128220,7 @@ type NetworkACLRuleItemNetworkACLRuleProtocolIcmp struct { // If absent, all codes are matched. Code *int64 `json:"code,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The ICMP traffic type to match. @@ -125312,7 +128250,7 @@ const ( ) // Constants associated with the NetworkACLRuleItemNetworkACLRuleProtocolIcmp.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRuleItemNetworkACLRuleProtocolIcmpProtocolIcmpConst = "icmp" ) @@ -125393,7 +128331,7 @@ func UnmarshalNetworkACLRuleItemNetworkACLRuleProtocolIcmp(m map[string]json.Raw return } -// NetworkACLRuleItemNetworkACLRuleProtocolTcpudp : NetworkACLRuleItemNetworkACLRuleProtocolTcpudp struct +// NetworkACLRuleItemNetworkACLRuleProtocolTcpudp : A rule for TCP or UDP traffic. // This model "extends" NetworkACLRuleItem type NetworkACLRuleItemNetworkACLRuleProtocolTcpudp struct { // The action to perform for a packet matching the rule. @@ -125433,7 +128371,7 @@ type NetworkACLRuleItemNetworkACLRuleProtocolTcpudp struct { // The inclusive lower bound of the TCP or UDP destination port range. DestinationPortMin *int64 `json:"destination_port_min" validate:"required"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The inclusive upper bound of the TCP or UDP source port range. @@ -125464,7 +128402,7 @@ const ( ) // Constants associated with the NetworkACLRuleItemNetworkACLRuleProtocolTcpudp.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRuleItemNetworkACLRuleProtocolTcpudpProtocolTCPConst = "tcp" NetworkACLRuleItemNetworkACLRuleProtocolTcpudpProtocolUDPConst = "udp" @@ -125578,7 +128516,7 @@ type NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolAllPrototype // The source IP address or CIDR block to match. The CIDR block `0.0.0.0/0` matches all source addresses. Source *string `json:"source" validate:"required"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` } @@ -125603,7 +128541,7 @@ const ( ) // Constants associated with the NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolAllPrototype.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolAllPrototypeProtocolAllConst = "all" ) @@ -125697,7 +128635,7 @@ type NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolIcmpPrototype // If specified, `type` must also be specified. If unspecified, all codes are matched. Code *int64 `json:"code,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The ICMP traffic type to match. @@ -125727,7 +128665,7 @@ const ( ) // Constants associated with the NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolIcmpPrototype.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolIcmpPrototypeProtocolIcmpConst = "icmp" ) @@ -125838,7 +128776,7 @@ type NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolTcpudpPrototy // `destination_port_max` must also be unspecified, allowing traffic for all destination ports. DestinationPortMin *int64 `json:"destination_port_min,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The inclusive upper bound of the TCP or UDP source port range. @@ -125875,7 +128813,7 @@ const ( ) // Constants associated with the NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolTcpudpPrototype.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolTcpudpPrototypeProtocolTCPConst = "tcp" NetworkACLRulePrototypeNetworkACLContextNetworkACLRuleProtocolTcpudpPrototypeProtocolUDPConst = "udp" @@ -125987,7 +128925,7 @@ type NetworkACLRulePrototypeNetworkACLRuleProtocolAllPrototype struct { // The source IP address or CIDR block to match. The CIDR block `0.0.0.0/0` matches all source addresses. Source *string `json:"source" validate:"required"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` } @@ -126012,7 +128950,7 @@ const ( ) // Constants associated with the NetworkACLRulePrototypeNetworkACLRuleProtocolAllPrototype.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRulePrototypeNetworkACLRuleProtocolAllPrototypeProtocolAllConst = "all" ) @@ -126113,7 +129051,7 @@ type NetworkACLRulePrototypeNetworkACLRuleProtocolIcmpPrototype struct { // If specified, `type` must also be specified. If unspecified, all codes are matched. Code *int64 `json:"code,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The ICMP traffic type to match. @@ -126143,7 +129081,7 @@ const ( ) // Constants associated with the NetworkACLRulePrototypeNetworkACLRuleProtocolIcmpPrototype.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRulePrototypeNetworkACLRuleProtocolIcmpPrototypeProtocolIcmpConst = "icmp" ) @@ -126261,7 +129199,7 @@ type NetworkACLRulePrototypeNetworkACLRuleProtocolTcpudpPrototype struct { // `destination_port_max` must also be unspecified, allowing traffic for all destination ports. DestinationPortMin *int64 `json:"destination_port_min,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The inclusive upper bound of the TCP or UDP source port range. @@ -126298,7 +129236,7 @@ const ( ) // Constants associated with the NetworkACLRulePrototypeNetworkACLRuleProtocolTcpudpPrototype.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRulePrototypeNetworkACLRuleProtocolTcpudpPrototypeProtocolTCPConst = "tcp" NetworkACLRulePrototypeNetworkACLRuleProtocolTcpudpPrototypeProtocolUDPConst = "udp" @@ -126424,7 +129362,7 @@ type NetworkACLRuleNetworkACLRuleProtocolAll struct { // The source IP address or CIDR block to match. The CIDR block `0.0.0.0/0` matches all source addresses. Source *string `json:"source" validate:"required"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` } @@ -126449,7 +129387,7 @@ const ( ) // Constants associated with the NetworkACLRuleNetworkACLRuleProtocolAll.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRuleNetworkACLRuleProtocolAllProtocolAllConst = "all" ) @@ -126558,7 +129496,7 @@ type NetworkACLRuleNetworkACLRuleProtocolIcmp struct { // If absent, all codes are matched. Code *int64 `json:"code,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The ICMP traffic type to match. @@ -126588,7 +129526,7 @@ const ( ) // Constants associated with the NetworkACLRuleNetworkACLRuleProtocolIcmp.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRuleNetworkACLRuleProtocolIcmpProtocolIcmpConst = "icmp" ) @@ -126669,7 +129607,7 @@ func UnmarshalNetworkACLRuleNetworkACLRuleProtocolIcmp(m map[string]json.RawMess return } -// NetworkACLRuleNetworkACLRuleProtocolTcpudp : NetworkACLRuleNetworkACLRuleProtocolTcpudp struct +// NetworkACLRuleNetworkACLRuleProtocolTcpudp : A rule for TCP or UDP traffic. // This model "extends" NetworkACLRule type NetworkACLRuleNetworkACLRuleProtocolTcpudp struct { // The action to perform for a packet matching the rule. @@ -126708,7 +129646,7 @@ type NetworkACLRuleNetworkACLRuleProtocolTcpudp struct { // The inclusive lower bound of the TCP or UDP destination port range. DestinationPortMin *int64 `json:"destination_port_min" validate:"required"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The inclusive upper bound of the TCP or UDP source port range. @@ -126739,7 +129677,7 @@ const ( ) // Constants associated with the NetworkACLRuleNetworkACLRuleProtocolTcpudp.Protocol property. -// The name of the network protocol. +// The network protocol. const ( NetworkACLRuleNetworkACLRuleProtocolTcpudpProtocolTCPConst = "tcp" NetworkACLRuleNetworkACLRuleProtocolTcpudpProtocolUDPConst = "udp" @@ -129064,7 +132002,7 @@ type SecurityGroupRulePrototypeSecurityGroupRuleProtocolAll struct { Remote SecurityGroupRuleRemotePrototypeIntf `json:"remote,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` } @@ -129086,7 +132024,7 @@ const ( ) // Constants associated with the SecurityGroupRulePrototypeSecurityGroupRuleProtocolAll.Protocol property. -// The name of the network protocol. +// The network protocol. const ( SecurityGroupRulePrototypeSecurityGroupRuleProtocolAllProtocolAllConst = "all" ) @@ -129162,7 +132100,7 @@ type SecurityGroupRulePrototypeSecurityGroupRuleProtocolIcmp struct { // If specified, `type` must also be specified. If unspecified, all codes are allowed. Code *int64 `json:"code,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The ICMP traffic type to allow. @@ -129189,7 +132127,7 @@ const ( ) // Constants associated with the SecurityGroupRulePrototypeSecurityGroupRuleProtocolIcmp.Protocol property. -// The name of the network protocol. +// The network protocol. const ( SecurityGroupRulePrototypeSecurityGroupRuleProtocolIcmpProtocolIcmpConst = "icmp" ) @@ -129282,7 +132220,7 @@ type SecurityGroupRulePrototypeSecurityGroupRuleProtocolTcpudp struct { // unspecified, allowing traffic on all destination ports. PortMin *int64 `json:"port_min,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` } @@ -129304,7 +132242,7 @@ const ( ) // Constants associated with the SecurityGroupRulePrototypeSecurityGroupRuleProtocolTcpudp.Protocol property. -// The name of the network protocol. +// The network protocol. const ( SecurityGroupRulePrototypeSecurityGroupRuleProtocolTcpudpProtocolTCPConst = "tcp" SecurityGroupRulePrototypeSecurityGroupRuleProtocolTcpudpProtocolUDPConst = "udp" @@ -129792,7 +132730,7 @@ type SecurityGroupRuleSecurityGroupRuleProtocolAll struct { Remote SecurityGroupRuleRemoteIntf `json:"remote" validate:"required"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` } @@ -129814,7 +132752,7 @@ const ( ) // Constants associated with the SecurityGroupRuleSecurityGroupRuleProtocolAll.Protocol property. -// The name of the network protocol. +// The network protocol. const ( SecurityGroupRuleSecurityGroupRuleProtocolAllProtocolAllConst = "all" ) @@ -129891,7 +132829,7 @@ type SecurityGroupRuleSecurityGroupRuleProtocolIcmp struct { // The ICMP traffic code to allow. If absent, all codes are allowed. Code *int64 `json:"code,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` // The ICMP traffic type to allow. If absent, all types are allowed. @@ -129916,7 +132854,7 @@ const ( ) // Constants associated with the SecurityGroupRuleSecurityGroupRuleProtocolIcmp.Protocol property. -// The name of the network protocol. +// The network protocol. const ( SecurityGroupRuleSecurityGroupRuleProtocolIcmpProtocolIcmpConst = "icmp" ) @@ -130009,7 +132947,7 @@ type SecurityGroupRuleSecurityGroupRuleProtocolTcpudp struct { // The inclusive lower bound of the TCP or UDP destination port range. PortMin *int64 `json:"port_min,omitempty"` - // The name of the network protocol. + // The network protocol. Protocol *string `json:"protocol" validate:"required"` } @@ -130031,7 +132969,7 @@ const ( ) // Constants associated with the SecurityGroupRuleSecurityGroupRuleProtocolTcpudp.Protocol property. -// The name of the network protocol. +// The network protocol. const ( SecurityGroupRuleSecurityGroupRuleProtocolTcpudpProtocolTCPConst = "tcp" SecurityGroupRuleSecurityGroupRuleProtocolTcpudpProtocolUDPConst = "udp" @@ -130982,9 +133920,9 @@ type ShareMountTargetVirtualNetworkInterfacePrototypeVirtualNetworkInterfaceProt // `bare_metal_server_network_attachment`. EnableInfrastructureNat *bool `json:"enable_infrastructure_nat,omitempty"` - // Additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP identity, or - // a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be in the - // primary IP's subnet. + // The additional IP addresses to bind to the virtual network interface. Each item may be either a reserved IP + // identity, or a reserved IP prototype object which will be used to create a new reserved IP. All IP addresses must be + // in the primary IP's subnet. // // If reserved IP identities are provided, the specified reserved IPs must be unbound. // @@ -131636,7 +134574,7 @@ type SharePrototypeShareByOriginShare struct { ReplicaShare *SharePrototypeShareContext `json:"replica_share,omitempty"` - // Tags for this resource. + // The tags for this resource. UserTags []string `json:"user_tags,omitempty"` // The origin share for the accessor share. The origin share must have an @@ -131645,6 +134583,10 @@ type SharePrototypeShareByOriginShare struct { // // The specified share may be in a different account, subject to IAM policies. OriginShare ShareIdentityIntf `json:"origin_share" validate:"required"` + + // The resource group to use. If unspecified, the resource group from + // the origin share will be used. + ResourceGroup ResourceGroupIdentityIntf `json:"resource_group,omitempty"` } // Constants associated with the SharePrototypeShareByOriginShare.AllowedTransitEncryptionModes property. @@ -131702,6 +134644,11 @@ func UnmarshalSharePrototypeShareByOriginShare(m map[string]json.RawMessage, res err = core.SDKErrorf(err, "", "origin_share-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "resource_group", &obj.ResourceGroup, UnmarshalResourceGroupIdentity) + if err != nil { + err = core.SDKErrorf(err, "", "resource_group-error", common.GetComponentInfo()) + return + } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } @@ -131724,7 +134671,7 @@ type SharePrototypeShareBySize struct { ReplicaShare *SharePrototypeShareContext `json:"replica_share,omitempty"` - // Tags for this resource. + // The tags for this resource. UserTags []string `json:"user_tags,omitempty"` // The access control mode for the share: @@ -131766,8 +134713,6 @@ type SharePrototypeShareBySize struct { // // The specified value must be within the permitted `capacity` range of the share's profile and supported by the // share's specified IOPS. - // - // The maximum size for a share may increase in the future. Size *int64 `json:"size" validate:"required"` // The zone this file share will reside in. For a replica share in the same region as @@ -131903,7 +134848,7 @@ type SharePrototypeShareBySourceShare struct { ReplicaShare *SharePrototypeShareContext `json:"replica_share,omitempty"` - // Tags for this resource. + // The tags for this resource. UserTags []string `json:"user_tags,omitempty"` // The root key to use to wrap the data encryption key for the share. @@ -132058,7 +135003,7 @@ type SharePrototypeShareBySourceSnapshot struct { ReplicaShare *SharePrototypeShareContext `json:"replica_share,omitempty"` - // Tags for this resource. + // The tags for this resource. UserTags []string `json:"user_tags,omitempty"` // The root key to use to wrap the data encryption key for the share. @@ -132093,7 +135038,7 @@ type SharePrototypeShareBySourceSnapshot struct { // If unspecified, the source snapshot's `minimum_size` will be used. Size *int64 `json:"size,omitempty"` - // The source snapshot for this file share. + // The source snapshot to clone this file share from. // // This file share will reside in the same zone as the specified source snapshot. // The snapshot must have the `lifecycle_state` as `stable` and `status` as `available` @@ -132327,8 +135272,9 @@ type SnapshotConsistencyGroupPrototypeSnapshotConsistencyGroupBySnapshots struct ResourceGroup ResourceGroupIdentityIntf `json:"resource_group,omitempty"` - // The data-consistent member snapshots to create. All snapshots must specify a - // `source_volume` attached to the same virtual server instance. + // The data-consistent member snapshots to create. Each snapshot must specify a + // `source_volume` attached to the same virtual server instance, and all source volumes must have a + // `storage_generation` value of `1`. Snapshots []SnapshotPrototypeSnapshotConsistencyGroupContext `json:"snapshots" validate:"required"` } @@ -132483,7 +135429,13 @@ func UnmarshalSnapshotIdentityByID(m map[string]json.RawMessage, result interfac // SnapshotPrototypeSnapshotBySourceSnapshot : SnapshotPrototypeSnapshotBySourceSnapshot struct // This model "extends" SnapshotPrototype type SnapshotPrototypeSnapshotBySourceSnapshot struct { - // Clones to create for this snapshot. + // The usage constraints to match against the requested instance or bare metal server properties to determine + // compatibility. + // + // Can only be specified for bootable snapshots. + AllowedUse *SnapshotAllowedUsePrototype `json:"allowed_use,omitempty"` + + // The clones to create for this snapshot. Clones []SnapshotClonePrototype `json:"clones,omitempty"` // The name for this snapshot. The name must not be used by another snapshot in the region. If unspecified, the name @@ -132530,6 +135482,11 @@ func (*SnapshotPrototypeSnapshotBySourceSnapshot) isaSnapshotPrototype() bool { // UnmarshalSnapshotPrototypeSnapshotBySourceSnapshot unmarshals an instance of SnapshotPrototypeSnapshotBySourceSnapshot from the specified map of raw messages. func UnmarshalSnapshotPrototypeSnapshotBySourceSnapshot(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SnapshotPrototypeSnapshotBySourceSnapshot) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalSnapshotAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "clones", &obj.Clones, UnmarshalSnapshotClonePrototype) if err != nil { err = core.SDKErrorf(err, "", "clones-error", common.GetComponentInfo()) @@ -132567,7 +135524,13 @@ func UnmarshalSnapshotPrototypeSnapshotBySourceSnapshot(m map[string]json.RawMes // SnapshotPrototypeSnapshotBySourceVolume : SnapshotPrototypeSnapshotBySourceVolume struct // This model "extends" SnapshotPrototype type SnapshotPrototypeSnapshotBySourceVolume struct { - // Clones to create for this snapshot. + // The usage constraints to match against the requested instance or bare metal server properties to determine + // compatibility. + // + // Can only be specified for bootable snapshots. + AllowedUse *SnapshotAllowedUsePrototype `json:"allowed_use,omitempty"` + + // The clones to create for this snapshot. Clones []SnapshotClonePrototype `json:"clones,omitempty"` // The name for this snapshot. The name must not be used by another snapshot in the region. If unspecified, the name @@ -132602,6 +135565,11 @@ func (*SnapshotPrototypeSnapshotBySourceVolume) isaSnapshotPrototype() bool { // UnmarshalSnapshotPrototypeSnapshotBySourceVolume unmarshals an instance of SnapshotPrototypeSnapshotBySourceVolume from the specified map of raw messages. func UnmarshalSnapshotPrototypeSnapshotBySourceVolume(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SnapshotPrototypeSnapshotBySourceVolume) + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalSnapshotAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "clones", &obj.Clones, UnmarshalSnapshotClonePrototype) if err != nil { err = core.SDKErrorf(err, "", "clones-error", common.GetComponentInfo()) @@ -133669,6 +136637,16 @@ func UnmarshalVPCIdentityByCRN(m map[string]json.RawMessage, result interface{}) return } +// asPatch returns a generic map representation of the VPCIdentityByCRN +func (vpcIdentityByCRN *VPCIdentityByCRN) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(vpcIdentityByCRN.CRN) { + _patch["crn"] = vpcIdentityByCRN.CRN + } + + return +} + // VPCIdentityByHref : VPCIdentityByHref struct // This model "extends" VPCIdentity type VPCIdentityByHref struct { @@ -133704,6 +136682,16 @@ func UnmarshalVPCIdentityByHref(m map[string]json.RawMessage, result interface{} return } +// asPatch returns a generic map representation of the VPCIdentityByHref +func (vpcIdentityByHref *VPCIdentityByHref) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(vpcIdentityByHref.Href) { + _patch["href"] = vpcIdentityByHref.Href + } + + return +} + // VPCIdentityByID : VPCIdentityByID struct // This model "extends" VPCIdentity type VPCIdentityByID struct { @@ -133739,6 +136727,16 @@ func UnmarshalVPCIdentityByID(m map[string]json.RawMessage, result interface{}) return } +// asPatch returns a generic map representation of the VPCIdentityByID +func (vpcIdentityByID *VPCIdentityByID) asPatch() (_patch map[string]interface{}) { + _patch = map[string]interface{}{} + if !core.IsNil(vpcIdentityByID.ID) { + _patch["id"] = vpcIdentityByID.ID + } + + return +} + // VPNGatewayConnectionIkeIdentityPrototypeVPNGatewayConnectionIkeIdentityFqdn : VPNGatewayConnectionIkeIdentityPrototypeVPNGatewayConnectionIkeIdentityFqdn struct // This model "extends" VPNGatewayConnectionIkeIdentityPrototype type VPNGatewayConnectionIkeIdentityPrototypeVPNGatewayConnectionIkeIdentityFqdn struct { @@ -135151,7 +138149,7 @@ type VPNGatewayConnectionPrototypeVPNGatewayConnectionStaticRouteModePrototype s Peer VPNGatewayConnectionStaticRouteModePeerPrototypeIntf `json:"peer" validate:"required"` - // Routing protocols are disabled for this VPN gateway connection. + // The routing protocol for this VPN gateway connection. RoutingProtocol *string `json:"routing_protocol,omitempty"` } @@ -135169,7 +138167,7 @@ const ( ) // Constants associated with the VPNGatewayConnectionPrototypeVPNGatewayConnectionStaticRouteModePrototype.RoutingProtocol property. -// Routing protocols are disabled for this VPN gateway connection. +// The routing protocol for this VPN gateway connection. const ( VPNGatewayConnectionPrototypeVPNGatewayConnectionStaticRouteModePrototypeRoutingProtocolNoneConst = "none" ) @@ -135325,7 +138323,7 @@ type VPNGatewayConnectionRouteMode struct { Peer VPNGatewayConnectionStaticRouteModePeerIntf `json:"peer,omitempty"` - // Routing protocols are disabled for this VPN gateway connection. + // The routing protocol for this VPN gateway connection. RoutingProtocol *string `json:"routing_protocol,omitempty"` // The VPN tunnel configuration for this VPN gateway connection (in static route mode). @@ -135378,7 +138376,7 @@ const ( ) // Constants associated with the VPNGatewayConnectionRouteMode.RoutingProtocol property. -// Routing protocols are disabled for this VPN gateway connection. +// The routing protocol for this VPN gateway connection. const ( VPNGatewayConnectionRouteModeRoutingProtocolNoneConst = "none" ) @@ -135611,7 +138609,7 @@ func UnmarshalVPNGatewayConnectionStaticRouteModePeerVPNGatewayConnectionPeerByF // VPNGatewayPolicyMode : VPNGatewayPolicyMode struct // This model "extends" VPNGateway type VPNGatewayPolicyMode struct { - // Connections for this VPN gateway. + // The connections for this VPN gateway. Connections []VPNGatewayConnectionReference `json:"connections" validate:"required"` // The date and time that this VPN gateway was created. @@ -135661,7 +138659,7 @@ type VPNGatewayPolicyMode struct { // The VPC this VPN gateway resides in. VPC *VPCReference `json:"vpc" validate:"required"` - // Policy mode VPN gateway. + // The mode for this VPN gateway. Mode *string `json:"mode" validate:"required"` } @@ -135699,7 +138697,7 @@ const ( ) // Constants associated with the VPNGatewayPolicyMode.Mode property. -// Policy mode VPN gateway. +// The mode for this VPN gateway. const ( VPNGatewayPolicyModeModePolicyConst = "policy" ) @@ -135806,20 +138804,21 @@ type VPNGatewayPrototypeVPNGatewayPolicyModePrototype struct { Subnet SubnetIdentityIntf `json:"subnet" validate:"required"` - // Policy mode VPN gateway. - Mode *string `json:"mode,omitempty"` + // The mode for this VPN gateway. + Mode *string `json:"mode" validate:"required"` } // Constants associated with the VPNGatewayPrototypeVPNGatewayPolicyModePrototype.Mode property. -// Policy mode VPN gateway. +// The mode for this VPN gateway. const ( VPNGatewayPrototypeVPNGatewayPolicyModePrototypeModePolicyConst = "policy" ) // NewVPNGatewayPrototypeVPNGatewayPolicyModePrototype : Instantiate VPNGatewayPrototypeVPNGatewayPolicyModePrototype (Generic Model Constructor) -func (*VpcV1) NewVPNGatewayPrototypeVPNGatewayPolicyModePrototype(subnet SubnetIdentityIntf) (_model *VPNGatewayPrototypeVPNGatewayPolicyModePrototype, err error) { +func (*VpcV1) NewVPNGatewayPrototypeVPNGatewayPolicyModePrototype(subnet SubnetIdentityIntf, mode string) (_model *VPNGatewayPrototypeVPNGatewayPolicyModePrototype, err error) { _model = &VPNGatewayPrototypeVPNGatewayPolicyModePrototype{ Subnet: subnet, + Mode: core.StringPtr(mode), } err = core.ValidateStruct(_model, "required parameters") if err != nil { @@ -135870,12 +138869,12 @@ type VPNGatewayPrototypeVPNGatewayRouteModePrototype struct { Subnet SubnetIdentityIntf `json:"subnet" validate:"required"` - // Route mode VPN gateway. + // The mode for this VPN gateway. Mode *string `json:"mode,omitempty"` } // Constants associated with the VPNGatewayPrototypeVPNGatewayRouteModePrototype.Mode property. -// Route mode VPN gateway. +// The mode for this VPN gateway. const ( VPNGatewayPrototypeVPNGatewayRouteModePrototypeModeRouteConst = "route" ) @@ -135926,7 +138925,7 @@ func UnmarshalVPNGatewayPrototypeVPNGatewayRouteModePrototype(m map[string]json. // VPNGatewayRouteMode : VPNGatewayRouteMode struct // This model "extends" VPNGateway type VPNGatewayRouteMode struct { - // Connections for this VPN gateway. + // The connections for this VPN gateway. Connections []VPNGatewayConnectionReference `json:"connections" validate:"required"` // The date and time that this VPN gateway was created. @@ -135976,7 +138975,7 @@ type VPNGatewayRouteMode struct { // The VPC this VPN gateway resides in. VPC *VPCReference `json:"vpc" validate:"required"` - // Route mode VPN gateway. + // The mode for this VPN gateway. Mode *string `json:"mode" validate:"required"` } @@ -136014,7 +139013,7 @@ const ( ) // Constants associated with the VPNGatewayRouteMode.Mode property. -// Route mode VPN gateway. +// The mode for this VPN gateway. const ( VPNGatewayRouteModeModeRouteConst = "route" ) @@ -136849,6 +139848,13 @@ type VolumeAttachmentPrototypeVolumeVolumePrototypeInstanceContext struct { // If unspecified, the `encryption` type for the volume will be `provider_managed`. EncryptionKey EncryptionKeyIdentityIntf `json:"encryption_key,omitempty"` + // The usage constraints to be matched against requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified if `source_snapshot` is bootable. If not specified, the value of + // this property will be inherited from the `source_snapshot`. + AllowedUse *VolumeAllowedUsePrototype `json:"allowed_use,omitempty"` + // The snapshot to use as a source for the volume's data. // // The specified snapshot may be in a different account, subject to IAM policies. @@ -136914,6 +139920,11 @@ func UnmarshalVolumeAttachmentPrototypeVolumeVolumePrototypeInstanceContext(m ma err = core.SDKErrorf(err, "", "encryption_key-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalModel(m, "source_snapshot", &obj.SourceSnapshot, UnmarshalSnapshotIdentity) if err != nil { err = core.SDKErrorf(err, "", "source_snapshot-error", common.GetComponentInfo()) @@ -138083,6 +141094,13 @@ type VolumePrototypeVolumeBySourceSnapshot struct { // The zone this volume will reside in. Zone ZoneIdentityIntf `json:"zone" validate:"required"` + // The usage constraints to be matched against requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified if `source_snapshot` is bootable. If not specified, the value of + // this property will be inherited from the `source_snapshot`. + AllowedUse *VolumeAllowedUsePrototype `json:"allowed_use,omitempty"` + // The capacity to use for the volume (in gigabytes). The specified value must be at least the snapshot's // `minimum_capacity`, and must be within the `capacity` range of the volume's profile. // @@ -138159,6 +141177,11 @@ func UnmarshalVolumePrototypeVolumeBySourceSnapshot(m map[string]json.RawMessage err = core.SDKErrorf(err, "", "zone-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "capacity", &obj.Capacity) if err != nil { err = core.SDKErrorf(err, "", "capacity-error", common.GetComponentInfo()) @@ -141289,7 +144312,6 @@ func UnmarshalInstancePlacementTargetPrototypePlacementGroupIdentityPlacementGro // InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstanceByNetworkAttachment : InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstanceByNetworkAttachment struct // This model "extends" InstancePrototypeInstanceByCatalogOffering type InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -141336,9 +144358,6 @@ type InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstance // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -141355,8 +144374,8 @@ type InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstance // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -141530,7 +144549,6 @@ func UnmarshalInstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferin // InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstanceByNetworkInterface : InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstanceByNetworkInterface struct // This model "extends" InstancePrototypeInstanceByCatalogOffering type InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -141577,9 +144595,6 @@ type InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstance // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -141596,8 +144611,8 @@ type InstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferingInstance // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -141771,7 +144786,6 @@ func UnmarshalInstancePrototypeInstanceByCatalogOfferingInstanceByCatalogOfferin // InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkAttachment : InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkAttachment struct // This model "extends" InstancePrototypeInstanceByImage type InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -141818,9 +144832,6 @@ type InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkAttachment // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -141837,8 +144848,8 @@ type InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkAttachment // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -142013,7 +145024,6 @@ func UnmarshalInstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkAt // InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkInterface : InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkInterface struct // This model "extends" InstancePrototypeInstanceByImage type InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -142060,9 +145070,6 @@ type InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkInterface s // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -142079,8 +145086,8 @@ type InstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkInterface s // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -142255,7 +145262,6 @@ func UnmarshalInstancePrototypeInstanceByImageInstanceByImageInstanceByNetworkIn // InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceByNetworkAttachment : InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceByNetworkAttachment struct // This model "extends" InstancePrototypeInstanceBySourceSnapshot type InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -142302,9 +145308,6 @@ type InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceBy // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -142321,8 +145324,8 @@ type InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceBy // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -142489,7 +145492,6 @@ func UnmarshalInstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotI // InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceByNetworkInterface : InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceByNetworkInterface struct // This model "extends" InstancePrototypeInstanceBySourceSnapshot type InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -142536,9 +145538,6 @@ type InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceBy // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -142555,8 +145554,8 @@ type InstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotInstanceBy // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -142723,7 +145722,6 @@ func UnmarshalInstancePrototypeInstanceBySourceSnapshotInstanceBySourceSnapshotI // InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkAttachment : InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkAttachment struct // This model "extends" InstancePrototypeInstanceByVolume type InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -142770,9 +145768,6 @@ type InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkAttachmen // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -142789,8 +145784,8 @@ type InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkAttachmen // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -142957,7 +145952,6 @@ func UnmarshalInstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetwork // InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkInterface : InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkInterface struct // This model "extends" InstancePrototypeInstanceByVolume type InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -143004,9 +145998,6 @@ type InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkInterface // The system hostname will be based on this name. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -143023,8 +146014,8 @@ type InstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetworkInterface // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -143191,7 +146182,6 @@ func UnmarshalInstancePrototypeInstanceByVolumeInstanceByVolumeInstanceByNetwork // InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateByCatalogOfferingInstanceByNetworkAttachment : InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateByCatalogOfferingInstanceByNetworkAttachment struct // This model "extends" InstanceTemplatePrototypeInstanceTemplateByCatalogOffering type InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateByCatalogOfferingInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -143236,9 +146226,6 @@ type InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateB // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -143255,8 +146242,8 @@ type InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateB // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -143430,7 +146417,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstance // InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateByCatalogOfferingInstanceByNetworkInterface : InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateByCatalogOfferingInstanceByNetworkInterface struct // This model "extends" InstanceTemplatePrototypeInstanceTemplateByCatalogOffering type InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateByCatalogOfferingInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -143475,9 +146461,6 @@ type InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateB // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -143494,8 +146477,8 @@ type InstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstanceTemplateB // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -143669,7 +146652,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateByCatalogOfferingInstance // InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInstanceByNetworkAttachment : InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInstanceByNetworkAttachment struct // This model "extends" InstanceTemplatePrototypeInstanceTemplateByImage type InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -143714,9 +146696,6 @@ type InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInst // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -143733,8 +146712,8 @@ type InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInst // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -143909,7 +146888,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateBy // InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInstanceByNetworkInterface : InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInstanceByNetworkInterface struct // This model "extends" InstanceTemplatePrototypeInstanceTemplateByImage type InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -143954,9 +146932,6 @@ type InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInst // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -143973,8 +146948,8 @@ type InstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateByImageInst // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -144149,7 +147124,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateByImageInstanceTemplateBy // InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBySourceSnapshotInstanceByNetworkAttachment : InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBySourceSnapshotInstanceByNetworkAttachment struct // This model "extends" InstanceTemplatePrototypeInstanceTemplateBySourceSnapshot type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBySourceSnapshotInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -144194,9 +147168,6 @@ type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBy // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -144213,8 +147184,8 @@ type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBy // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -144381,7 +147352,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceT // InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBySourceSnapshotInstanceByNetworkInterface : InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBySourceSnapshotInstanceByNetworkInterface struct // This model "extends" InstanceTemplatePrototypeInstanceTemplateBySourceSnapshot type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBySourceSnapshotInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -144426,9 +147396,6 @@ type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBy // unspecified, the name will be a hyphenated list of randomly-selected words. Name *string `json:"name,omitempty"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -144445,8 +147412,8 @@ type InstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceTemplateBy // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -144613,7 +147580,6 @@ func UnmarshalInstanceTemplatePrototypeInstanceTemplateBySourceSnapshotInstanceT // InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByCatalogOfferingInstanceTemplateContextInstanceByNetworkAttachment : InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByCatalogOfferingInstanceTemplateContextInstanceByNetworkAttachment struct // This model "extends" InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContext type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByCatalogOfferingInstanceTemplateContextInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -144669,9 +147635,6 @@ type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByC // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -144689,8 +147652,8 @@ type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByC // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -144870,7 +147833,6 @@ func UnmarshalInstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextIn // InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByCatalogOfferingInstanceTemplateContextInstanceByNetworkInterface : InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByCatalogOfferingInstanceTemplateContextInstanceByNetworkInterface struct // This model "extends" InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContext type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByCatalogOfferingInstanceTemplateContextInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -144926,9 +147888,6 @@ type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByC // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -144946,8 +147905,8 @@ type InstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextInstanceByC // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -145127,7 +148086,6 @@ func UnmarshalInstanceTemplateInstanceByCatalogOfferingInstanceTemplateContextIn // InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstanceTemplateContextInstanceByNetworkAttachment : InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstanceTemplateContextInstanceByNetworkAttachment struct // This model "extends" InstanceTemplateInstanceByImageInstanceTemplateContext type InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstanceTemplateContextInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -145183,9 +148141,6 @@ type InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstan // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -145203,8 +148158,8 @@ type InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstan // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -145385,7 +148340,6 @@ func UnmarshalInstanceTemplateInstanceByImageInstanceTemplateContextInstanceByIm // InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstanceTemplateContextInstanceByNetworkInterface : InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstanceTemplateContextInstanceByNetworkInterface struct // This model "extends" InstanceTemplateInstanceByImageInstanceTemplateContext type InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstanceTemplateContextInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -145441,9 +148395,6 @@ type InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstan // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -145461,8 +148412,8 @@ type InstanceTemplateInstanceByImageInstanceTemplateContextInstanceByImageInstan // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -145643,7 +148594,6 @@ func UnmarshalInstanceTemplateInstanceByImageInstanceTemplateContextInstanceByIm // InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySourceSnapshotInstanceTemplateContextInstanceByNetworkAttachment : InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySourceSnapshotInstanceTemplateContextInstanceByNetworkAttachment struct // This model "extends" InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContext type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySourceSnapshotInstanceTemplateContextInstanceByNetworkAttachment struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -145699,9 +148649,6 @@ type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySo // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -145719,8 +148666,8 @@ type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySo // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -145901,7 +148848,6 @@ func UnmarshalInstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextIns // InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySourceSnapshotInstanceTemplateContextInstanceByNetworkInterface : InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySourceSnapshotInstanceTemplateContextInstanceByNetworkInterface struct // This model "extends" InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContext type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySourceSnapshotInstanceTemplateContextInstanceByNetworkInterface struct { - // The availability policy to use for this virtual server instance. AvailabilityPolicy *InstanceAvailabilityPolicyPrototype `json:"availability_policy,omitempty"` // The cluster network attachments to create for this virtual server instance. A cluster network attachment represents @@ -145957,9 +148903,6 @@ type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySo // The name for this instance template. The name is unique across all instance templates in the region. Name *string `json:"name" validate:"required"` - // The placement restrictions to use for the virtual server instance. - // - // If specified, `reservation_affinity.policy` must be `disabled`. PlacementTarget InstancePlacementTargetPrototypeIntf `json:"placement_target,omitempty"` // The [profile](https://cloud.ibm.com/docs/vpc?topic=vpc-profiles) to use for this virtual server instance. @@ -145977,8 +148920,8 @@ type InstanceTemplateInstanceBySourceSnapshotInstanceTemplateContextInstanceBySo // `total_network_bandwidth`. TotalVolumeBandwidth *int64 `json:"total_volume_bandwidth,omitempty"` - // [User data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual server - // instance. + // The [user data](https://cloud.ibm.com/docs/vpc?topic=vpc-user-data) to make available when setting up the virtual + // server instance. UserData *string `json:"user_data,omitempty"` // The additional volume attachments to create for the virtual server instance. @@ -148366,7 +151309,7 @@ type VPNGatewayConnectionRouteModeVPNGatewayConnectionStaticRouteMode struct { Peer VPNGatewayConnectionStaticRouteModePeerIntf `json:"peer" validate:"required"` - // Routing protocols are disabled for this VPN gateway connection. + // The routing protocol for this VPN gateway connection. RoutingProtocol *string `json:"routing_protocol" validate:"required"` // The VPN tunnel configuration for this VPN gateway connection (in static route mode). @@ -148419,7 +151362,7 @@ const ( ) // Constants associated with the VPNGatewayConnectionRouteModeVPNGatewayConnectionStaticRouteMode.RoutingProtocol property. -// Routing protocols are disabled for this VPN gateway connection. +// The routing protocol for this VPN gateway connection. const ( VPNGatewayConnectionRouteModeVPNGatewayConnectionStaticRouteModeRoutingProtocolNoneConst = "none" ) @@ -148958,6 +151901,13 @@ type VolumeAttachmentPrototypeVolumeVolumePrototypeInstanceContextVolumePrototyp // The [user tags](https://cloud.ibm.com/apidocs/tagging#types-of-tags) associated with this volume. UserTags []string `json:"user_tags,omitempty"` + // The usage constraints to be matched against requested instance or bare metal server + // properties to determine compatibility. + // + // Can only be specified if `source_snapshot` is bootable. If not specified, the value of + // this property will be inherited from the `source_snapshot`. + AllowedUse *VolumeAllowedUsePrototype `json:"allowed_use,omitempty"` + // The capacity to use for the volume (in gigabytes). The specified value must be at least the snapshot's // `minimum_capacity`, and must be within the `capacity` range of the volume's profile. // @@ -149032,6 +151982,11 @@ func UnmarshalVolumeAttachmentPrototypeVolumeVolumePrototypeInstanceContextVolum err = core.SDKErrorf(err, "", "user_tags-error", common.GetComponentInfo()) return } + err = core.UnmarshalModel(m, "allowed_use", &obj.AllowedUse, UnmarshalVolumeAllowedUsePrototype) + if err != nil { + err = core.SDKErrorf(err, "", "allowed_use-error", common.GetComponentInfo()) + return + } err = core.UnmarshalPrimitive(m, "capacity", &obj.Capacity) if err != nil { err = core.SDKErrorf(err, "", "capacity-error", common.GetComponentInfo()) @@ -149289,25 +152244,25 @@ func UnmarshalInstanceGroupManagerActionPrototypeScheduledActionPrototypeByRunAt return } -// VpcsPager can be used to simplify the use of the "ListVpcs" method. -type VpcsPager struct { +// BackupPoliciesPager can be used to simplify the use of the "ListBackupPolicies" method. +type BackupPoliciesPager struct { hasNext bool - options *ListVpcsOptions + options *ListBackupPoliciesOptions client *VpcV1 pageContext struct { next *string } } -// NewVpcsPager returns a new VpcsPager instance. -func (vpc *VpcV1) NewVpcsPager(options *ListVpcsOptions) (pager *VpcsPager, err error) { +// NewBackupPoliciesPager returns a new BackupPoliciesPager instance. +func (vpc *VpcV1) NewBackupPoliciesPager(options *ListBackupPoliciesOptions) (pager *BackupPoliciesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVpcsOptions = *options - pager = &VpcsPager{ + var optionsCopy ListBackupPoliciesOptions = *options + pager = &BackupPoliciesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -149316,19 +152271,19 @@ func (vpc *VpcV1) NewVpcsPager(options *ListVpcsOptions) (pager *VpcsPager, err } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VpcsPager) HasNext() bool { +func (pager *BackupPoliciesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VpcsPager) GetNextWithContext(ctx context.Context) (page []VPC, err error) { +func (pager *BackupPoliciesPager) GetNextWithContext(ctx context.Context) (page []BackupPolicyIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVpcsWithContext(ctx, pager.options) + result, _, err := pager.client.ListBackupPoliciesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -149347,16 +152302,16 @@ func (pager *VpcsPager) GetNextWithContext(ctx context.Context) (page []VPC, err } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Vpcs + page = result.BackupPolicies return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VpcsPager) GetAllWithContext(ctx context.Context) (allItems []VPC, err error) { +func (pager *BackupPoliciesPager) GetAllWithContext(ctx context.Context) (allItems []BackupPolicyIntf, err error) { for pager.HasNext() { - var nextPage []VPC + var nextPage []BackupPolicyIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -149368,38 +152323,38 @@ func (pager *VpcsPager) GetAllWithContext(ctx context.Context) (allItems []VPC, } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VpcsPager) GetNext() (page []VPC, err error) { +func (pager *BackupPoliciesPager) GetNext() (page []BackupPolicyIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VpcsPager) GetAll() (allItems []VPC, err error) { +func (pager *BackupPoliciesPager) GetAll() (allItems []BackupPolicyIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPCAddressPrefixesPager can be used to simplify the use of the "ListVPCAddressPrefixes" method. -type VPCAddressPrefixesPager struct { +// BackupPolicyJobsPager can be used to simplify the use of the "ListBackupPolicyJobs" method. +type BackupPolicyJobsPager struct { hasNext bool - options *ListVPCAddressPrefixesOptions + options *ListBackupPolicyJobsOptions client *VpcV1 pageContext struct { next *string } } -// NewVPCAddressPrefixesPager returns a new VPCAddressPrefixesPager instance. -func (vpc *VpcV1) NewVPCAddressPrefixesPager(options *ListVPCAddressPrefixesOptions) (pager *VPCAddressPrefixesPager, err error) { +// NewBackupPolicyJobsPager returns a new BackupPolicyJobsPager instance. +func (vpc *VpcV1) NewBackupPolicyJobsPager(options *ListBackupPolicyJobsOptions) (pager *BackupPolicyJobsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPCAddressPrefixesOptions = *options - pager = &VPCAddressPrefixesPager{ + var optionsCopy ListBackupPolicyJobsOptions = *options + pager = &BackupPolicyJobsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -149408,19 +152363,19 @@ func (vpc *VpcV1) NewVPCAddressPrefixesPager(options *ListVPCAddressPrefixesOpti } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPCAddressPrefixesPager) HasNext() bool { +func (pager *BackupPolicyJobsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPCAddressPrefixesPager) GetNextWithContext(ctx context.Context) (page []AddressPrefix, err error) { +func (pager *BackupPolicyJobsPager) GetNextWithContext(ctx context.Context) (page []BackupPolicyJob, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPCAddressPrefixesWithContext(ctx, pager.options) + result, _, err := pager.client.ListBackupPolicyJobsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -149439,16 +152394,16 @@ func (pager *VPCAddressPrefixesPager) GetNextWithContext(ctx context.Context) (p } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.AddressPrefixes + page = result.Jobs return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPCAddressPrefixesPager) GetAllWithContext(ctx context.Context) (allItems []AddressPrefix, err error) { +func (pager *BackupPolicyJobsPager) GetAllWithContext(ctx context.Context) (allItems []BackupPolicyJob, err error) { for pager.HasNext() { - var nextPage []AddressPrefix + var nextPage []BackupPolicyJob nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -149460,38 +152415,38 @@ func (pager *VPCAddressPrefixesPager) GetAllWithContext(ctx context.Context) (al } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPCAddressPrefixesPager) GetNext() (page []AddressPrefix, err error) { +func (pager *BackupPolicyJobsPager) GetNext() (page []BackupPolicyJob, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPCAddressPrefixesPager) GetAll() (allItems []AddressPrefix, err error) { +func (pager *BackupPolicyJobsPager) GetAll() (allItems []BackupPolicyJob, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPCDnsResolutionBindingsPager can be used to simplify the use of the "ListVPCDnsResolutionBindings" method. -type VPCDnsResolutionBindingsPager struct { +// BareMetalServerProfilesPager can be used to simplify the use of the "ListBareMetalServerProfiles" method. +type BareMetalServerProfilesPager struct { hasNext bool - options *ListVPCDnsResolutionBindingsOptions + options *ListBareMetalServerProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewVPCDnsResolutionBindingsPager returns a new VPCDnsResolutionBindingsPager instance. -func (vpc *VpcV1) NewVPCDnsResolutionBindingsPager(options *ListVPCDnsResolutionBindingsOptions) (pager *VPCDnsResolutionBindingsPager, err error) { +// NewBareMetalServerProfilesPager returns a new BareMetalServerProfilesPager instance. +func (vpc *VpcV1) NewBareMetalServerProfilesPager(options *ListBareMetalServerProfilesOptions) (pager *BareMetalServerProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPCDnsResolutionBindingsOptions = *options - pager = &VPCDnsResolutionBindingsPager{ + var optionsCopy ListBareMetalServerProfilesOptions = *options + pager = &BareMetalServerProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -149500,19 +152455,19 @@ func (vpc *VpcV1) NewVPCDnsResolutionBindingsPager(options *ListVPCDnsResolution } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPCDnsResolutionBindingsPager) HasNext() bool { +func (pager *BareMetalServerProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPCDnsResolutionBindingsPager) GetNextWithContext(ctx context.Context) (page []VpcdnsResolutionBinding, err error) { +func (pager *BareMetalServerProfilesPager) GetNextWithContext(ctx context.Context) (page []BareMetalServerProfile, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPCDnsResolutionBindingsWithContext(ctx, pager.options) + result, _, err := pager.client.ListBareMetalServerProfilesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -149531,16 +152486,16 @@ func (pager *VPCDnsResolutionBindingsPager) GetNextWithContext(ctx context.Conte } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.DnsResolutionBindings + page = result.Profiles return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPCDnsResolutionBindingsPager) GetAllWithContext(ctx context.Context) (allItems []VpcdnsResolutionBinding, err error) { +func (pager *BareMetalServerProfilesPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServerProfile, err error) { for pager.HasNext() { - var nextPage []VpcdnsResolutionBinding + var nextPage []BareMetalServerProfile nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -149552,38 +152507,38 @@ func (pager *VPCDnsResolutionBindingsPager) GetAllWithContext(ctx context.Contex } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPCDnsResolutionBindingsPager) GetNext() (page []VpcdnsResolutionBinding, err error) { +func (pager *BareMetalServerProfilesPager) GetNext() (page []BareMetalServerProfile, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPCDnsResolutionBindingsPager) GetAll() (allItems []VpcdnsResolutionBinding, err error) { +func (pager *BareMetalServerProfilesPager) GetAll() (allItems []BareMetalServerProfile, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPCRoutesPager can be used to simplify the use of the "ListVPCRoutes" method. -type VPCRoutesPager struct { +// BareMetalServersPager can be used to simplify the use of the "ListBareMetalServers" method. +type BareMetalServersPager struct { hasNext bool - options *ListVPCRoutesOptions + options *ListBareMetalServersOptions client *VpcV1 pageContext struct { next *string } } -// NewVPCRoutesPager returns a new VPCRoutesPager instance. -func (vpc *VpcV1) NewVPCRoutesPager(options *ListVPCRoutesOptions) (pager *VPCRoutesPager, err error) { +// NewBareMetalServersPager returns a new BareMetalServersPager instance. +func (vpc *VpcV1) NewBareMetalServersPager(options *ListBareMetalServersOptions) (pager *BareMetalServersPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPCRoutesOptions = *options - pager = &VPCRoutesPager{ + var optionsCopy ListBareMetalServersOptions = *options + pager = &BareMetalServersPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -149592,19 +152547,19 @@ func (vpc *VpcV1) NewVPCRoutesPager(options *ListVPCRoutesOptions) (pager *VPCRo } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPCRoutesPager) HasNext() bool { +func (pager *BareMetalServersPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPCRoutesPager) GetNextWithContext(ctx context.Context) (page []Route, err error) { +func (pager *BareMetalServersPager) GetNextWithContext(ctx context.Context) (page []BareMetalServer, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPCRoutesWithContext(ctx, pager.options) + result, _, err := pager.client.ListBareMetalServersWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -149623,16 +152578,16 @@ func (pager *VPCRoutesPager) GetNextWithContext(ctx context.Context) (page []Rou } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Routes + page = result.BareMetalServers return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPCRoutesPager) GetAllWithContext(ctx context.Context) (allItems []Route, err error) { +func (pager *BareMetalServersPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServer, err error) { for pager.HasNext() { - var nextPage []Route + var nextPage []BareMetalServer nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -149644,38 +152599,38 @@ func (pager *VPCRoutesPager) GetAllWithContext(ctx context.Context) (allItems [] } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPCRoutesPager) GetNext() (page []Route, err error) { +func (pager *BareMetalServersPager) GetNext() (page []BareMetalServer, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPCRoutesPager) GetAll() (allItems []Route, err error) { +func (pager *BareMetalServersPager) GetAll() (allItems []BareMetalServer, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPCRoutingTablesPager can be used to simplify the use of the "ListVPCRoutingTables" method. -type VPCRoutingTablesPager struct { +// BareMetalServerNetworkAttachmentsPager can be used to simplify the use of the "ListBareMetalServerNetworkAttachments" method. +type BareMetalServerNetworkAttachmentsPager struct { hasNext bool - options *ListVPCRoutingTablesOptions + options *ListBareMetalServerNetworkAttachmentsOptions client *VpcV1 pageContext struct { next *string } } -// NewVPCRoutingTablesPager returns a new VPCRoutingTablesPager instance. -func (vpc *VpcV1) NewVPCRoutingTablesPager(options *ListVPCRoutingTablesOptions) (pager *VPCRoutingTablesPager, err error) { +// NewBareMetalServerNetworkAttachmentsPager returns a new BareMetalServerNetworkAttachmentsPager instance. +func (vpc *VpcV1) NewBareMetalServerNetworkAttachmentsPager(options *ListBareMetalServerNetworkAttachmentsOptions) (pager *BareMetalServerNetworkAttachmentsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPCRoutingTablesOptions = *options - pager = &VPCRoutingTablesPager{ + var optionsCopy ListBareMetalServerNetworkAttachmentsOptions = *options + pager = &BareMetalServerNetworkAttachmentsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -149684,19 +152639,19 @@ func (vpc *VpcV1) NewVPCRoutingTablesPager(options *ListVPCRoutingTablesOptions) } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPCRoutingTablesPager) HasNext() bool { +func (pager *BareMetalServerNetworkAttachmentsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPCRoutingTablesPager) GetNextWithContext(ctx context.Context) (page []RoutingTable, err error) { +func (pager *BareMetalServerNetworkAttachmentsPager) GetNextWithContext(ctx context.Context) (page []BareMetalServerNetworkAttachmentIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPCRoutingTablesWithContext(ctx, pager.options) + result, _, err := pager.client.ListBareMetalServerNetworkAttachmentsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -149715,16 +152670,16 @@ func (pager *VPCRoutingTablesPager) GetNextWithContext(ctx context.Context) (pag } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.RoutingTables + page = result.NetworkAttachments return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPCRoutingTablesPager) GetAllWithContext(ctx context.Context) (allItems []RoutingTable, err error) { +func (pager *BareMetalServerNetworkAttachmentsPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServerNetworkAttachmentIntf, err error) { for pager.HasNext() { - var nextPage []RoutingTable + var nextPage []BareMetalServerNetworkAttachmentIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -149736,38 +152691,38 @@ func (pager *VPCRoutingTablesPager) GetAllWithContext(ctx context.Context) (allI } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPCRoutingTablesPager) GetNext() (page []RoutingTable, err error) { +func (pager *BareMetalServerNetworkAttachmentsPager) GetNext() (page []BareMetalServerNetworkAttachmentIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPCRoutingTablesPager) GetAll() (allItems []RoutingTable, err error) { +func (pager *BareMetalServerNetworkAttachmentsPager) GetAll() (allItems []BareMetalServerNetworkAttachmentIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPCRoutingTableRoutesPager can be used to simplify the use of the "ListVPCRoutingTableRoutes" method. -type VPCRoutingTableRoutesPager struct { +// BareMetalServerNetworkInterfacesPager can be used to simplify the use of the "ListBareMetalServerNetworkInterfaces" method. +type BareMetalServerNetworkInterfacesPager struct { hasNext bool - options *ListVPCRoutingTableRoutesOptions + options *ListBareMetalServerNetworkInterfacesOptions client *VpcV1 pageContext struct { next *string } } -// NewVPCRoutingTableRoutesPager returns a new VPCRoutingTableRoutesPager instance. -func (vpc *VpcV1) NewVPCRoutingTableRoutesPager(options *ListVPCRoutingTableRoutesOptions) (pager *VPCRoutingTableRoutesPager, err error) { +// NewBareMetalServerNetworkInterfacesPager returns a new BareMetalServerNetworkInterfacesPager instance. +func (vpc *VpcV1) NewBareMetalServerNetworkInterfacesPager(options *ListBareMetalServerNetworkInterfacesOptions) (pager *BareMetalServerNetworkInterfacesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPCRoutingTableRoutesOptions = *options - pager = &VPCRoutingTableRoutesPager{ + var optionsCopy ListBareMetalServerNetworkInterfacesOptions = *options + pager = &BareMetalServerNetworkInterfacesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -149776,19 +152731,19 @@ func (vpc *VpcV1) NewVPCRoutingTableRoutesPager(options *ListVPCRoutingTableRout } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPCRoutingTableRoutesPager) HasNext() bool { +func (pager *BareMetalServerNetworkInterfacesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPCRoutingTableRoutesPager) GetNextWithContext(ctx context.Context) (page []Route, err error) { +func (pager *BareMetalServerNetworkInterfacesPager) GetNextWithContext(ctx context.Context) (page []BareMetalServerNetworkInterfaceIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPCRoutingTableRoutesWithContext(ctx, pager.options) + result, _, err := pager.client.ListBareMetalServerNetworkInterfacesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -149807,16 +152762,16 @@ func (pager *VPCRoutingTableRoutesPager) GetNextWithContext(ctx context.Context) } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Routes + page = result.NetworkInterfaces return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPCRoutingTableRoutesPager) GetAllWithContext(ctx context.Context) (allItems []Route, err error) { +func (pager *BareMetalServerNetworkInterfacesPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServerNetworkInterfaceIntf, err error) { for pager.HasNext() { - var nextPage []Route + var nextPage []BareMetalServerNetworkInterfaceIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -149828,38 +152783,38 @@ func (pager *VPCRoutingTableRoutesPager) GetAllWithContext(ctx context.Context) } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPCRoutingTableRoutesPager) GetNext() (page []Route, err error) { +func (pager *BareMetalServerNetworkInterfacesPager) GetNext() (page []BareMetalServerNetworkInterfaceIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPCRoutingTableRoutesPager) GetAll() (allItems []Route, err error) { +func (pager *BareMetalServerNetworkInterfacesPager) GetAll() (allItems []BareMetalServerNetworkInterfaceIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// SubnetsPager can be used to simplify the use of the "ListSubnets" method. -type SubnetsPager struct { +// ClusterNetworkProfilesPager can be used to simplify the use of the "ListClusterNetworkProfiles" method. +type ClusterNetworkProfilesPager struct { hasNext bool - options *ListSubnetsOptions + options *ListClusterNetworkProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewSubnetsPager returns a new SubnetsPager instance. -func (vpc *VpcV1) NewSubnetsPager(options *ListSubnetsOptions) (pager *SubnetsPager, err error) { +// NewClusterNetworkProfilesPager returns a new ClusterNetworkProfilesPager instance. +func (vpc *VpcV1) NewClusterNetworkProfilesPager(options *ListClusterNetworkProfilesOptions) (pager *ClusterNetworkProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListSubnetsOptions = *options - pager = &SubnetsPager{ + var optionsCopy ListClusterNetworkProfilesOptions = *options + pager = &ClusterNetworkProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -149868,19 +152823,295 @@ func (vpc *VpcV1) NewSubnetsPager(options *ListSubnetsOptions) (pager *SubnetsPa } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *SubnetsPager) HasNext() bool { +func (pager *ClusterNetworkProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *SubnetsPager) GetNextWithContext(ctx context.Context) (page []Subnet, err error) { +func (pager *ClusterNetworkProfilesPager) GetNextWithContext(ctx context.Context) (page []ClusterNetworkProfile, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListSubnetsWithContext(ctx, pager.options) + result, _, err := pager.client.ListClusterNetworkProfilesWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.Profiles + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *ClusterNetworkProfilesPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetworkProfile, err error) { + for pager.HasNext() { + var nextPage []ClusterNetworkProfile + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *ClusterNetworkProfilesPager) GetNext() (page []ClusterNetworkProfile, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *ClusterNetworkProfilesPager) GetAll() (allItems []ClusterNetworkProfile, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ClusterNetworksPager can be used to simplify the use of the "ListClusterNetworks" method. +type ClusterNetworksPager struct { + hasNext bool + options *ListClusterNetworksOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewClusterNetworksPager returns a new ClusterNetworksPager instance. +func (vpc *VpcV1) NewClusterNetworksPager(options *ListClusterNetworksOptions) (pager *ClusterNetworksPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListClusterNetworksOptions = *options + pager = &ClusterNetworksPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *ClusterNetworksPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *ClusterNetworksPager) GetNextWithContext(ctx context.Context) (page []ClusterNetwork, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListClusterNetworksWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.ClusterNetworks + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *ClusterNetworksPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetwork, err error) { + for pager.HasNext() { + var nextPage []ClusterNetwork + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *ClusterNetworksPager) GetNext() (page []ClusterNetwork, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *ClusterNetworksPager) GetAll() (allItems []ClusterNetwork, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ClusterNetworkInterfacesPager can be used to simplify the use of the "ListClusterNetworkInterfaces" method. +type ClusterNetworkInterfacesPager struct { + hasNext bool + options *ListClusterNetworkInterfacesOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewClusterNetworkInterfacesPager returns a new ClusterNetworkInterfacesPager instance. +func (vpc *VpcV1) NewClusterNetworkInterfacesPager(options *ListClusterNetworkInterfacesOptions) (pager *ClusterNetworkInterfacesPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListClusterNetworkInterfacesOptions = *options + pager = &ClusterNetworkInterfacesPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *ClusterNetworkInterfacesPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *ClusterNetworkInterfacesPager) GetNextWithContext(ctx context.Context) (page []ClusterNetworkInterface, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListClusterNetworkInterfacesWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.Interfaces + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *ClusterNetworkInterfacesPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetworkInterface, err error) { + for pager.HasNext() { + var nextPage []ClusterNetworkInterface + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *ClusterNetworkInterfacesPager) GetNext() (page []ClusterNetworkInterface, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *ClusterNetworkInterfacesPager) GetAll() (allItems []ClusterNetworkInterface, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// ClusterNetworkSubnetsPager can be used to simplify the use of the "ListClusterNetworkSubnets" method. +type ClusterNetworkSubnetsPager struct { + hasNext bool + options *ListClusterNetworkSubnetsOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewClusterNetworkSubnetsPager returns a new ClusterNetworkSubnetsPager instance. +func (vpc *VpcV1) NewClusterNetworkSubnetsPager(options *ListClusterNetworkSubnetsOptions) (pager *ClusterNetworkSubnetsPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListClusterNetworkSubnetsOptions = *options + pager = &ClusterNetworkSubnetsPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *ClusterNetworkSubnetsPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *ClusterNetworkSubnetsPager) GetNextWithContext(ctx context.Context) (page []ClusterNetworkSubnet, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListClusterNetworkSubnetsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -149906,9 +153137,9 @@ func (pager *SubnetsPager) GetNextWithContext(ctx context.Context) (page []Subne // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *SubnetsPager) GetAllWithContext(ctx context.Context) (allItems []Subnet, err error) { +func (pager *ClusterNetworkSubnetsPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetworkSubnet, err error) { for pager.HasNext() { - var nextPage []Subnet + var nextPage []ClusterNetworkSubnet nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -149920,38 +153151,38 @@ func (pager *SubnetsPager) GetAllWithContext(ctx context.Context) (allItems []Su } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *SubnetsPager) GetNext() (page []Subnet, err error) { +func (pager *ClusterNetworkSubnetsPager) GetNext() (page []ClusterNetworkSubnet, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *SubnetsPager) GetAll() (allItems []Subnet, err error) { +func (pager *ClusterNetworkSubnetsPager) GetAll() (allItems []ClusterNetworkSubnet, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// SubnetReservedIpsPager can be used to simplify the use of the "ListSubnetReservedIps" method. -type SubnetReservedIpsPager struct { +// ClusterNetworkSubnetReservedIpsPager can be used to simplify the use of the "ListClusterNetworkSubnetReservedIps" method. +type ClusterNetworkSubnetReservedIpsPager struct { hasNext bool - options *ListSubnetReservedIpsOptions + options *ListClusterNetworkSubnetReservedIpsOptions client *VpcV1 pageContext struct { next *string } } -// NewSubnetReservedIpsPager returns a new SubnetReservedIpsPager instance. -func (vpc *VpcV1) NewSubnetReservedIpsPager(options *ListSubnetReservedIpsOptions) (pager *SubnetReservedIpsPager, err error) { +// NewClusterNetworkSubnetReservedIpsPager returns a new ClusterNetworkSubnetReservedIpsPager instance. +func (vpc *VpcV1) NewClusterNetworkSubnetReservedIpsPager(options *ListClusterNetworkSubnetReservedIpsOptions) (pager *ClusterNetworkSubnetReservedIpsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListSubnetReservedIpsOptions = *options - pager = &SubnetReservedIpsPager{ + var optionsCopy ListClusterNetworkSubnetReservedIpsOptions = *options + pager = &ClusterNetworkSubnetReservedIpsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -149960,19 +153191,19 @@ func (vpc *VpcV1) NewSubnetReservedIpsPager(options *ListSubnetReservedIpsOption } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *SubnetReservedIpsPager) HasNext() bool { +func (pager *ClusterNetworkSubnetReservedIpsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *SubnetReservedIpsPager) GetNextWithContext(ctx context.Context) (page []ReservedIP, err error) { +func (pager *ClusterNetworkSubnetReservedIpsPager) GetNextWithContext(ctx context.Context) (page []ClusterNetworkSubnetReservedIP, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListSubnetReservedIpsWithContext(ctx, pager.options) + result, _, err := pager.client.ListClusterNetworkSubnetReservedIpsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -149998,7 +153229,467 @@ func (pager *SubnetReservedIpsPager) GetNextWithContext(ctx context.Context) (pa // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *SubnetReservedIpsPager) GetAllWithContext(ctx context.Context) (allItems []ReservedIP, err error) { +func (pager *ClusterNetworkSubnetReservedIpsPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetworkSubnetReservedIP, err error) { + for pager.HasNext() { + var nextPage []ClusterNetworkSubnetReservedIP + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *ClusterNetworkSubnetReservedIpsPager) GetNext() (page []ClusterNetworkSubnetReservedIP, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *ClusterNetworkSubnetReservedIpsPager) GetAll() (allItems []ClusterNetworkSubnetReservedIP, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// DedicatedHostGroupsPager can be used to simplify the use of the "ListDedicatedHostGroups" method. +type DedicatedHostGroupsPager struct { + hasNext bool + options *ListDedicatedHostGroupsOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewDedicatedHostGroupsPager returns a new DedicatedHostGroupsPager instance. +func (vpc *VpcV1) NewDedicatedHostGroupsPager(options *ListDedicatedHostGroupsOptions) (pager *DedicatedHostGroupsPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListDedicatedHostGroupsOptions = *options + pager = &DedicatedHostGroupsPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *DedicatedHostGroupsPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *DedicatedHostGroupsPager) GetNextWithContext(ctx context.Context) (page []DedicatedHostGroup, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListDedicatedHostGroupsWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.Groups + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *DedicatedHostGroupsPager) GetAllWithContext(ctx context.Context) (allItems []DedicatedHostGroup, err error) { + for pager.HasNext() { + var nextPage []DedicatedHostGroup + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *DedicatedHostGroupsPager) GetNext() (page []DedicatedHostGroup, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *DedicatedHostGroupsPager) GetAll() (allItems []DedicatedHostGroup, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// DedicatedHostProfilesPager can be used to simplify the use of the "ListDedicatedHostProfiles" method. +type DedicatedHostProfilesPager struct { + hasNext bool + options *ListDedicatedHostProfilesOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewDedicatedHostProfilesPager returns a new DedicatedHostProfilesPager instance. +func (vpc *VpcV1) NewDedicatedHostProfilesPager(options *ListDedicatedHostProfilesOptions) (pager *DedicatedHostProfilesPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListDedicatedHostProfilesOptions = *options + pager = &DedicatedHostProfilesPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *DedicatedHostProfilesPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *DedicatedHostProfilesPager) GetNextWithContext(ctx context.Context) (page []DedicatedHostProfile, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListDedicatedHostProfilesWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.Profiles + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *DedicatedHostProfilesPager) GetAllWithContext(ctx context.Context) (allItems []DedicatedHostProfile, err error) { + for pager.HasNext() { + var nextPage []DedicatedHostProfile + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *DedicatedHostProfilesPager) GetNext() (page []DedicatedHostProfile, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *DedicatedHostProfilesPager) GetAll() (allItems []DedicatedHostProfile, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// DedicatedHostsPager can be used to simplify the use of the "ListDedicatedHosts" method. +type DedicatedHostsPager struct { + hasNext bool + options *ListDedicatedHostsOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewDedicatedHostsPager returns a new DedicatedHostsPager instance. +func (vpc *VpcV1) NewDedicatedHostsPager(options *ListDedicatedHostsOptions) (pager *DedicatedHostsPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListDedicatedHostsOptions = *options + pager = &DedicatedHostsPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *DedicatedHostsPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *DedicatedHostsPager) GetNextWithContext(ctx context.Context) (page []DedicatedHost, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListDedicatedHostsWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.DedicatedHosts + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *DedicatedHostsPager) GetAllWithContext(ctx context.Context) (allItems []DedicatedHost, err error) { + for pager.HasNext() { + var nextPage []DedicatedHost + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *DedicatedHostsPager) GetNext() (page []DedicatedHost, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *DedicatedHostsPager) GetAll() (allItems []DedicatedHost, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// EndpointGatewaysPager can be used to simplify the use of the "ListEndpointGateways" method. +type EndpointGatewaysPager struct { + hasNext bool + options *ListEndpointGatewaysOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewEndpointGatewaysPager returns a new EndpointGatewaysPager instance. +func (vpc *VpcV1) NewEndpointGatewaysPager(options *ListEndpointGatewaysOptions) (pager *EndpointGatewaysPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListEndpointGatewaysOptions = *options + pager = &EndpointGatewaysPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *EndpointGatewaysPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *EndpointGatewaysPager) GetNextWithContext(ctx context.Context) (page []EndpointGateway, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListEndpointGatewaysWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.EndpointGateways + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *EndpointGatewaysPager) GetAllWithContext(ctx context.Context) (allItems []EndpointGateway, err error) { + for pager.HasNext() { + var nextPage []EndpointGateway + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *EndpointGatewaysPager) GetNext() (page []EndpointGateway, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *EndpointGatewaysPager) GetAll() (allItems []EndpointGateway, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// EndpointGatewayIpsPager can be used to simplify the use of the "ListEndpointGatewayIps" method. +type EndpointGatewayIpsPager struct { + hasNext bool + options *ListEndpointGatewayIpsOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewEndpointGatewayIpsPager returns a new EndpointGatewayIpsPager instance. +func (vpc *VpcV1) NewEndpointGatewayIpsPager(options *ListEndpointGatewayIpsOptions) (pager *EndpointGatewayIpsPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListEndpointGatewayIpsOptions = *options + pager = &EndpointGatewayIpsPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *EndpointGatewayIpsPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *EndpointGatewayIpsPager) GetNextWithContext(ctx context.Context) (page []ReservedIP, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListEndpointGatewayIpsWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.Ips + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *EndpointGatewayIpsPager) GetAllWithContext(ctx context.Context) (allItems []ReservedIP, err error) { for pager.HasNext() { var nextPage []ReservedIP nextPage, err = pager.GetNextWithContext(ctx) @@ -150012,14 +153703,198 @@ func (pager *SubnetReservedIpsPager) GetAllWithContext(ctx context.Context) (all } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *SubnetReservedIpsPager) GetNext() (page []ReservedIP, err error) { +func (pager *EndpointGatewayIpsPager) GetNext() (page []ReservedIP, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *SubnetReservedIpsPager) GetAll() (allItems []ReservedIP, err error) { +func (pager *EndpointGatewayIpsPager) GetAll() (allItems []ReservedIP, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// FloatingIpsPager can be used to simplify the use of the "ListFloatingIps" method. +type FloatingIpsPager struct { + hasNext bool + options *ListFloatingIpsOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewFloatingIpsPager returns a new FloatingIpsPager instance. +func (vpc *VpcV1) NewFloatingIpsPager(options *ListFloatingIpsOptions) (pager *FloatingIpsPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListFloatingIpsOptions = *options + pager = &FloatingIpsPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *FloatingIpsPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *FloatingIpsPager) GetNextWithContext(ctx context.Context) (page []FloatingIP, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListFloatingIpsWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.FloatingIps + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *FloatingIpsPager) GetAllWithContext(ctx context.Context) (allItems []FloatingIP, err error) { + for pager.HasNext() { + var nextPage []FloatingIP + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *FloatingIpsPager) GetNext() (page []FloatingIP, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *FloatingIpsPager) GetAll() (allItems []FloatingIP, err error) { + allItems, err = pager.GetAllWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// FlowLogCollectorsPager can be used to simplify the use of the "ListFlowLogCollectors" method. +type FlowLogCollectorsPager struct { + hasNext bool + options *ListFlowLogCollectorsOptions + client *VpcV1 + pageContext struct { + next *string + } +} + +// NewFlowLogCollectorsPager returns a new FlowLogCollectorsPager instance. +func (vpc *VpcV1) NewFlowLogCollectorsPager(options *ListFlowLogCollectorsOptions) (pager *FlowLogCollectorsPager, err error) { + if options.Start != nil && *options.Start != "" { + err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) + return + } + + var optionsCopy ListFlowLogCollectorsOptions = *options + pager = &FlowLogCollectorsPager{ + hasNext: true, + options: &optionsCopy, + client: vpc, + } + return +} + +// HasNext returns true if there are potentially more results to be retrieved. +func (pager *FlowLogCollectorsPager) HasNext() bool { + return pager.hasNext +} + +// GetNextWithContext returns the next page of results using the specified Context. +func (pager *FlowLogCollectorsPager) GetNextWithContext(ctx context.Context) (page []FlowLogCollector, err error) { + if !pager.HasNext() { + return nil, fmt.Errorf("no more results available") + } + + pager.options.Start = pager.pageContext.next + + result, _, err := pager.client.ListFlowLogCollectorsWithContext(ctx, pager.options) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + + var next *string + if result.Next != nil { + var start *string + start, err = core.GetQueryParam(result.Next.Href, "start") + if err != nil { + errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) + err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) + return + } + next = start + } + pager.pageContext.next = next + pager.hasNext = (pager.pageContext.next != nil) + page = result.FlowLogCollectors + + return +} + +// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly +// until all pages of results have been retrieved. +func (pager *FlowLogCollectorsPager) GetAllWithContext(ctx context.Context) (allItems []FlowLogCollector, err error) { + for pager.HasNext() { + var nextPage []FlowLogCollector + nextPage, err = pager.GetNextWithContext(ctx) + if err != nil { + err = core.RepurposeSDKProblem(err, "error-getting-next-page") + return + } + allItems = append(allItems, nextPage...) + } + return +} + +// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. +func (pager *FlowLogCollectorsPager) GetNext() (page []FlowLogCollector, err error) { + page, err = pager.GetNextWithContext(context.Background()) + err = core.RepurposeSDKProblem(err, "") + return +} + +// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. +func (pager *FlowLogCollectorsPager) GetAll() (allItems []FlowLogCollector, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return @@ -150117,209 +153992,25 @@ func (pager *ImagesPager) GetAll() (allItems []Image, err error) { return } -// OperatingSystemsPager can be used to simplify the use of the "ListOperatingSystems" method. -type OperatingSystemsPager struct { - hasNext bool - options *ListOperatingSystemsOptions - client *VpcV1 - pageContext struct { - next *string - } -} - -// NewOperatingSystemsPager returns a new OperatingSystemsPager instance. -func (vpc *VpcV1) NewOperatingSystemsPager(options *ListOperatingSystemsOptions) (pager *OperatingSystemsPager, err error) { - if options.Start != nil && *options.Start != "" { - err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) - return - } - - var optionsCopy ListOperatingSystemsOptions = *options - pager = &OperatingSystemsPager{ - hasNext: true, - options: &optionsCopy, - client: vpc, - } - return -} - -// HasNext returns true if there are potentially more results to be retrieved. -func (pager *OperatingSystemsPager) HasNext() bool { - return pager.hasNext -} - -// GetNextWithContext returns the next page of results using the specified Context. -func (pager *OperatingSystemsPager) GetNextWithContext(ctx context.Context) (page []OperatingSystem, err error) { - if !pager.HasNext() { - return nil, fmt.Errorf("no more results available") - } - - pager.options.Start = pager.pageContext.next - - result, _, err := pager.client.ListOperatingSystemsWithContext(ctx, pager.options) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - - var next *string - if result.Next != nil { - var start *string - start, err = core.GetQueryParam(result.Next.Href, "start") - if err != nil { - errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) - err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) - return - } - next = start - } - pager.pageContext.next = next - pager.hasNext = (pager.pageContext.next != nil) - page = result.OperatingSystems - - return -} - -// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly -// until all pages of results have been retrieved. -func (pager *OperatingSystemsPager) GetAllWithContext(ctx context.Context) (allItems []OperatingSystem, err error) { - for pager.HasNext() { - var nextPage []OperatingSystem - nextPage, err = pager.GetNextWithContext(ctx) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - allItems = append(allItems, nextPage...) - } - return -} - -// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *OperatingSystemsPager) GetNext() (page []OperatingSystem, err error) { - page, err = pager.GetNextWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *OperatingSystemsPager) GetAll() (allItems []OperatingSystem, err error) { - allItems, err = pager.GetAllWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// KeysPager can be used to simplify the use of the "ListKeys" method. -type KeysPager struct { - hasNext bool - options *ListKeysOptions - client *VpcV1 - pageContext struct { - next *string - } -} - -// NewKeysPager returns a new KeysPager instance. -func (vpc *VpcV1) NewKeysPager(options *ListKeysOptions) (pager *KeysPager, err error) { - if options.Start != nil && *options.Start != "" { - err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) - return - } - - var optionsCopy ListKeysOptions = *options - pager = &KeysPager{ - hasNext: true, - options: &optionsCopy, - client: vpc, - } - return -} - -// HasNext returns true if there are potentially more results to be retrieved. -func (pager *KeysPager) HasNext() bool { - return pager.hasNext -} - -// GetNextWithContext returns the next page of results using the specified Context. -func (pager *KeysPager) GetNextWithContext(ctx context.Context) (page []Key, err error) { - if !pager.HasNext() { - return nil, fmt.Errorf("no more results available") - } - - pager.options.Start = pager.pageContext.next - - result, _, err := pager.client.ListKeysWithContext(ctx, pager.options) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - - var next *string - if result.Next != nil { - var start *string - start, err = core.GetQueryParam(result.Next.Href, "start") - if err != nil { - errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) - err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) - return - } - next = start - } - pager.pageContext.next = next - pager.hasNext = (pager.pageContext.next != nil) - page = result.Keys - - return -} - -// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly -// until all pages of results have been retrieved. -func (pager *KeysPager) GetAllWithContext(ctx context.Context) (allItems []Key, err error) { - for pager.HasNext() { - var nextPage []Key - nextPage, err = pager.GetNextWithContext(ctx) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - allItems = append(allItems, nextPage...) - } - return -} - -// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *KeysPager) GetNext() (page []Key, err error) { - page, err = pager.GetNextWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *KeysPager) GetAll() (allItems []Key, err error) { - allItems, err = pager.GetAllWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// InstancesPager can be used to simplify the use of the "ListInstances" method. -type InstancesPager struct { +// ImageBareMetalServerProfilesPager can be used to simplify the use of the "ListImageBareMetalServerProfiles" method. +type ImageBareMetalServerProfilesPager struct { hasNext bool - options *ListInstancesOptions + options *ListImageBareMetalServerProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewInstancesPager returns a new InstancesPager instance. -func (vpc *VpcV1) NewInstancesPager(options *ListInstancesOptions) (pager *InstancesPager, err error) { +// NewImageBareMetalServerProfilesPager returns a new ImageBareMetalServerProfilesPager instance. +func (vpc *VpcV1) NewImageBareMetalServerProfilesPager(options *ListImageBareMetalServerProfilesOptions) (pager *ImageBareMetalServerProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListInstancesOptions = *options - pager = &InstancesPager{ + var optionsCopy ListImageBareMetalServerProfilesOptions = *options + pager = &ImageBareMetalServerProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -150328,19 +154019,19 @@ func (vpc *VpcV1) NewInstancesPager(options *ListInstancesOptions) (pager *Insta } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *InstancesPager) HasNext() bool { +func (pager *ImageBareMetalServerProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *InstancesPager) GetNextWithContext(ctx context.Context) (page []Instance, err error) { +func (pager *ImageBareMetalServerProfilesPager) GetNextWithContext(ctx context.Context) (page []BareMetalServerProfileReference, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListInstancesWithContext(ctx, pager.options) + result, _, err := pager.client.ListImageBareMetalServerProfilesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -150359,16 +154050,16 @@ func (pager *InstancesPager) GetNextWithContext(ctx context.Context) (page []Ins } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Instances + page = result.BareMetalServerProfiles return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *InstancesPager) GetAllWithContext(ctx context.Context) (allItems []Instance, err error) { +func (pager *ImageBareMetalServerProfilesPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServerProfileReference, err error) { for pager.HasNext() { - var nextPage []Instance + var nextPage []BareMetalServerProfileReference nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -150380,38 +154071,38 @@ func (pager *InstancesPager) GetAllWithContext(ctx context.Context) (allItems [] } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *InstancesPager) GetNext() (page []Instance, err error) { +func (pager *ImageBareMetalServerProfilesPager) GetNext() (page []BareMetalServerProfileReference, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *InstancesPager) GetAll() (allItems []Instance, err error) { +func (pager *ImageBareMetalServerProfilesPager) GetAll() (allItems []BareMetalServerProfileReference, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// InstanceClusterNetworkAttachmentsPager can be used to simplify the use of the "ListInstanceClusterNetworkAttachments" method. -type InstanceClusterNetworkAttachmentsPager struct { +// ImageInstanceProfilesPager can be used to simplify the use of the "ListImageInstanceProfiles" method. +type ImageInstanceProfilesPager struct { hasNext bool - options *ListInstanceClusterNetworkAttachmentsOptions + options *ListImageInstanceProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewInstanceClusterNetworkAttachmentsPager returns a new InstanceClusterNetworkAttachmentsPager instance. -func (vpc *VpcV1) NewInstanceClusterNetworkAttachmentsPager(options *ListInstanceClusterNetworkAttachmentsOptions) (pager *InstanceClusterNetworkAttachmentsPager, err error) { +// NewImageInstanceProfilesPager returns a new ImageInstanceProfilesPager instance. +func (vpc *VpcV1) NewImageInstanceProfilesPager(options *ListImageInstanceProfilesOptions) (pager *ImageInstanceProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListInstanceClusterNetworkAttachmentsOptions = *options - pager = &InstanceClusterNetworkAttachmentsPager{ + var optionsCopy ListImageInstanceProfilesOptions = *options + pager = &ImageInstanceProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -150420,19 +154111,19 @@ func (vpc *VpcV1) NewInstanceClusterNetworkAttachmentsPager(options *ListInstanc } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *InstanceClusterNetworkAttachmentsPager) HasNext() bool { +func (pager *ImageInstanceProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *InstanceClusterNetworkAttachmentsPager) GetNextWithContext(ctx context.Context) (page []InstanceClusterNetworkAttachment, err error) { +func (pager *ImageInstanceProfilesPager) GetNextWithContext(ctx context.Context) (page []InstanceProfileReference, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListInstanceClusterNetworkAttachmentsWithContext(ctx, pager.options) + result, _, err := pager.client.ListImageInstanceProfilesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -150451,16 +154142,16 @@ func (pager *InstanceClusterNetworkAttachmentsPager) GetNextWithContext(ctx cont } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.ClusterNetworkAttachments + page = result.InstanceProfiles return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *InstanceClusterNetworkAttachmentsPager) GetAllWithContext(ctx context.Context) (allItems []InstanceClusterNetworkAttachment, err error) { +func (pager *ImageInstanceProfilesPager) GetAllWithContext(ctx context.Context) (allItems []InstanceProfileReference, err error) { for pager.HasNext() { - var nextPage []InstanceClusterNetworkAttachment + var nextPage []InstanceProfileReference nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -150472,38 +154163,38 @@ func (pager *InstanceClusterNetworkAttachmentsPager) GetAllWithContext(ctx conte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *InstanceClusterNetworkAttachmentsPager) GetNext() (page []InstanceClusterNetworkAttachment, err error) { +func (pager *ImageInstanceProfilesPager) GetNext() (page []InstanceProfileReference, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *InstanceClusterNetworkAttachmentsPager) GetAll() (allItems []InstanceClusterNetworkAttachment, err error) { +func (pager *ImageInstanceProfilesPager) GetAll() (allItems []InstanceProfileReference, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// InstanceNetworkInterfaceIpsPager can be used to simplify the use of the "ListInstanceNetworkInterfaceIps" method. -type InstanceNetworkInterfaceIpsPager struct { +// OperatingSystemsPager can be used to simplify the use of the "ListOperatingSystems" method. +type OperatingSystemsPager struct { hasNext bool - options *ListInstanceNetworkInterfaceIpsOptions + options *ListOperatingSystemsOptions client *VpcV1 pageContext struct { next *string } } -// NewInstanceNetworkInterfaceIpsPager returns a new InstanceNetworkInterfaceIpsPager instance. -func (vpc *VpcV1) NewInstanceNetworkInterfaceIpsPager(options *ListInstanceNetworkInterfaceIpsOptions) (pager *InstanceNetworkInterfaceIpsPager, err error) { +// NewOperatingSystemsPager returns a new OperatingSystemsPager instance. +func (vpc *VpcV1) NewOperatingSystemsPager(options *ListOperatingSystemsOptions) (pager *OperatingSystemsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListInstanceNetworkInterfaceIpsOptions = *options - pager = &InstanceNetworkInterfaceIpsPager{ + var optionsCopy ListOperatingSystemsOptions = *options + pager = &OperatingSystemsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -150512,19 +154203,19 @@ func (vpc *VpcV1) NewInstanceNetworkInterfaceIpsPager(options *ListInstanceNetwo } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *InstanceNetworkInterfaceIpsPager) HasNext() bool { +func (pager *OperatingSystemsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *InstanceNetworkInterfaceIpsPager) GetNextWithContext(ctx context.Context) (page []ReservedIP, err error) { +func (pager *OperatingSystemsPager) GetNextWithContext(ctx context.Context) (page []OperatingSystem, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListInstanceNetworkInterfaceIpsWithContext(ctx, pager.options) + result, _, err := pager.client.ListOperatingSystemsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -150543,16 +154234,16 @@ func (pager *InstanceNetworkInterfaceIpsPager) GetNextWithContext(ctx context.Co } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Ips + page = result.OperatingSystems return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *InstanceNetworkInterfaceIpsPager) GetAllWithContext(ctx context.Context) (allItems []ReservedIP, err error) { +func (pager *OperatingSystemsPager) GetAllWithContext(ctx context.Context) (allItems []OperatingSystem, err error) { for pager.HasNext() { - var nextPage []ReservedIP + var nextPage []OperatingSystem nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -150564,14 +154255,14 @@ func (pager *InstanceNetworkInterfaceIpsPager) GetAllWithContext(ctx context.Con } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *InstanceNetworkInterfaceIpsPager) GetNext() (page []ReservedIP, err error) { +func (pager *OperatingSystemsPager) GetNext() (page []OperatingSystem, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *InstanceNetworkInterfaceIpsPager) GetAll() (allItems []ReservedIP, err error) { +func (pager *OperatingSystemsPager) GetAll() (allItems []OperatingSystem, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return @@ -151037,117 +154728,25 @@ func (pager *InstanceGroupMembershipsPager) GetAll() (allItems []InstanceGroupMe return } -// ReservationsPager can be used to simplify the use of the "ListReservations" method. -type ReservationsPager struct { - hasNext bool - options *ListReservationsOptions - client *VpcV1 - pageContext struct { - next *string - } -} - -// NewReservationsPager returns a new ReservationsPager instance. -func (vpc *VpcV1) NewReservationsPager(options *ListReservationsOptions) (pager *ReservationsPager, err error) { - if options.Start != nil && *options.Start != "" { - err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) - return - } - - var optionsCopy ListReservationsOptions = *options - pager = &ReservationsPager{ - hasNext: true, - options: &optionsCopy, - client: vpc, - } - return -} - -// HasNext returns true if there are potentially more results to be retrieved. -func (pager *ReservationsPager) HasNext() bool { - return pager.hasNext -} - -// GetNextWithContext returns the next page of results using the specified Context. -func (pager *ReservationsPager) GetNextWithContext(ctx context.Context) (page []Reservation, err error) { - if !pager.HasNext() { - return nil, fmt.Errorf("no more results available") - } - - pager.options.Start = pager.pageContext.next - - result, _, err := pager.client.ListReservationsWithContext(ctx, pager.options) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - - var next *string - if result.Next != nil { - var start *string - start, err = core.GetQueryParam(result.Next.Href, "start") - if err != nil { - errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) - err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) - return - } - next = start - } - pager.pageContext.next = next - pager.hasNext = (pager.pageContext.next != nil) - page = result.Reservations - - return -} - -// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly -// until all pages of results have been retrieved. -func (pager *ReservationsPager) GetAllWithContext(ctx context.Context) (allItems []Reservation, err error) { - for pager.HasNext() { - var nextPage []Reservation - nextPage, err = pager.GetNextWithContext(ctx) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - allItems = append(allItems, nextPage...) - } - return -} - -// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ReservationsPager) GetNext() (page []Reservation, err error) { - page, err = pager.GetNextWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ReservationsPager) GetAll() (allItems []Reservation, err error) { - allItems, err = pager.GetAllWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// DedicatedHostGroupsPager can be used to simplify the use of the "ListDedicatedHostGroups" method. -type DedicatedHostGroupsPager struct { +// InstancesPager can be used to simplify the use of the "ListInstances" method. +type InstancesPager struct { hasNext bool - options *ListDedicatedHostGroupsOptions + options *ListInstancesOptions client *VpcV1 pageContext struct { next *string } } -// NewDedicatedHostGroupsPager returns a new DedicatedHostGroupsPager instance. -func (vpc *VpcV1) NewDedicatedHostGroupsPager(options *ListDedicatedHostGroupsOptions) (pager *DedicatedHostGroupsPager, err error) { +// NewInstancesPager returns a new InstancesPager instance. +func (vpc *VpcV1) NewInstancesPager(options *ListInstancesOptions) (pager *InstancesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListDedicatedHostGroupsOptions = *options - pager = &DedicatedHostGroupsPager{ + var optionsCopy ListInstancesOptions = *options + pager = &InstancesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151156,19 +154755,19 @@ func (vpc *VpcV1) NewDedicatedHostGroupsPager(options *ListDedicatedHostGroupsOp } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *DedicatedHostGroupsPager) HasNext() bool { +func (pager *InstancesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *DedicatedHostGroupsPager) GetNextWithContext(ctx context.Context) (page []DedicatedHostGroup, err error) { +func (pager *InstancesPager) GetNextWithContext(ctx context.Context) (page []Instance, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListDedicatedHostGroupsWithContext(ctx, pager.options) + result, _, err := pager.client.ListInstancesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151187,16 +154786,16 @@ func (pager *DedicatedHostGroupsPager) GetNextWithContext(ctx context.Context) ( } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Groups + page = result.Instances return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *DedicatedHostGroupsPager) GetAllWithContext(ctx context.Context) (allItems []DedicatedHostGroup, err error) { +func (pager *InstancesPager) GetAllWithContext(ctx context.Context) (allItems []Instance, err error) { for pager.HasNext() { - var nextPage []DedicatedHostGroup + var nextPage []Instance nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151208,38 +154807,38 @@ func (pager *DedicatedHostGroupsPager) GetAllWithContext(ctx context.Context) (a } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *DedicatedHostGroupsPager) GetNext() (page []DedicatedHostGroup, err error) { +func (pager *InstancesPager) GetNext() (page []Instance, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *DedicatedHostGroupsPager) GetAll() (allItems []DedicatedHostGroup, err error) { +func (pager *InstancesPager) GetAll() (allItems []Instance, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// DedicatedHostProfilesPager can be used to simplify the use of the "ListDedicatedHostProfiles" method. -type DedicatedHostProfilesPager struct { +// InstanceClusterNetworkAttachmentsPager can be used to simplify the use of the "ListInstanceClusterNetworkAttachments" method. +type InstanceClusterNetworkAttachmentsPager struct { hasNext bool - options *ListDedicatedHostProfilesOptions + options *ListInstanceClusterNetworkAttachmentsOptions client *VpcV1 pageContext struct { next *string } } -// NewDedicatedHostProfilesPager returns a new DedicatedHostProfilesPager instance. -func (vpc *VpcV1) NewDedicatedHostProfilesPager(options *ListDedicatedHostProfilesOptions) (pager *DedicatedHostProfilesPager, err error) { +// NewInstanceClusterNetworkAttachmentsPager returns a new InstanceClusterNetworkAttachmentsPager instance. +func (vpc *VpcV1) NewInstanceClusterNetworkAttachmentsPager(options *ListInstanceClusterNetworkAttachmentsOptions) (pager *InstanceClusterNetworkAttachmentsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListDedicatedHostProfilesOptions = *options - pager = &DedicatedHostProfilesPager{ + var optionsCopy ListInstanceClusterNetworkAttachmentsOptions = *options + pager = &InstanceClusterNetworkAttachmentsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151248,19 +154847,19 @@ func (vpc *VpcV1) NewDedicatedHostProfilesPager(options *ListDedicatedHostProfil } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *DedicatedHostProfilesPager) HasNext() bool { +func (pager *InstanceClusterNetworkAttachmentsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *DedicatedHostProfilesPager) GetNextWithContext(ctx context.Context) (page []DedicatedHostProfile, err error) { +func (pager *InstanceClusterNetworkAttachmentsPager) GetNextWithContext(ctx context.Context) (page []InstanceClusterNetworkAttachment, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListDedicatedHostProfilesWithContext(ctx, pager.options) + result, _, err := pager.client.ListInstanceClusterNetworkAttachmentsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151279,16 +154878,16 @@ func (pager *DedicatedHostProfilesPager) GetNextWithContext(ctx context.Context) } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Profiles + page = result.ClusterNetworkAttachments return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *DedicatedHostProfilesPager) GetAllWithContext(ctx context.Context) (allItems []DedicatedHostProfile, err error) { +func (pager *InstanceClusterNetworkAttachmentsPager) GetAllWithContext(ctx context.Context) (allItems []InstanceClusterNetworkAttachment, err error) { for pager.HasNext() { - var nextPage []DedicatedHostProfile + var nextPage []InstanceClusterNetworkAttachment nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151300,38 +154899,38 @@ func (pager *DedicatedHostProfilesPager) GetAllWithContext(ctx context.Context) } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *DedicatedHostProfilesPager) GetNext() (page []DedicatedHostProfile, err error) { +func (pager *InstanceClusterNetworkAttachmentsPager) GetNext() (page []InstanceClusterNetworkAttachment, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *DedicatedHostProfilesPager) GetAll() (allItems []DedicatedHostProfile, err error) { +func (pager *InstanceClusterNetworkAttachmentsPager) GetAll() (allItems []InstanceClusterNetworkAttachment, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// DedicatedHostsPager can be used to simplify the use of the "ListDedicatedHosts" method. -type DedicatedHostsPager struct { +// InstanceNetworkInterfaceIpsPager can be used to simplify the use of the "ListInstanceNetworkInterfaceIps" method. +type InstanceNetworkInterfaceIpsPager struct { hasNext bool - options *ListDedicatedHostsOptions + options *ListInstanceNetworkInterfaceIpsOptions client *VpcV1 pageContext struct { next *string } } -// NewDedicatedHostsPager returns a new DedicatedHostsPager instance. -func (vpc *VpcV1) NewDedicatedHostsPager(options *ListDedicatedHostsOptions) (pager *DedicatedHostsPager, err error) { +// NewInstanceNetworkInterfaceIpsPager returns a new InstanceNetworkInterfaceIpsPager instance. +func (vpc *VpcV1) NewInstanceNetworkInterfaceIpsPager(options *ListInstanceNetworkInterfaceIpsOptions) (pager *InstanceNetworkInterfaceIpsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListDedicatedHostsOptions = *options - pager = &DedicatedHostsPager{ + var optionsCopy ListInstanceNetworkInterfaceIpsOptions = *options + pager = &InstanceNetworkInterfaceIpsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151340,19 +154939,19 @@ func (vpc *VpcV1) NewDedicatedHostsPager(options *ListDedicatedHostsOptions) (pa } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *DedicatedHostsPager) HasNext() bool { +func (pager *InstanceNetworkInterfaceIpsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *DedicatedHostsPager) GetNextWithContext(ctx context.Context) (page []DedicatedHost, err error) { +func (pager *InstanceNetworkInterfaceIpsPager) GetNextWithContext(ctx context.Context) (page []ReservedIP, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListDedicatedHostsWithContext(ctx, pager.options) + result, _, err := pager.client.ListInstanceNetworkInterfaceIpsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151371,16 +154970,16 @@ func (pager *DedicatedHostsPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.DedicatedHosts + page = result.Ips return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *DedicatedHostsPager) GetAllWithContext(ctx context.Context) (allItems []DedicatedHost, err error) { +func (pager *InstanceNetworkInterfaceIpsPager) GetAllWithContext(ctx context.Context) (allItems []ReservedIP, err error) { for pager.HasNext() { - var nextPage []DedicatedHost + var nextPage []ReservedIP nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151392,38 +154991,38 @@ func (pager *DedicatedHostsPager) GetAllWithContext(ctx context.Context) (allIte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *DedicatedHostsPager) GetNext() (page []DedicatedHost, err error) { +func (pager *InstanceNetworkInterfaceIpsPager) GetNext() (page []ReservedIP, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *DedicatedHostsPager) GetAll() (allItems []DedicatedHost, err error) { +func (pager *InstanceNetworkInterfaceIpsPager) GetAll() (allItems []ReservedIP, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// PlacementGroupsPager can be used to simplify the use of the "ListPlacementGroups" method. -type PlacementGroupsPager struct { +// KeysPager can be used to simplify the use of the "ListKeys" method. +type KeysPager struct { hasNext bool - options *ListPlacementGroupsOptions + options *ListKeysOptions client *VpcV1 pageContext struct { next *string } } -// NewPlacementGroupsPager returns a new PlacementGroupsPager instance. -func (vpc *VpcV1) NewPlacementGroupsPager(options *ListPlacementGroupsOptions) (pager *PlacementGroupsPager, err error) { +// NewKeysPager returns a new KeysPager instance. +func (vpc *VpcV1) NewKeysPager(options *ListKeysOptions) (pager *KeysPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListPlacementGroupsOptions = *options - pager = &PlacementGroupsPager{ + var optionsCopy ListKeysOptions = *options + pager = &KeysPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151432,19 +155031,19 @@ func (vpc *VpcV1) NewPlacementGroupsPager(options *ListPlacementGroupsOptions) ( } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *PlacementGroupsPager) HasNext() bool { +func (pager *KeysPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *PlacementGroupsPager) GetNextWithContext(ctx context.Context) (page []PlacementGroup, err error) { +func (pager *KeysPager) GetNextWithContext(ctx context.Context) (page []Key, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListPlacementGroupsWithContext(ctx, pager.options) + result, _, err := pager.client.ListKeysWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151463,16 +155062,16 @@ func (pager *PlacementGroupsPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.PlacementGroups + page = result.Keys return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *PlacementGroupsPager) GetAllWithContext(ctx context.Context) (allItems []PlacementGroup, err error) { +func (pager *KeysPager) GetAllWithContext(ctx context.Context) (allItems []Key, err error) { for pager.HasNext() { - var nextPage []PlacementGroup + var nextPage []Key nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151484,38 +155083,38 @@ func (pager *PlacementGroupsPager) GetAllWithContext(ctx context.Context) (allIt } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *PlacementGroupsPager) GetNext() (page []PlacementGroup, err error) { +func (pager *KeysPager) GetNext() (page []Key, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *PlacementGroupsPager) GetAll() (allItems []PlacementGroup, err error) { +func (pager *KeysPager) GetAll() (allItems []Key, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// BareMetalServerProfilesPager can be used to simplify the use of the "ListBareMetalServerProfiles" method. -type BareMetalServerProfilesPager struct { +// LoadBalancerProfilesPager can be used to simplify the use of the "ListLoadBalancerProfiles" method. +type LoadBalancerProfilesPager struct { hasNext bool - options *ListBareMetalServerProfilesOptions + options *ListLoadBalancerProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewBareMetalServerProfilesPager returns a new BareMetalServerProfilesPager instance. -func (vpc *VpcV1) NewBareMetalServerProfilesPager(options *ListBareMetalServerProfilesOptions) (pager *BareMetalServerProfilesPager, err error) { +// NewLoadBalancerProfilesPager returns a new LoadBalancerProfilesPager instance. +func (vpc *VpcV1) NewLoadBalancerProfilesPager(options *ListLoadBalancerProfilesOptions) (pager *LoadBalancerProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListBareMetalServerProfilesOptions = *options - pager = &BareMetalServerProfilesPager{ + var optionsCopy ListLoadBalancerProfilesOptions = *options + pager = &LoadBalancerProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151524,19 +155123,19 @@ func (vpc *VpcV1) NewBareMetalServerProfilesPager(options *ListBareMetalServerPr } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *BareMetalServerProfilesPager) HasNext() bool { +func (pager *LoadBalancerProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *BareMetalServerProfilesPager) GetNextWithContext(ctx context.Context) (page []BareMetalServerProfile, err error) { +func (pager *LoadBalancerProfilesPager) GetNextWithContext(ctx context.Context) (page []LoadBalancerProfile, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListBareMetalServerProfilesWithContext(ctx, pager.options) + result, _, err := pager.client.ListLoadBalancerProfilesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151562,9 +155161,9 @@ func (pager *BareMetalServerProfilesPager) GetNextWithContext(ctx context.Contex // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *BareMetalServerProfilesPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServerProfile, err error) { +func (pager *LoadBalancerProfilesPager) GetAllWithContext(ctx context.Context) (allItems []LoadBalancerProfile, err error) { for pager.HasNext() { - var nextPage []BareMetalServerProfile + var nextPage []LoadBalancerProfile nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151576,38 +155175,38 @@ func (pager *BareMetalServerProfilesPager) GetAllWithContext(ctx context.Context } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *BareMetalServerProfilesPager) GetNext() (page []BareMetalServerProfile, err error) { +func (pager *LoadBalancerProfilesPager) GetNext() (page []LoadBalancerProfile, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *BareMetalServerProfilesPager) GetAll() (allItems []BareMetalServerProfile, err error) { +func (pager *LoadBalancerProfilesPager) GetAll() (allItems []LoadBalancerProfile, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// BareMetalServersPager can be used to simplify the use of the "ListBareMetalServers" method. -type BareMetalServersPager struct { +// LoadBalancersPager can be used to simplify the use of the "ListLoadBalancers" method. +type LoadBalancersPager struct { hasNext bool - options *ListBareMetalServersOptions + options *ListLoadBalancersOptions client *VpcV1 pageContext struct { next *string } } -// NewBareMetalServersPager returns a new BareMetalServersPager instance. -func (vpc *VpcV1) NewBareMetalServersPager(options *ListBareMetalServersOptions) (pager *BareMetalServersPager, err error) { +// NewLoadBalancersPager returns a new LoadBalancersPager instance. +func (vpc *VpcV1) NewLoadBalancersPager(options *ListLoadBalancersOptions) (pager *LoadBalancersPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListBareMetalServersOptions = *options - pager = &BareMetalServersPager{ + var optionsCopy ListLoadBalancersOptions = *options + pager = &LoadBalancersPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151616,19 +155215,19 @@ func (vpc *VpcV1) NewBareMetalServersPager(options *ListBareMetalServersOptions) } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *BareMetalServersPager) HasNext() bool { +func (pager *LoadBalancersPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *BareMetalServersPager) GetNextWithContext(ctx context.Context) (page []BareMetalServer, err error) { +func (pager *LoadBalancersPager) GetNextWithContext(ctx context.Context) (page []LoadBalancer, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListBareMetalServersWithContext(ctx, pager.options) + result, _, err := pager.client.ListLoadBalancersWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151647,16 +155246,16 @@ func (pager *BareMetalServersPager) GetNextWithContext(ctx context.Context) (pag } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.BareMetalServers + page = result.LoadBalancers return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *BareMetalServersPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServer, err error) { +func (pager *LoadBalancersPager) GetAllWithContext(ctx context.Context) (allItems []LoadBalancer, err error) { for pager.HasNext() { - var nextPage []BareMetalServer + var nextPage []LoadBalancer nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151668,38 +155267,38 @@ func (pager *BareMetalServersPager) GetAllWithContext(ctx context.Context) (allI } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *BareMetalServersPager) GetNext() (page []BareMetalServer, err error) { +func (pager *LoadBalancersPager) GetNext() (page []LoadBalancer, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *BareMetalServersPager) GetAll() (allItems []BareMetalServer, err error) { +func (pager *LoadBalancersPager) GetAll() (allItems []LoadBalancer, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// BareMetalServerNetworkAttachmentsPager can be used to simplify the use of the "ListBareMetalServerNetworkAttachments" method. -type BareMetalServerNetworkAttachmentsPager struct { +// NetworkAclsPager can be used to simplify the use of the "ListNetworkAcls" method. +type NetworkAclsPager struct { hasNext bool - options *ListBareMetalServerNetworkAttachmentsOptions + options *ListNetworkAclsOptions client *VpcV1 pageContext struct { next *string } } -// NewBareMetalServerNetworkAttachmentsPager returns a new BareMetalServerNetworkAttachmentsPager instance. -func (vpc *VpcV1) NewBareMetalServerNetworkAttachmentsPager(options *ListBareMetalServerNetworkAttachmentsOptions) (pager *BareMetalServerNetworkAttachmentsPager, err error) { +// NewNetworkAclsPager returns a new NetworkAclsPager instance. +func (vpc *VpcV1) NewNetworkAclsPager(options *ListNetworkAclsOptions) (pager *NetworkAclsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListBareMetalServerNetworkAttachmentsOptions = *options - pager = &BareMetalServerNetworkAttachmentsPager{ + var optionsCopy ListNetworkAclsOptions = *options + pager = &NetworkAclsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151708,19 +155307,19 @@ func (vpc *VpcV1) NewBareMetalServerNetworkAttachmentsPager(options *ListBareMet } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *BareMetalServerNetworkAttachmentsPager) HasNext() bool { +func (pager *NetworkAclsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *BareMetalServerNetworkAttachmentsPager) GetNextWithContext(ctx context.Context) (page []BareMetalServerNetworkAttachmentIntf, err error) { +func (pager *NetworkAclsPager) GetNextWithContext(ctx context.Context) (page []NetworkACL, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListBareMetalServerNetworkAttachmentsWithContext(ctx, pager.options) + result, _, err := pager.client.ListNetworkAclsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151739,16 +155338,16 @@ func (pager *BareMetalServerNetworkAttachmentsPager) GetNextWithContext(ctx cont } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.NetworkAttachments + page = result.NetworkAcls return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *BareMetalServerNetworkAttachmentsPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServerNetworkAttachmentIntf, err error) { +func (pager *NetworkAclsPager) GetAllWithContext(ctx context.Context) (allItems []NetworkACL, err error) { for pager.HasNext() { - var nextPage []BareMetalServerNetworkAttachmentIntf + var nextPage []NetworkACL nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151760,38 +155359,38 @@ func (pager *BareMetalServerNetworkAttachmentsPager) GetAllWithContext(ctx conte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *BareMetalServerNetworkAttachmentsPager) GetNext() (page []BareMetalServerNetworkAttachmentIntf, err error) { +func (pager *NetworkAclsPager) GetNext() (page []NetworkACL, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *BareMetalServerNetworkAttachmentsPager) GetAll() (allItems []BareMetalServerNetworkAttachmentIntf, err error) { +func (pager *NetworkAclsPager) GetAll() (allItems []NetworkACL, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// BareMetalServerNetworkInterfacesPager can be used to simplify the use of the "ListBareMetalServerNetworkInterfaces" method. -type BareMetalServerNetworkInterfacesPager struct { +// NetworkACLRulesPager can be used to simplify the use of the "ListNetworkACLRules" method. +type NetworkACLRulesPager struct { hasNext bool - options *ListBareMetalServerNetworkInterfacesOptions + options *ListNetworkACLRulesOptions client *VpcV1 pageContext struct { next *string } } -// NewBareMetalServerNetworkInterfacesPager returns a new BareMetalServerNetworkInterfacesPager instance. -func (vpc *VpcV1) NewBareMetalServerNetworkInterfacesPager(options *ListBareMetalServerNetworkInterfacesOptions) (pager *BareMetalServerNetworkInterfacesPager, err error) { +// NewNetworkACLRulesPager returns a new NetworkACLRulesPager instance. +func (vpc *VpcV1) NewNetworkACLRulesPager(options *ListNetworkACLRulesOptions) (pager *NetworkACLRulesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListBareMetalServerNetworkInterfacesOptions = *options - pager = &BareMetalServerNetworkInterfacesPager{ + var optionsCopy ListNetworkACLRulesOptions = *options + pager = &NetworkACLRulesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151800,19 +155399,19 @@ func (vpc *VpcV1) NewBareMetalServerNetworkInterfacesPager(options *ListBareMeta } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *BareMetalServerNetworkInterfacesPager) HasNext() bool { +func (pager *NetworkACLRulesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *BareMetalServerNetworkInterfacesPager) GetNextWithContext(ctx context.Context) (page []BareMetalServerNetworkInterfaceIntf, err error) { +func (pager *NetworkACLRulesPager) GetNextWithContext(ctx context.Context) (page []NetworkACLRuleItemIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListBareMetalServerNetworkInterfacesWithContext(ctx, pager.options) + result, _, err := pager.client.ListNetworkACLRulesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151831,16 +155430,16 @@ func (pager *BareMetalServerNetworkInterfacesPager) GetNextWithContext(ctx conte } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.NetworkInterfaces + page = result.Rules return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *BareMetalServerNetworkInterfacesPager) GetAllWithContext(ctx context.Context) (allItems []BareMetalServerNetworkInterfaceIntf, err error) { +func (pager *NetworkACLRulesPager) GetAllWithContext(ctx context.Context) (allItems []NetworkACLRuleItemIntf, err error) { for pager.HasNext() { - var nextPage []BareMetalServerNetworkInterfaceIntf + var nextPage []NetworkACLRuleItemIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151852,38 +155451,38 @@ func (pager *BareMetalServerNetworkInterfacesPager) GetAllWithContext(ctx contex } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *BareMetalServerNetworkInterfacesPager) GetNext() (page []BareMetalServerNetworkInterfaceIntf, err error) { +func (pager *NetworkACLRulesPager) GetNext() (page []NetworkACLRuleItemIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *BareMetalServerNetworkInterfacesPager) GetAll() (allItems []BareMetalServerNetworkInterfaceIntf, err error) { +func (pager *NetworkACLRulesPager) GetAll() (allItems []NetworkACLRuleItemIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VolumeProfilesPager can be used to simplify the use of the "ListVolumeProfiles" method. -type VolumeProfilesPager struct { +// PlacementGroupsPager can be used to simplify the use of the "ListPlacementGroups" method. +type PlacementGroupsPager struct { hasNext bool - options *ListVolumeProfilesOptions + options *ListPlacementGroupsOptions client *VpcV1 pageContext struct { next *string } } -// NewVolumeProfilesPager returns a new VolumeProfilesPager instance. -func (vpc *VpcV1) NewVolumeProfilesPager(options *ListVolumeProfilesOptions) (pager *VolumeProfilesPager, err error) { +// NewPlacementGroupsPager returns a new PlacementGroupsPager instance. +func (vpc *VpcV1) NewPlacementGroupsPager(options *ListPlacementGroupsOptions) (pager *PlacementGroupsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVolumeProfilesOptions = *options - pager = &VolumeProfilesPager{ + var optionsCopy ListPlacementGroupsOptions = *options + pager = &PlacementGroupsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151892,19 +155491,19 @@ func (vpc *VpcV1) NewVolumeProfilesPager(options *ListVolumeProfilesOptions) (pa } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VolumeProfilesPager) HasNext() bool { +func (pager *PlacementGroupsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VolumeProfilesPager) GetNextWithContext(ctx context.Context) (page []VolumeProfile, err error) { +func (pager *PlacementGroupsPager) GetNextWithContext(ctx context.Context) (page []PlacementGroup, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVolumeProfilesWithContext(ctx, pager.options) + result, _, err := pager.client.ListPlacementGroupsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -151923,16 +155522,16 @@ func (pager *VolumeProfilesPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Profiles + page = result.PlacementGroups return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VolumeProfilesPager) GetAllWithContext(ctx context.Context) (allItems []VolumeProfile, err error) { +func (pager *PlacementGroupsPager) GetAllWithContext(ctx context.Context) (allItems []PlacementGroup, err error) { for pager.HasNext() { - var nextPage []VolumeProfile + var nextPage []PlacementGroup nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -151944,38 +155543,38 @@ func (pager *VolumeProfilesPager) GetAllWithContext(ctx context.Context) (allIte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VolumeProfilesPager) GetNext() (page []VolumeProfile, err error) { +func (pager *PlacementGroupsPager) GetNext() (page []PlacementGroup, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VolumeProfilesPager) GetAll() (allItems []VolumeProfile, err error) { +func (pager *PlacementGroupsPager) GetAll() (allItems []PlacementGroup, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VolumesPager can be used to simplify the use of the "ListVolumes" method. -type VolumesPager struct { +// PrivatePathServiceGatewaysPager can be used to simplify the use of the "ListPrivatePathServiceGateways" method. +type PrivatePathServiceGatewaysPager struct { hasNext bool - options *ListVolumesOptions + options *ListPrivatePathServiceGatewaysOptions client *VpcV1 pageContext struct { next *string } } -// NewVolumesPager returns a new VolumesPager instance. -func (vpc *VpcV1) NewVolumesPager(options *ListVolumesOptions) (pager *VolumesPager, err error) { +// NewPrivatePathServiceGatewaysPager returns a new PrivatePathServiceGatewaysPager instance. +func (vpc *VpcV1) NewPrivatePathServiceGatewaysPager(options *ListPrivatePathServiceGatewaysOptions) (pager *PrivatePathServiceGatewaysPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVolumesOptions = *options - pager = &VolumesPager{ + var optionsCopy ListPrivatePathServiceGatewaysOptions = *options + pager = &PrivatePathServiceGatewaysPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -151984,19 +155583,19 @@ func (vpc *VpcV1) NewVolumesPager(options *ListVolumesOptions) (pager *VolumesPa } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VolumesPager) HasNext() bool { +func (pager *PrivatePathServiceGatewaysPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VolumesPager) GetNextWithContext(ctx context.Context) (page []Volume, err error) { +func (pager *PrivatePathServiceGatewaysPager) GetNextWithContext(ctx context.Context) (page []PrivatePathServiceGateway, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVolumesWithContext(ctx, pager.options) + result, _, err := pager.client.ListPrivatePathServiceGatewaysWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152015,16 +155614,16 @@ func (pager *VolumesPager) GetNextWithContext(ctx context.Context) (page []Volum } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Volumes + page = result.PrivatePathServiceGateways return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VolumesPager) GetAllWithContext(ctx context.Context) (allItems []Volume, err error) { +func (pager *PrivatePathServiceGatewaysPager) GetAllWithContext(ctx context.Context) (allItems []PrivatePathServiceGateway, err error) { for pager.HasNext() { - var nextPage []Volume + var nextPage []PrivatePathServiceGateway nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152036,38 +155635,38 @@ func (pager *VolumesPager) GetAllWithContext(ctx context.Context) (allItems []Vo } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VolumesPager) GetNext() (page []Volume, err error) { +func (pager *PrivatePathServiceGatewaysPager) GetNext() (page []PrivatePathServiceGateway, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VolumesPager) GetAll() (allItems []Volume, err error) { +func (pager *PrivatePathServiceGatewaysPager) GetAll() (allItems []PrivatePathServiceGateway, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// SnapshotConsistencyGroupsPager can be used to simplify the use of the "ListSnapshotConsistencyGroups" method. -type SnapshotConsistencyGroupsPager struct { +// PrivatePathServiceGatewayAccountPoliciesPager can be used to simplify the use of the "ListPrivatePathServiceGatewayAccountPolicies" method. +type PrivatePathServiceGatewayAccountPoliciesPager struct { hasNext bool - options *ListSnapshotConsistencyGroupsOptions + options *ListPrivatePathServiceGatewayAccountPoliciesOptions client *VpcV1 pageContext struct { next *string } } -// NewSnapshotConsistencyGroupsPager returns a new SnapshotConsistencyGroupsPager instance. -func (vpc *VpcV1) NewSnapshotConsistencyGroupsPager(options *ListSnapshotConsistencyGroupsOptions) (pager *SnapshotConsistencyGroupsPager, err error) { +// NewPrivatePathServiceGatewayAccountPoliciesPager returns a new PrivatePathServiceGatewayAccountPoliciesPager instance. +func (vpc *VpcV1) NewPrivatePathServiceGatewayAccountPoliciesPager(options *ListPrivatePathServiceGatewayAccountPoliciesOptions) (pager *PrivatePathServiceGatewayAccountPoliciesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListSnapshotConsistencyGroupsOptions = *options - pager = &SnapshotConsistencyGroupsPager{ + var optionsCopy ListPrivatePathServiceGatewayAccountPoliciesOptions = *options + pager = &PrivatePathServiceGatewayAccountPoliciesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152076,19 +155675,19 @@ func (vpc *VpcV1) NewSnapshotConsistencyGroupsPager(options *ListSnapshotConsist } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *SnapshotConsistencyGroupsPager) HasNext() bool { +func (pager *PrivatePathServiceGatewayAccountPoliciesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *SnapshotConsistencyGroupsPager) GetNextWithContext(ctx context.Context) (page []SnapshotConsistencyGroup, err error) { +func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetNextWithContext(ctx context.Context) (page []PrivatePathServiceGatewayAccountPolicy, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListSnapshotConsistencyGroupsWithContext(ctx, pager.options) + result, _, err := pager.client.ListPrivatePathServiceGatewayAccountPoliciesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152107,16 +155706,16 @@ func (pager *SnapshotConsistencyGroupsPager) GetNextWithContext(ctx context.Cont } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.SnapshotConsistencyGroups + page = result.AccountPolicies return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *SnapshotConsistencyGroupsPager) GetAllWithContext(ctx context.Context) (allItems []SnapshotConsistencyGroup, err error) { +func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetAllWithContext(ctx context.Context) (allItems []PrivatePathServiceGatewayAccountPolicy, err error) { for pager.HasNext() { - var nextPage []SnapshotConsistencyGroup + var nextPage []PrivatePathServiceGatewayAccountPolicy nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152128,38 +155727,38 @@ func (pager *SnapshotConsistencyGroupsPager) GetAllWithContext(ctx context.Conte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *SnapshotConsistencyGroupsPager) GetNext() (page []SnapshotConsistencyGroup, err error) { +func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetNext() (page []PrivatePathServiceGatewayAccountPolicy, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *SnapshotConsistencyGroupsPager) GetAll() (allItems []SnapshotConsistencyGroup, err error) { +func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetAll() (allItems []PrivatePathServiceGatewayAccountPolicy, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// SnapshotsPager can be used to simplify the use of the "ListSnapshots" method. -type SnapshotsPager struct { +// PrivatePathServiceGatewayEndpointGatewayBindingsPager can be used to simplify the use of the "ListPrivatePathServiceGatewayEndpointGatewayBindings" method. +type PrivatePathServiceGatewayEndpointGatewayBindingsPager struct { hasNext bool - options *ListSnapshotsOptions + options *ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions client *VpcV1 pageContext struct { next *string } } -// NewSnapshotsPager returns a new SnapshotsPager instance. -func (vpc *VpcV1) NewSnapshotsPager(options *ListSnapshotsOptions) (pager *SnapshotsPager, err error) { +// NewPrivatePathServiceGatewayEndpointGatewayBindingsPager returns a new PrivatePathServiceGatewayEndpointGatewayBindingsPager instance. +func (vpc *VpcV1) NewPrivatePathServiceGatewayEndpointGatewayBindingsPager(options *ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions) (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListSnapshotsOptions = *options - pager = &SnapshotsPager{ + var optionsCopy ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions = *options + pager = &PrivatePathServiceGatewayEndpointGatewayBindingsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152168,19 +155767,19 @@ func (vpc *VpcV1) NewSnapshotsPager(options *ListSnapshotsOptions) (pager *Snaps } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *SnapshotsPager) HasNext() bool { +func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *SnapshotsPager) GetNextWithContext(ctx context.Context) (page []Snapshot, err error) { +func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetNextWithContext(ctx context.Context) (page []PrivatePathServiceGatewayEndpointGatewayBinding, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListSnapshotsWithContext(ctx, pager.options) + result, _, err := pager.client.ListPrivatePathServiceGatewayEndpointGatewayBindingsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152199,16 +155798,16 @@ func (pager *SnapshotsPager) GetNextWithContext(ctx context.Context) (page []Sna } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Snapshots + page = result.EndpointGatewayBindings return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *SnapshotsPager) GetAllWithContext(ctx context.Context) (allItems []Snapshot, err error) { +func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetAllWithContext(ctx context.Context) (allItems []PrivatePathServiceGatewayEndpointGatewayBinding, err error) { for pager.HasNext() { - var nextPage []Snapshot + var nextPage []PrivatePathServiceGatewayEndpointGatewayBinding nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152220,38 +155819,38 @@ func (pager *SnapshotsPager) GetAllWithContext(ctx context.Context) (allItems [] } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *SnapshotsPager) GetNext() (page []Snapshot, err error) { +func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetNext() (page []PrivatePathServiceGatewayEndpointGatewayBinding, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *SnapshotsPager) GetAll() (allItems []Snapshot, err error) { +func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetAll() (allItems []PrivatePathServiceGatewayEndpointGatewayBinding, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ShareProfilesPager can be used to simplify the use of the "ListShareProfiles" method. -type ShareProfilesPager struct { +// PublicAddressRangesPager can be used to simplify the use of the "ListPublicAddressRanges" method. +type PublicAddressRangesPager struct { hasNext bool - options *ListShareProfilesOptions + options *ListPublicAddressRangesOptions client *VpcV1 pageContext struct { next *string } } -// NewShareProfilesPager returns a new ShareProfilesPager instance. -func (vpc *VpcV1) NewShareProfilesPager(options *ListShareProfilesOptions) (pager *ShareProfilesPager, err error) { +// NewPublicAddressRangesPager returns a new PublicAddressRangesPager instance. +func (vpc *VpcV1) NewPublicAddressRangesPager(options *ListPublicAddressRangesOptions) (pager *PublicAddressRangesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListShareProfilesOptions = *options - pager = &ShareProfilesPager{ + var optionsCopy ListPublicAddressRangesOptions = *options + pager = &PublicAddressRangesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152260,19 +155859,19 @@ func (vpc *VpcV1) NewShareProfilesPager(options *ListShareProfilesOptions) (page } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ShareProfilesPager) HasNext() bool { +func (pager *PublicAddressRangesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ShareProfilesPager) GetNextWithContext(ctx context.Context) (page []ShareProfile, err error) { +func (pager *PublicAddressRangesPager) GetNextWithContext(ctx context.Context) (page []PublicAddressRange, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListShareProfilesWithContext(ctx, pager.options) + result, _, err := pager.client.ListPublicAddressRangesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152291,16 +155890,16 @@ func (pager *ShareProfilesPager) GetNextWithContext(ctx context.Context) (page [ } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Profiles + page = result.PublicAddressRanges return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ShareProfilesPager) GetAllWithContext(ctx context.Context) (allItems []ShareProfile, err error) { +func (pager *PublicAddressRangesPager) GetAllWithContext(ctx context.Context) (allItems []PublicAddressRange, err error) { for pager.HasNext() { - var nextPage []ShareProfile + var nextPage []PublicAddressRange nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152312,38 +155911,38 @@ func (pager *ShareProfilesPager) GetAllWithContext(ctx context.Context) (allItem } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ShareProfilesPager) GetNext() (page []ShareProfile, err error) { +func (pager *PublicAddressRangesPager) GetNext() (page []PublicAddressRange, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ShareProfilesPager) GetAll() (allItems []ShareProfile, err error) { +func (pager *PublicAddressRangesPager) GetAll() (allItems []PublicAddressRange, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// SharesPager can be used to simplify the use of the "ListShares" method. -type SharesPager struct { +// PublicGatewaysPager can be used to simplify the use of the "ListPublicGateways" method. +type PublicGatewaysPager struct { hasNext bool - options *ListSharesOptions + options *ListPublicGatewaysOptions client *VpcV1 pageContext struct { next *string } } -// NewSharesPager returns a new SharesPager instance. -func (vpc *VpcV1) NewSharesPager(options *ListSharesOptions) (pager *SharesPager, err error) { +// NewPublicGatewaysPager returns a new PublicGatewaysPager instance. +func (vpc *VpcV1) NewPublicGatewaysPager(options *ListPublicGatewaysOptions) (pager *PublicGatewaysPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListSharesOptions = *options - pager = &SharesPager{ + var optionsCopy ListPublicGatewaysOptions = *options + pager = &PublicGatewaysPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152352,19 +155951,19 @@ func (vpc *VpcV1) NewSharesPager(options *ListSharesOptions) (pager *SharesPager } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *SharesPager) HasNext() bool { +func (pager *PublicGatewaysPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *SharesPager) GetNextWithContext(ctx context.Context) (page []Share, err error) { +func (pager *PublicGatewaysPager) GetNextWithContext(ctx context.Context) (page []PublicGateway, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListSharesWithContext(ctx, pager.options) + result, _, err := pager.client.ListPublicGatewaysWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152383,16 +155982,16 @@ func (pager *SharesPager) GetNextWithContext(ctx context.Context) (page []Share, } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Shares + page = result.PublicGateways return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *SharesPager) GetAllWithContext(ctx context.Context) (allItems []Share, err error) { +func (pager *PublicGatewaysPager) GetAllWithContext(ctx context.Context) (allItems []PublicGateway, err error) { for pager.HasNext() { - var nextPage []Share + var nextPage []PublicGateway nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152404,38 +156003,38 @@ func (pager *SharesPager) GetAllWithContext(ctx context.Context) (allItems []Sha } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *SharesPager) GetNext() (page []Share, err error) { +func (pager *PublicGatewaysPager) GetNext() (page []PublicGateway, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *SharesPager) GetAll() (allItems []Share, err error) { +func (pager *PublicGatewaysPager) GetAll() (allItems []PublicGateway, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ShareAccessorBindingsPager can be used to simplify the use of the "ListShareAccessorBindings" method. -type ShareAccessorBindingsPager struct { +// ReservationsPager can be used to simplify the use of the "ListReservations" method. +type ReservationsPager struct { hasNext bool - options *ListShareAccessorBindingsOptions + options *ListReservationsOptions client *VpcV1 pageContext struct { next *string } } -// NewShareAccessorBindingsPager returns a new ShareAccessorBindingsPager instance. -func (vpc *VpcV1) NewShareAccessorBindingsPager(options *ListShareAccessorBindingsOptions) (pager *ShareAccessorBindingsPager, err error) { +// NewReservationsPager returns a new ReservationsPager instance. +func (vpc *VpcV1) NewReservationsPager(options *ListReservationsOptions) (pager *ReservationsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListShareAccessorBindingsOptions = *options - pager = &ShareAccessorBindingsPager{ + var optionsCopy ListReservationsOptions = *options + pager = &ReservationsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152444,19 +156043,19 @@ func (vpc *VpcV1) NewShareAccessorBindingsPager(options *ListShareAccessorBindin } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ShareAccessorBindingsPager) HasNext() bool { +func (pager *ReservationsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ShareAccessorBindingsPager) GetNextWithContext(ctx context.Context) (page []ShareAccessorBinding, err error) { +func (pager *ReservationsPager) GetNextWithContext(ctx context.Context) (page []Reservation, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListShareAccessorBindingsWithContext(ctx, pager.options) + result, _, err := pager.client.ListReservationsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152475,16 +156074,16 @@ func (pager *ShareAccessorBindingsPager) GetNextWithContext(ctx context.Context) } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.AccessorBindings + page = result.Reservations return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ShareAccessorBindingsPager) GetAllWithContext(ctx context.Context) (allItems []ShareAccessorBinding, err error) { +func (pager *ReservationsPager) GetAllWithContext(ctx context.Context) (allItems []Reservation, err error) { for pager.HasNext() { - var nextPage []ShareAccessorBinding + var nextPage []Reservation nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152496,38 +156095,38 @@ func (pager *ShareAccessorBindingsPager) GetAllWithContext(ctx context.Context) } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ShareAccessorBindingsPager) GetNext() (page []ShareAccessorBinding, err error) { +func (pager *ReservationsPager) GetNext() (page []Reservation, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ShareAccessorBindingsPager) GetAll() (allItems []ShareAccessorBinding, err error) { +func (pager *ReservationsPager) GetAll() (allItems []Reservation, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ShareMountTargetsPager can be used to simplify the use of the "ListShareMountTargets" method. -type ShareMountTargetsPager struct { +// SecurityGroupsPager can be used to simplify the use of the "ListSecurityGroups" method. +type SecurityGroupsPager struct { hasNext bool - options *ListShareMountTargetsOptions + options *ListSecurityGroupsOptions client *VpcV1 pageContext struct { next *string } } -// NewShareMountTargetsPager returns a new ShareMountTargetsPager instance. -func (vpc *VpcV1) NewShareMountTargetsPager(options *ListShareMountTargetsOptions) (pager *ShareMountTargetsPager, err error) { +// NewSecurityGroupsPager returns a new SecurityGroupsPager instance. +func (vpc *VpcV1) NewSecurityGroupsPager(options *ListSecurityGroupsOptions) (pager *SecurityGroupsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListShareMountTargetsOptions = *options - pager = &ShareMountTargetsPager{ + var optionsCopy ListSecurityGroupsOptions = *options + pager = &SecurityGroupsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152536,19 +156135,19 @@ func (vpc *VpcV1) NewShareMountTargetsPager(options *ListShareMountTargetsOption } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ShareMountTargetsPager) HasNext() bool { +func (pager *SecurityGroupsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ShareMountTargetsPager) GetNextWithContext(ctx context.Context) (page []ShareMountTarget, err error) { +func (pager *SecurityGroupsPager) GetNextWithContext(ctx context.Context) (page []SecurityGroup, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListShareMountTargetsWithContext(ctx, pager.options) + result, _, err := pager.client.ListSecurityGroupsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152567,16 +156166,16 @@ func (pager *ShareMountTargetsPager) GetNextWithContext(ctx context.Context) (pa } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.MountTargets + page = result.SecurityGroups return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ShareMountTargetsPager) GetAllWithContext(ctx context.Context) (allItems []ShareMountTarget, err error) { +func (pager *SecurityGroupsPager) GetAllWithContext(ctx context.Context) (allItems []SecurityGroup, err error) { for pager.HasNext() { - var nextPage []ShareMountTarget + var nextPage []SecurityGroup nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152588,38 +156187,38 @@ func (pager *ShareMountTargetsPager) GetAllWithContext(ctx context.Context) (all } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ShareMountTargetsPager) GetNext() (page []ShareMountTarget, err error) { +func (pager *SecurityGroupsPager) GetNext() (page []SecurityGroup, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ShareMountTargetsPager) GetAll() (allItems []ShareMountTarget, err error) { +func (pager *SecurityGroupsPager) GetAll() (allItems []SecurityGroup, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ShareSnapshotsPager can be used to simplify the use of the "ListShareSnapshots" method. -type ShareSnapshotsPager struct { +// SecurityGroupTargetsPager can be used to simplify the use of the "ListSecurityGroupTargets" method. +type SecurityGroupTargetsPager struct { hasNext bool - options *ListShareSnapshotsOptions + options *ListSecurityGroupTargetsOptions client *VpcV1 pageContext struct { next *string } } -// NewShareSnapshotsPager returns a new ShareSnapshotsPager instance. -func (vpc *VpcV1) NewShareSnapshotsPager(options *ListShareSnapshotsOptions) (pager *ShareSnapshotsPager, err error) { +// NewSecurityGroupTargetsPager returns a new SecurityGroupTargetsPager instance. +func (vpc *VpcV1) NewSecurityGroupTargetsPager(options *ListSecurityGroupTargetsOptions) (pager *SecurityGroupTargetsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListShareSnapshotsOptions = *options - pager = &ShareSnapshotsPager{ + var optionsCopy ListSecurityGroupTargetsOptions = *options + pager = &SecurityGroupTargetsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152628,19 +156227,19 @@ func (vpc *VpcV1) NewShareSnapshotsPager(options *ListShareSnapshotsOptions) (pa } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ShareSnapshotsPager) HasNext() bool { +func (pager *SecurityGroupTargetsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ShareSnapshotsPager) GetNextWithContext(ctx context.Context) (page []ShareSnapshot, err error) { +func (pager *SecurityGroupTargetsPager) GetNextWithContext(ctx context.Context) (page []SecurityGroupTargetReferenceIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListShareSnapshotsWithContext(ctx, pager.options) + result, _, err := pager.client.ListSecurityGroupTargetsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152659,16 +156258,16 @@ func (pager *ShareSnapshotsPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Snapshots + page = result.Targets return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ShareSnapshotsPager) GetAllWithContext(ctx context.Context) (allItems []ShareSnapshot, err error) { +func (pager *SecurityGroupTargetsPager) GetAllWithContext(ctx context.Context) (allItems []SecurityGroupTargetReferenceIntf, err error) { for pager.HasNext() { - var nextPage []ShareSnapshot + var nextPage []SecurityGroupTargetReferenceIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152680,38 +156279,38 @@ func (pager *ShareSnapshotsPager) GetAllWithContext(ctx context.Context) (allIte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ShareSnapshotsPager) GetNext() (page []ShareSnapshot, err error) { +func (pager *SecurityGroupTargetsPager) GetNext() (page []SecurityGroupTargetReferenceIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ShareSnapshotsPager) GetAll() (allItems []ShareSnapshot, err error) { +func (pager *SecurityGroupTargetsPager) GetAll() (allItems []SecurityGroupTargetReferenceIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// BackupPoliciesPager can be used to simplify the use of the "ListBackupPolicies" method. -type BackupPoliciesPager struct { +// ShareProfilesPager can be used to simplify the use of the "ListShareProfiles" method. +type ShareProfilesPager struct { hasNext bool - options *ListBackupPoliciesOptions + options *ListShareProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewBackupPoliciesPager returns a new BackupPoliciesPager instance. -func (vpc *VpcV1) NewBackupPoliciesPager(options *ListBackupPoliciesOptions) (pager *BackupPoliciesPager, err error) { +// NewShareProfilesPager returns a new ShareProfilesPager instance. +func (vpc *VpcV1) NewShareProfilesPager(options *ListShareProfilesOptions) (pager *ShareProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListBackupPoliciesOptions = *options - pager = &BackupPoliciesPager{ + var optionsCopy ListShareProfilesOptions = *options + pager = &ShareProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152720,19 +156319,19 @@ func (vpc *VpcV1) NewBackupPoliciesPager(options *ListBackupPoliciesOptions) (pa } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *BackupPoliciesPager) HasNext() bool { +func (pager *ShareProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *BackupPoliciesPager) GetNextWithContext(ctx context.Context) (page []BackupPolicyIntf, err error) { +func (pager *ShareProfilesPager) GetNextWithContext(ctx context.Context) (page []ShareProfile, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListBackupPoliciesWithContext(ctx, pager.options) + result, _, err := pager.client.ListShareProfilesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152751,16 +156350,16 @@ func (pager *BackupPoliciesPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.BackupPolicies + page = result.Profiles return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *BackupPoliciesPager) GetAllWithContext(ctx context.Context) (allItems []BackupPolicyIntf, err error) { +func (pager *ShareProfilesPager) GetAllWithContext(ctx context.Context) (allItems []ShareProfile, err error) { for pager.HasNext() { - var nextPage []BackupPolicyIntf + var nextPage []ShareProfile nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152772,38 +156371,38 @@ func (pager *BackupPoliciesPager) GetAllWithContext(ctx context.Context) (allIte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *BackupPoliciesPager) GetNext() (page []BackupPolicyIntf, err error) { +func (pager *ShareProfilesPager) GetNext() (page []ShareProfile, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *BackupPoliciesPager) GetAll() (allItems []BackupPolicyIntf, err error) { +func (pager *ShareProfilesPager) GetAll() (allItems []ShareProfile, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// BackupPolicyJobsPager can be used to simplify the use of the "ListBackupPolicyJobs" method. -type BackupPolicyJobsPager struct { +// SharesPager can be used to simplify the use of the "ListShares" method. +type SharesPager struct { hasNext bool - options *ListBackupPolicyJobsOptions + options *ListSharesOptions client *VpcV1 pageContext struct { next *string } } -// NewBackupPolicyJobsPager returns a new BackupPolicyJobsPager instance. -func (vpc *VpcV1) NewBackupPolicyJobsPager(options *ListBackupPolicyJobsOptions) (pager *BackupPolicyJobsPager, err error) { +// NewSharesPager returns a new SharesPager instance. +func (vpc *VpcV1) NewSharesPager(options *ListSharesOptions) (pager *SharesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListBackupPolicyJobsOptions = *options - pager = &BackupPolicyJobsPager{ + var optionsCopy ListSharesOptions = *options + pager = &SharesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152812,19 +156411,19 @@ func (vpc *VpcV1) NewBackupPolicyJobsPager(options *ListBackupPolicyJobsOptions) } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *BackupPolicyJobsPager) HasNext() bool { +func (pager *SharesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *BackupPolicyJobsPager) GetNextWithContext(ctx context.Context) (page []BackupPolicyJob, err error) { +func (pager *SharesPager) GetNextWithContext(ctx context.Context) (page []Share, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListBackupPolicyJobsWithContext(ctx, pager.options) + result, _, err := pager.client.ListSharesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152843,16 +156442,16 @@ func (pager *BackupPolicyJobsPager) GetNextWithContext(ctx context.Context) (pag } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Jobs + page = result.Shares return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *BackupPolicyJobsPager) GetAllWithContext(ctx context.Context) (allItems []BackupPolicyJob, err error) { +func (pager *SharesPager) GetAllWithContext(ctx context.Context) (allItems []Share, err error) { for pager.HasNext() { - var nextPage []BackupPolicyJob + var nextPage []Share nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152864,38 +156463,38 @@ func (pager *BackupPolicyJobsPager) GetAllWithContext(ctx context.Context) (allI } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *BackupPolicyJobsPager) GetNext() (page []BackupPolicyJob, err error) { +func (pager *SharesPager) GetNext() (page []Share, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *BackupPolicyJobsPager) GetAll() (allItems []BackupPolicyJob, err error) { +func (pager *SharesPager) GetAll() (allItems []Share, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VirtualNetworkInterfacesPager can be used to simplify the use of the "ListVirtualNetworkInterfaces" method. -type VirtualNetworkInterfacesPager struct { +// ShareAccessorBindingsPager can be used to simplify the use of the "ListShareAccessorBindings" method. +type ShareAccessorBindingsPager struct { hasNext bool - options *ListVirtualNetworkInterfacesOptions + options *ListShareAccessorBindingsOptions client *VpcV1 pageContext struct { next *string } } -// NewVirtualNetworkInterfacesPager returns a new VirtualNetworkInterfacesPager instance. -func (vpc *VpcV1) NewVirtualNetworkInterfacesPager(options *ListVirtualNetworkInterfacesOptions) (pager *VirtualNetworkInterfacesPager, err error) { +// NewShareAccessorBindingsPager returns a new ShareAccessorBindingsPager instance. +func (vpc *VpcV1) NewShareAccessorBindingsPager(options *ListShareAccessorBindingsOptions) (pager *ShareAccessorBindingsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVirtualNetworkInterfacesOptions = *options - pager = &VirtualNetworkInterfacesPager{ + var optionsCopy ListShareAccessorBindingsOptions = *options + pager = &ShareAccessorBindingsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152904,19 +156503,19 @@ func (vpc *VpcV1) NewVirtualNetworkInterfacesPager(options *ListVirtualNetworkIn } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VirtualNetworkInterfacesPager) HasNext() bool { +func (pager *ShareAccessorBindingsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VirtualNetworkInterfacesPager) GetNextWithContext(ctx context.Context) (page []VirtualNetworkInterface, err error) { +func (pager *ShareAccessorBindingsPager) GetNextWithContext(ctx context.Context) (page []ShareAccessorBinding, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVirtualNetworkInterfacesWithContext(ctx, pager.options) + result, _, err := pager.client.ListShareAccessorBindingsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -152935,16 +156534,16 @@ func (pager *VirtualNetworkInterfacesPager) GetNextWithContext(ctx context.Conte } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.VirtualNetworkInterfaces + page = result.AccessorBindings return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VirtualNetworkInterfacesPager) GetAllWithContext(ctx context.Context) (allItems []VirtualNetworkInterface, err error) { +func (pager *ShareAccessorBindingsPager) GetAllWithContext(ctx context.Context) (allItems []ShareAccessorBinding, err error) { for pager.HasNext() { - var nextPage []VirtualNetworkInterface + var nextPage []ShareAccessorBinding nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -152956,38 +156555,38 @@ func (pager *VirtualNetworkInterfacesPager) GetAllWithContext(ctx context.Contex } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VirtualNetworkInterfacesPager) GetNext() (page []VirtualNetworkInterface, err error) { +func (pager *ShareAccessorBindingsPager) GetNext() (page []ShareAccessorBinding, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VirtualNetworkInterfacesPager) GetAll() (allItems []VirtualNetworkInterface, err error) { +func (pager *ShareAccessorBindingsPager) GetAll() (allItems []ShareAccessorBinding, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// NetworkInterfaceFloatingIpsPager can be used to simplify the use of the "ListNetworkInterfaceFloatingIps" method. -type NetworkInterfaceFloatingIpsPager struct { +// ShareMountTargetsPager can be used to simplify the use of the "ListShareMountTargets" method. +type ShareMountTargetsPager struct { hasNext bool - options *ListNetworkInterfaceFloatingIpsOptions + options *ListShareMountTargetsOptions client *VpcV1 pageContext struct { next *string } } -// NewNetworkInterfaceFloatingIpsPager returns a new NetworkInterfaceFloatingIpsPager instance. -func (vpc *VpcV1) NewNetworkInterfaceFloatingIpsPager(options *ListNetworkInterfaceFloatingIpsOptions) (pager *NetworkInterfaceFloatingIpsPager, err error) { +// NewShareMountTargetsPager returns a new ShareMountTargetsPager instance. +func (vpc *VpcV1) NewShareMountTargetsPager(options *ListShareMountTargetsOptions) (pager *ShareMountTargetsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListNetworkInterfaceFloatingIpsOptions = *options - pager = &NetworkInterfaceFloatingIpsPager{ + var optionsCopy ListShareMountTargetsOptions = *options + pager = &ShareMountTargetsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -152996,19 +156595,19 @@ func (vpc *VpcV1) NewNetworkInterfaceFloatingIpsPager(options *ListNetworkInterf } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *NetworkInterfaceFloatingIpsPager) HasNext() bool { +func (pager *ShareMountTargetsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *NetworkInterfaceFloatingIpsPager) GetNextWithContext(ctx context.Context) (page []FloatingIPReference, err error) { +func (pager *ShareMountTargetsPager) GetNextWithContext(ctx context.Context) (page []ShareMountTarget, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListNetworkInterfaceFloatingIpsWithContext(ctx, pager.options) + result, _, err := pager.client.ListShareMountTargetsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153027,16 +156626,16 @@ func (pager *NetworkInterfaceFloatingIpsPager) GetNextWithContext(ctx context.Co } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.FloatingIps + page = result.MountTargets return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *NetworkInterfaceFloatingIpsPager) GetAllWithContext(ctx context.Context) (allItems []FloatingIPReference, err error) { +func (pager *ShareMountTargetsPager) GetAllWithContext(ctx context.Context) (allItems []ShareMountTarget, err error) { for pager.HasNext() { - var nextPage []FloatingIPReference + var nextPage []ShareMountTarget nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153048,38 +156647,38 @@ func (pager *NetworkInterfaceFloatingIpsPager) GetAllWithContext(ctx context.Con } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *NetworkInterfaceFloatingIpsPager) GetNext() (page []FloatingIPReference, err error) { +func (pager *ShareMountTargetsPager) GetNext() (page []ShareMountTarget, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *NetworkInterfaceFloatingIpsPager) GetAll() (allItems []FloatingIPReference, err error) { +func (pager *ShareMountTargetsPager) GetAll() (allItems []ShareMountTarget, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VirtualNetworkInterfaceIpsPager can be used to simplify the use of the "ListVirtualNetworkInterfaceIps" method. -type VirtualNetworkInterfaceIpsPager struct { +// ShareSnapshotsPager can be used to simplify the use of the "ListShareSnapshots" method. +type ShareSnapshotsPager struct { hasNext bool - options *ListVirtualNetworkInterfaceIpsOptions + options *ListShareSnapshotsOptions client *VpcV1 pageContext struct { next *string } } -// NewVirtualNetworkInterfaceIpsPager returns a new VirtualNetworkInterfaceIpsPager instance. -func (vpc *VpcV1) NewVirtualNetworkInterfaceIpsPager(options *ListVirtualNetworkInterfaceIpsOptions) (pager *VirtualNetworkInterfaceIpsPager, err error) { +// NewShareSnapshotsPager returns a new ShareSnapshotsPager instance. +func (vpc *VpcV1) NewShareSnapshotsPager(options *ListShareSnapshotsOptions) (pager *ShareSnapshotsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVirtualNetworkInterfaceIpsOptions = *options - pager = &VirtualNetworkInterfaceIpsPager{ + var optionsCopy ListShareSnapshotsOptions = *options + pager = &ShareSnapshotsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -153088,19 +156687,19 @@ func (vpc *VpcV1) NewVirtualNetworkInterfaceIpsPager(options *ListVirtualNetwork } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VirtualNetworkInterfaceIpsPager) HasNext() bool { +func (pager *ShareSnapshotsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VirtualNetworkInterfaceIpsPager) GetNextWithContext(ctx context.Context) (page []ReservedIPReference, err error) { +func (pager *ShareSnapshotsPager) GetNextWithContext(ctx context.Context) (page []ShareSnapshot, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVirtualNetworkInterfaceIpsWithContext(ctx, pager.options) + result, _, err := pager.client.ListShareSnapshotsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153119,16 +156718,16 @@ func (pager *VirtualNetworkInterfaceIpsPager) GetNextWithContext(ctx context.Con } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Ips + page = result.Snapshots return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VirtualNetworkInterfaceIpsPager) GetAllWithContext(ctx context.Context) (allItems []ReservedIPReference, err error) { +func (pager *ShareSnapshotsPager) GetAllWithContext(ctx context.Context) (allItems []ShareSnapshot, err error) { for pager.HasNext() { - var nextPage []ReservedIPReference + var nextPage []ShareSnapshot nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153140,38 +156739,38 @@ func (pager *VirtualNetworkInterfaceIpsPager) GetAllWithContext(ctx context.Cont } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VirtualNetworkInterfaceIpsPager) GetNext() (page []ReservedIPReference, err error) { +func (pager *ShareSnapshotsPager) GetNext() (page []ShareSnapshot, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VirtualNetworkInterfaceIpsPager) GetAll() (allItems []ReservedIPReference, err error) { +func (pager *ShareSnapshotsPager) GetAll() (allItems []ShareSnapshot, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ClusterNetworkProfilesPager can be used to simplify the use of the "ListClusterNetworkProfiles" method. -type ClusterNetworkProfilesPager struct { +// SnapshotConsistencyGroupsPager can be used to simplify the use of the "ListSnapshotConsistencyGroups" method. +type SnapshotConsistencyGroupsPager struct { hasNext bool - options *ListClusterNetworkProfilesOptions + options *ListSnapshotConsistencyGroupsOptions client *VpcV1 pageContext struct { next *string } } -// NewClusterNetworkProfilesPager returns a new ClusterNetworkProfilesPager instance. -func (vpc *VpcV1) NewClusterNetworkProfilesPager(options *ListClusterNetworkProfilesOptions) (pager *ClusterNetworkProfilesPager, err error) { +// NewSnapshotConsistencyGroupsPager returns a new SnapshotConsistencyGroupsPager instance. +func (vpc *VpcV1) NewSnapshotConsistencyGroupsPager(options *ListSnapshotConsistencyGroupsOptions) (pager *SnapshotConsistencyGroupsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListClusterNetworkProfilesOptions = *options - pager = &ClusterNetworkProfilesPager{ + var optionsCopy ListSnapshotConsistencyGroupsOptions = *options + pager = &SnapshotConsistencyGroupsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -153180,19 +156779,19 @@ func (vpc *VpcV1) NewClusterNetworkProfilesPager(options *ListClusterNetworkProf } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ClusterNetworkProfilesPager) HasNext() bool { +func (pager *SnapshotConsistencyGroupsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ClusterNetworkProfilesPager) GetNextWithContext(ctx context.Context) (page []ClusterNetworkProfile, err error) { +func (pager *SnapshotConsistencyGroupsPager) GetNextWithContext(ctx context.Context) (page []SnapshotConsistencyGroup, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListClusterNetworkProfilesWithContext(ctx, pager.options) + result, _, err := pager.client.ListSnapshotConsistencyGroupsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153211,16 +156810,16 @@ func (pager *ClusterNetworkProfilesPager) GetNextWithContext(ctx context.Context } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Profiles + page = result.SnapshotConsistencyGroups return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ClusterNetworkProfilesPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetworkProfile, err error) { +func (pager *SnapshotConsistencyGroupsPager) GetAllWithContext(ctx context.Context) (allItems []SnapshotConsistencyGroup, err error) { for pager.HasNext() { - var nextPage []ClusterNetworkProfile + var nextPage []SnapshotConsistencyGroup nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153232,38 +156831,38 @@ func (pager *ClusterNetworkProfilesPager) GetAllWithContext(ctx context.Context) } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworkProfilesPager) GetNext() (page []ClusterNetworkProfile, err error) { +func (pager *SnapshotConsistencyGroupsPager) GetNext() (page []SnapshotConsistencyGroup, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworkProfilesPager) GetAll() (allItems []ClusterNetworkProfile, err error) { +func (pager *SnapshotConsistencyGroupsPager) GetAll() (allItems []SnapshotConsistencyGroup, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ClusterNetworksPager can be used to simplify the use of the "ListClusterNetworks" method. -type ClusterNetworksPager struct { +// SnapshotsPager can be used to simplify the use of the "ListSnapshots" method. +type SnapshotsPager struct { hasNext bool - options *ListClusterNetworksOptions + options *ListSnapshotsOptions client *VpcV1 pageContext struct { next *string } } -// NewClusterNetworksPager returns a new ClusterNetworksPager instance. -func (vpc *VpcV1) NewClusterNetworksPager(options *ListClusterNetworksOptions) (pager *ClusterNetworksPager, err error) { +// NewSnapshotsPager returns a new SnapshotsPager instance. +func (vpc *VpcV1) NewSnapshotsPager(options *ListSnapshotsOptions) (pager *SnapshotsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListClusterNetworksOptions = *options - pager = &ClusterNetworksPager{ + var optionsCopy ListSnapshotsOptions = *options + pager = &SnapshotsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -153272,19 +156871,19 @@ func (vpc *VpcV1) NewClusterNetworksPager(options *ListClusterNetworksOptions) ( } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ClusterNetworksPager) HasNext() bool { +func (pager *SnapshotsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ClusterNetworksPager) GetNextWithContext(ctx context.Context) (page []ClusterNetwork, err error) { +func (pager *SnapshotsPager) GetNextWithContext(ctx context.Context) (page []Snapshot, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListClusterNetworksWithContext(ctx, pager.options) + result, _, err := pager.client.ListSnapshotsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153303,16 +156902,16 @@ func (pager *ClusterNetworksPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.ClusterNetworks + page = result.Snapshots return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ClusterNetworksPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetwork, err error) { +func (pager *SnapshotsPager) GetAllWithContext(ctx context.Context) (allItems []Snapshot, err error) { for pager.HasNext() { - var nextPage []ClusterNetwork + var nextPage []Snapshot nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153324,38 +156923,38 @@ func (pager *ClusterNetworksPager) GetAllWithContext(ctx context.Context) (allIt } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworksPager) GetNext() (page []ClusterNetwork, err error) { +func (pager *SnapshotsPager) GetNext() (page []Snapshot, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworksPager) GetAll() (allItems []ClusterNetwork, err error) { +func (pager *SnapshotsPager) GetAll() (allItems []Snapshot, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ClusterNetworkInterfacesPager can be used to simplify the use of the "ListClusterNetworkInterfaces" method. -type ClusterNetworkInterfacesPager struct { +// SnapshotInstanceProfilesPager can be used to simplify the use of the "ListSnapshotInstanceProfiles" method. +type SnapshotInstanceProfilesPager struct { hasNext bool - options *ListClusterNetworkInterfacesOptions + options *ListSnapshotInstanceProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewClusterNetworkInterfacesPager returns a new ClusterNetworkInterfacesPager instance. -func (vpc *VpcV1) NewClusterNetworkInterfacesPager(options *ListClusterNetworkInterfacesOptions) (pager *ClusterNetworkInterfacesPager, err error) { +// NewSnapshotInstanceProfilesPager returns a new SnapshotInstanceProfilesPager instance. +func (vpc *VpcV1) NewSnapshotInstanceProfilesPager(options *ListSnapshotInstanceProfilesOptions) (pager *SnapshotInstanceProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListClusterNetworkInterfacesOptions = *options - pager = &ClusterNetworkInterfacesPager{ + var optionsCopy ListSnapshotInstanceProfilesOptions = *options + pager = &SnapshotInstanceProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -153364,19 +156963,19 @@ func (vpc *VpcV1) NewClusterNetworkInterfacesPager(options *ListClusterNetworkIn } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ClusterNetworkInterfacesPager) HasNext() bool { +func (pager *SnapshotInstanceProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ClusterNetworkInterfacesPager) GetNextWithContext(ctx context.Context) (page []ClusterNetworkInterface, err error) { +func (pager *SnapshotInstanceProfilesPager) GetNextWithContext(ctx context.Context) (page []InstanceProfileReference, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListClusterNetworkInterfacesWithContext(ctx, pager.options) + result, _, err := pager.client.ListSnapshotInstanceProfilesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153395,16 +156994,16 @@ func (pager *ClusterNetworkInterfacesPager) GetNextWithContext(ctx context.Conte } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Interfaces + page = result.InstanceProfiles return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ClusterNetworkInterfacesPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetworkInterface, err error) { +func (pager *SnapshotInstanceProfilesPager) GetAllWithContext(ctx context.Context) (allItems []InstanceProfileReference, err error) { for pager.HasNext() { - var nextPage []ClusterNetworkInterface + var nextPage []InstanceProfileReference nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153416,38 +157015,38 @@ func (pager *ClusterNetworkInterfacesPager) GetAllWithContext(ctx context.Contex } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworkInterfacesPager) GetNext() (page []ClusterNetworkInterface, err error) { +func (pager *SnapshotInstanceProfilesPager) GetNext() (page []InstanceProfileReference, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworkInterfacesPager) GetAll() (allItems []ClusterNetworkInterface, err error) { +func (pager *SnapshotInstanceProfilesPager) GetAll() (allItems []InstanceProfileReference, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ClusterNetworkSubnetsPager can be used to simplify the use of the "ListClusterNetworkSubnets" method. -type ClusterNetworkSubnetsPager struct { +// SubnetsPager can be used to simplify the use of the "ListSubnets" method. +type SubnetsPager struct { hasNext bool - options *ListClusterNetworkSubnetsOptions + options *ListSubnetsOptions client *VpcV1 pageContext struct { next *string } } -// NewClusterNetworkSubnetsPager returns a new ClusterNetworkSubnetsPager instance. -func (vpc *VpcV1) NewClusterNetworkSubnetsPager(options *ListClusterNetworkSubnetsOptions) (pager *ClusterNetworkSubnetsPager, err error) { +// NewSubnetsPager returns a new SubnetsPager instance. +func (vpc *VpcV1) NewSubnetsPager(options *ListSubnetsOptions) (pager *SubnetsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListClusterNetworkSubnetsOptions = *options - pager = &ClusterNetworkSubnetsPager{ + var optionsCopy ListSubnetsOptions = *options + pager = &SubnetsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -153456,19 +157055,19 @@ func (vpc *VpcV1) NewClusterNetworkSubnetsPager(options *ListClusterNetworkSubne } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ClusterNetworkSubnetsPager) HasNext() bool { +func (pager *SubnetsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ClusterNetworkSubnetsPager) GetNextWithContext(ctx context.Context) (page []ClusterNetworkSubnet, err error) { +func (pager *SubnetsPager) GetNextWithContext(ctx context.Context) (page []Subnet, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListClusterNetworkSubnetsWithContext(ctx, pager.options) + result, _, err := pager.client.ListSubnetsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153494,9 +157093,9 @@ func (pager *ClusterNetworkSubnetsPager) GetNextWithContext(ctx context.Context) // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ClusterNetworkSubnetsPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetworkSubnet, err error) { +func (pager *SubnetsPager) GetAllWithContext(ctx context.Context) (allItems []Subnet, err error) { for pager.HasNext() { - var nextPage []ClusterNetworkSubnet + var nextPage []Subnet nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153508,38 +157107,38 @@ func (pager *ClusterNetworkSubnetsPager) GetAllWithContext(ctx context.Context) } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworkSubnetsPager) GetNext() (page []ClusterNetworkSubnet, err error) { +func (pager *SubnetsPager) GetNext() (page []Subnet, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworkSubnetsPager) GetAll() (allItems []ClusterNetworkSubnet, err error) { +func (pager *SubnetsPager) GetAll() (allItems []Subnet, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// ClusterNetworkSubnetReservedIpsPager can be used to simplify the use of the "ListClusterNetworkSubnetReservedIps" method. -type ClusterNetworkSubnetReservedIpsPager struct { +// SubnetReservedIpsPager can be used to simplify the use of the "ListSubnetReservedIps" method. +type SubnetReservedIpsPager struct { hasNext bool - options *ListClusterNetworkSubnetReservedIpsOptions + options *ListSubnetReservedIpsOptions client *VpcV1 pageContext struct { next *string } } -// NewClusterNetworkSubnetReservedIpsPager returns a new ClusterNetworkSubnetReservedIpsPager instance. -func (vpc *VpcV1) NewClusterNetworkSubnetReservedIpsPager(options *ListClusterNetworkSubnetReservedIpsOptions) (pager *ClusterNetworkSubnetReservedIpsPager, err error) { +// NewSubnetReservedIpsPager returns a new SubnetReservedIpsPager instance. +func (vpc *VpcV1) NewSubnetReservedIpsPager(options *ListSubnetReservedIpsOptions) (pager *SubnetReservedIpsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListClusterNetworkSubnetReservedIpsOptions = *options - pager = &ClusterNetworkSubnetReservedIpsPager{ + var optionsCopy ListSubnetReservedIpsOptions = *options + pager = &SubnetReservedIpsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -153548,19 +157147,19 @@ func (vpc *VpcV1) NewClusterNetworkSubnetReservedIpsPager(options *ListClusterNe } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *ClusterNetworkSubnetReservedIpsPager) HasNext() bool { +func (pager *SubnetReservedIpsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *ClusterNetworkSubnetReservedIpsPager) GetNextWithContext(ctx context.Context) (page []ClusterNetworkSubnetReservedIP, err error) { +func (pager *SubnetReservedIpsPager) GetNextWithContext(ctx context.Context) (page []ReservedIP, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListClusterNetworkSubnetReservedIpsWithContext(ctx, pager.options) + result, _, err := pager.client.ListSubnetReservedIpsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153586,9 +157185,9 @@ func (pager *ClusterNetworkSubnetReservedIpsPager) GetNextWithContext(ctx contex // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *ClusterNetworkSubnetReservedIpsPager) GetAllWithContext(ctx context.Context) (allItems []ClusterNetworkSubnetReservedIP, err error) { +func (pager *SubnetReservedIpsPager) GetAllWithContext(ctx context.Context) (allItems []ReservedIP, err error) { for pager.HasNext() { - var nextPage []ClusterNetworkSubnetReservedIP + var nextPage []ReservedIP nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153600,38 +157199,38 @@ func (pager *ClusterNetworkSubnetReservedIpsPager) GetAllWithContext(ctx context } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworkSubnetReservedIpsPager) GetNext() (page []ClusterNetworkSubnetReservedIP, err error) { +func (pager *SubnetReservedIpsPager) GetNext() (page []ReservedIP, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *ClusterNetworkSubnetReservedIpsPager) GetAll() (allItems []ClusterNetworkSubnetReservedIP, err error) { +func (pager *SubnetReservedIpsPager) GetAll() (allItems []ReservedIP, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// PublicGatewaysPager can be used to simplify the use of the "ListPublicGateways" method. -type PublicGatewaysPager struct { +// VirtualNetworkInterfacesPager can be used to simplify the use of the "ListVirtualNetworkInterfaces" method. +type VirtualNetworkInterfacesPager struct { hasNext bool - options *ListPublicGatewaysOptions + options *ListVirtualNetworkInterfacesOptions client *VpcV1 pageContext struct { next *string } } -// NewPublicGatewaysPager returns a new PublicGatewaysPager instance. -func (vpc *VpcV1) NewPublicGatewaysPager(options *ListPublicGatewaysOptions) (pager *PublicGatewaysPager, err error) { +// NewVirtualNetworkInterfacesPager returns a new VirtualNetworkInterfacesPager instance. +func (vpc *VpcV1) NewVirtualNetworkInterfacesPager(options *ListVirtualNetworkInterfacesOptions) (pager *VirtualNetworkInterfacesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListPublicGatewaysOptions = *options - pager = &PublicGatewaysPager{ + var optionsCopy ListVirtualNetworkInterfacesOptions = *options + pager = &VirtualNetworkInterfacesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -153640,19 +157239,19 @@ func (vpc *VpcV1) NewPublicGatewaysPager(options *ListPublicGatewaysOptions) (pa } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *PublicGatewaysPager) HasNext() bool { +func (pager *VirtualNetworkInterfacesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *PublicGatewaysPager) GetNextWithContext(ctx context.Context) (page []PublicGateway, err error) { +func (pager *VirtualNetworkInterfacesPager) GetNextWithContext(ctx context.Context) (page []VirtualNetworkInterface, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListPublicGatewaysWithContext(ctx, pager.options) + result, _, err := pager.client.ListVirtualNetworkInterfacesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153671,16 +157270,16 @@ func (pager *PublicGatewaysPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.PublicGateways + page = result.VirtualNetworkInterfaces return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *PublicGatewaysPager) GetAllWithContext(ctx context.Context) (allItems []PublicGateway, err error) { +func (pager *VirtualNetworkInterfacesPager) GetAllWithContext(ctx context.Context) (allItems []VirtualNetworkInterface, err error) { for pager.HasNext() { - var nextPage []PublicGateway + var nextPage []VirtualNetworkInterface nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153692,38 +157291,38 @@ func (pager *PublicGatewaysPager) GetAllWithContext(ctx context.Context) (allIte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *PublicGatewaysPager) GetNext() (page []PublicGateway, err error) { +func (pager *VirtualNetworkInterfacesPager) GetNext() (page []VirtualNetworkInterface, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *PublicGatewaysPager) GetAll() (allItems []PublicGateway, err error) { +func (pager *VirtualNetworkInterfacesPager) GetAll() (allItems []VirtualNetworkInterface, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// FloatingIpsPager can be used to simplify the use of the "ListFloatingIps" method. -type FloatingIpsPager struct { +// NetworkInterfaceFloatingIpsPager can be used to simplify the use of the "ListNetworkInterfaceFloatingIps" method. +type NetworkInterfaceFloatingIpsPager struct { hasNext bool - options *ListFloatingIpsOptions + options *ListNetworkInterfaceFloatingIpsOptions client *VpcV1 pageContext struct { next *string } } -// NewFloatingIpsPager returns a new FloatingIpsPager instance. -func (vpc *VpcV1) NewFloatingIpsPager(options *ListFloatingIpsOptions) (pager *FloatingIpsPager, err error) { +// NewNetworkInterfaceFloatingIpsPager returns a new NetworkInterfaceFloatingIpsPager instance. +func (vpc *VpcV1) NewNetworkInterfaceFloatingIpsPager(options *ListNetworkInterfaceFloatingIpsOptions) (pager *NetworkInterfaceFloatingIpsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListFloatingIpsOptions = *options - pager = &FloatingIpsPager{ + var optionsCopy ListNetworkInterfaceFloatingIpsOptions = *options + pager = &NetworkInterfaceFloatingIpsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -153732,19 +157331,19 @@ func (vpc *VpcV1) NewFloatingIpsPager(options *ListFloatingIpsOptions) (pager *F } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *FloatingIpsPager) HasNext() bool { +func (pager *NetworkInterfaceFloatingIpsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *FloatingIpsPager) GetNextWithContext(ctx context.Context) (page []FloatingIP, err error) { +func (pager *NetworkInterfaceFloatingIpsPager) GetNextWithContext(ctx context.Context) (page []FloatingIPReference, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListFloatingIpsWithContext(ctx, pager.options) + result, _, err := pager.client.ListNetworkInterfaceFloatingIpsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -153770,193 +157369,9 @@ func (pager *FloatingIpsPager) GetNextWithContext(ctx context.Context) (page []F // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *FloatingIpsPager) GetAllWithContext(ctx context.Context) (allItems []FloatingIP, err error) { - for pager.HasNext() { - var nextPage []FloatingIP - nextPage, err = pager.GetNextWithContext(ctx) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - allItems = append(allItems, nextPage...) - } - return -} - -// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *FloatingIpsPager) GetNext() (page []FloatingIP, err error) { - page, err = pager.GetNextWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *FloatingIpsPager) GetAll() (allItems []FloatingIP, err error) { - allItems, err = pager.GetAllWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// NetworkAclsPager can be used to simplify the use of the "ListNetworkAcls" method. -type NetworkAclsPager struct { - hasNext bool - options *ListNetworkAclsOptions - client *VpcV1 - pageContext struct { - next *string - } -} - -// NewNetworkAclsPager returns a new NetworkAclsPager instance. -func (vpc *VpcV1) NewNetworkAclsPager(options *ListNetworkAclsOptions) (pager *NetworkAclsPager, err error) { - if options.Start != nil && *options.Start != "" { - err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) - return - } - - var optionsCopy ListNetworkAclsOptions = *options - pager = &NetworkAclsPager{ - hasNext: true, - options: &optionsCopy, - client: vpc, - } - return -} - -// HasNext returns true if there are potentially more results to be retrieved. -func (pager *NetworkAclsPager) HasNext() bool { - return pager.hasNext -} - -// GetNextWithContext returns the next page of results using the specified Context. -func (pager *NetworkAclsPager) GetNextWithContext(ctx context.Context) (page []NetworkACL, err error) { - if !pager.HasNext() { - return nil, fmt.Errorf("no more results available") - } - - pager.options.Start = pager.pageContext.next - - result, _, err := pager.client.ListNetworkAclsWithContext(ctx, pager.options) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - - var next *string - if result.Next != nil { - var start *string - start, err = core.GetQueryParam(result.Next.Href, "start") - if err != nil { - errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) - err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) - return - } - next = start - } - pager.pageContext.next = next - pager.hasNext = (pager.pageContext.next != nil) - page = result.NetworkAcls - - return -} - -// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly -// until all pages of results have been retrieved. -func (pager *NetworkAclsPager) GetAllWithContext(ctx context.Context) (allItems []NetworkACL, err error) { - for pager.HasNext() { - var nextPage []NetworkACL - nextPage, err = pager.GetNextWithContext(ctx) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - allItems = append(allItems, nextPage...) - } - return -} - -// GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *NetworkAclsPager) GetNext() (page []NetworkACL, err error) { - page, err = pager.GetNextWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *NetworkAclsPager) GetAll() (allItems []NetworkACL, err error) { - allItems, err = pager.GetAllWithContext(context.Background()) - err = core.RepurposeSDKProblem(err, "") - return -} - -// NetworkACLRulesPager can be used to simplify the use of the "ListNetworkACLRules" method. -type NetworkACLRulesPager struct { - hasNext bool - options *ListNetworkACLRulesOptions - client *VpcV1 - pageContext struct { - next *string - } -} - -// NewNetworkACLRulesPager returns a new NetworkACLRulesPager instance. -func (vpc *VpcV1) NewNetworkACLRulesPager(options *ListNetworkACLRulesOptions) (pager *NetworkACLRulesPager, err error) { - if options.Start != nil && *options.Start != "" { - err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) - return - } - - var optionsCopy ListNetworkACLRulesOptions = *options - pager = &NetworkACLRulesPager{ - hasNext: true, - options: &optionsCopy, - client: vpc, - } - return -} - -// HasNext returns true if there are potentially more results to be retrieved. -func (pager *NetworkACLRulesPager) HasNext() bool { - return pager.hasNext -} - -// GetNextWithContext returns the next page of results using the specified Context. -func (pager *NetworkACLRulesPager) GetNextWithContext(ctx context.Context) (page []NetworkACLRuleItemIntf, err error) { - if !pager.HasNext() { - return nil, fmt.Errorf("no more results available") - } - - pager.options.Start = pager.pageContext.next - - result, _, err := pager.client.ListNetworkACLRulesWithContext(ctx, pager.options) - if err != nil { - err = core.RepurposeSDKProblem(err, "error-getting-next-page") - return - } - - var next *string - if result.Next != nil { - var start *string - start, err = core.GetQueryParam(result.Next.Href, "start") - if err != nil { - errMsg := fmt.Sprintf("error retrieving 'start' query parameter from URL '%s': %s", *result.Next.Href, err.Error()) - err = core.SDKErrorf(err, errMsg, "get-query-error", common.GetComponentInfo()) - return - } - next = start - } - pager.pageContext.next = next - pager.hasNext = (pager.pageContext.next != nil) - page = result.Rules - - return -} - -// GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly -// until all pages of results have been retrieved. -func (pager *NetworkACLRulesPager) GetAllWithContext(ctx context.Context) (allItems []NetworkACLRuleItemIntf, err error) { +func (pager *NetworkInterfaceFloatingIpsPager) GetAllWithContext(ctx context.Context) (allItems []FloatingIPReference, err error) { for pager.HasNext() { - var nextPage []NetworkACLRuleItemIntf + var nextPage []FloatingIPReference nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -153968,38 +157383,38 @@ func (pager *NetworkACLRulesPager) GetAllWithContext(ctx context.Context) (allIt } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *NetworkACLRulesPager) GetNext() (page []NetworkACLRuleItemIntf, err error) { +func (pager *NetworkInterfaceFloatingIpsPager) GetNext() (page []FloatingIPReference, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *NetworkACLRulesPager) GetAll() (allItems []NetworkACLRuleItemIntf, err error) { +func (pager *NetworkInterfaceFloatingIpsPager) GetAll() (allItems []FloatingIPReference, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// SecurityGroupsPager can be used to simplify the use of the "ListSecurityGroups" method. -type SecurityGroupsPager struct { +// VirtualNetworkInterfaceIpsPager can be used to simplify the use of the "ListVirtualNetworkInterfaceIps" method. +type VirtualNetworkInterfaceIpsPager struct { hasNext bool - options *ListSecurityGroupsOptions + options *ListVirtualNetworkInterfaceIpsOptions client *VpcV1 pageContext struct { next *string } } -// NewSecurityGroupsPager returns a new SecurityGroupsPager instance. -func (vpc *VpcV1) NewSecurityGroupsPager(options *ListSecurityGroupsOptions) (pager *SecurityGroupsPager, err error) { +// NewVirtualNetworkInterfaceIpsPager returns a new VirtualNetworkInterfaceIpsPager instance. +func (vpc *VpcV1) NewVirtualNetworkInterfaceIpsPager(options *ListVirtualNetworkInterfaceIpsOptions) (pager *VirtualNetworkInterfaceIpsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListSecurityGroupsOptions = *options - pager = &SecurityGroupsPager{ + var optionsCopy ListVirtualNetworkInterfaceIpsOptions = *options + pager = &VirtualNetworkInterfaceIpsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154008,19 +157423,19 @@ func (vpc *VpcV1) NewSecurityGroupsPager(options *ListSecurityGroupsOptions) (pa } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *SecurityGroupsPager) HasNext() bool { +func (pager *VirtualNetworkInterfaceIpsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *SecurityGroupsPager) GetNextWithContext(ctx context.Context) (page []SecurityGroup, err error) { +func (pager *VirtualNetworkInterfaceIpsPager) GetNextWithContext(ctx context.Context) (page []ReservedIPReference, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListSecurityGroupsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVirtualNetworkInterfaceIpsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154039,16 +157454,16 @@ func (pager *SecurityGroupsPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.SecurityGroups + page = result.Ips return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *SecurityGroupsPager) GetAllWithContext(ctx context.Context) (allItems []SecurityGroup, err error) { +func (pager *VirtualNetworkInterfaceIpsPager) GetAllWithContext(ctx context.Context) (allItems []ReservedIPReference, err error) { for pager.HasNext() { - var nextPage []SecurityGroup + var nextPage []ReservedIPReference nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154060,38 +157475,38 @@ func (pager *SecurityGroupsPager) GetAllWithContext(ctx context.Context) (allIte } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *SecurityGroupsPager) GetNext() (page []SecurityGroup, err error) { +func (pager *VirtualNetworkInterfaceIpsPager) GetNext() (page []ReservedIPReference, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *SecurityGroupsPager) GetAll() (allItems []SecurityGroup, err error) { +func (pager *VirtualNetworkInterfaceIpsPager) GetAll() (allItems []ReservedIPReference, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// SecurityGroupTargetsPager can be used to simplify the use of the "ListSecurityGroupTargets" method. -type SecurityGroupTargetsPager struct { +// VolumeProfilesPager can be used to simplify the use of the "ListVolumeProfiles" method. +type VolumeProfilesPager struct { hasNext bool - options *ListSecurityGroupTargetsOptions + options *ListVolumeProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewSecurityGroupTargetsPager returns a new SecurityGroupTargetsPager instance. -func (vpc *VpcV1) NewSecurityGroupTargetsPager(options *ListSecurityGroupTargetsOptions) (pager *SecurityGroupTargetsPager, err error) { +// NewVolumeProfilesPager returns a new VolumeProfilesPager instance. +func (vpc *VpcV1) NewVolumeProfilesPager(options *ListVolumeProfilesOptions) (pager *VolumeProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListSecurityGroupTargetsOptions = *options - pager = &SecurityGroupTargetsPager{ + var optionsCopy ListVolumeProfilesOptions = *options + pager = &VolumeProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154100,19 +157515,19 @@ func (vpc *VpcV1) NewSecurityGroupTargetsPager(options *ListSecurityGroupTargets } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *SecurityGroupTargetsPager) HasNext() bool { +func (pager *VolumeProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *SecurityGroupTargetsPager) GetNextWithContext(ctx context.Context) (page []SecurityGroupTargetReferenceIntf, err error) { +func (pager *VolumeProfilesPager) GetNextWithContext(ctx context.Context) (page []VolumeProfile, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListSecurityGroupTargetsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVolumeProfilesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154131,16 +157546,16 @@ func (pager *SecurityGroupTargetsPager) GetNextWithContext(ctx context.Context) } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Targets + page = result.Profiles return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *SecurityGroupTargetsPager) GetAllWithContext(ctx context.Context) (allItems []SecurityGroupTargetReferenceIntf, err error) { +func (pager *VolumeProfilesPager) GetAllWithContext(ctx context.Context) (allItems []VolumeProfile, err error) { for pager.HasNext() { - var nextPage []SecurityGroupTargetReferenceIntf + var nextPage []VolumeProfile nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154152,38 +157567,38 @@ func (pager *SecurityGroupTargetsPager) GetAllWithContext(ctx context.Context) ( } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *SecurityGroupTargetsPager) GetNext() (page []SecurityGroupTargetReferenceIntf, err error) { +func (pager *VolumeProfilesPager) GetNext() (page []VolumeProfile, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *SecurityGroupTargetsPager) GetAll() (allItems []SecurityGroupTargetReferenceIntf, err error) { +func (pager *VolumeProfilesPager) GetAll() (allItems []VolumeProfile, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// IkePoliciesPager can be used to simplify the use of the "ListIkePolicies" method. -type IkePoliciesPager struct { +// VolumesPager can be used to simplify the use of the "ListVolumes" method. +type VolumesPager struct { hasNext bool - options *ListIkePoliciesOptions + options *ListVolumesOptions client *VpcV1 pageContext struct { next *string } } -// NewIkePoliciesPager returns a new IkePoliciesPager instance. -func (vpc *VpcV1) NewIkePoliciesPager(options *ListIkePoliciesOptions) (pager *IkePoliciesPager, err error) { +// NewVolumesPager returns a new VolumesPager instance. +func (vpc *VpcV1) NewVolumesPager(options *ListVolumesOptions) (pager *VolumesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListIkePoliciesOptions = *options - pager = &IkePoliciesPager{ + var optionsCopy ListVolumesOptions = *options + pager = &VolumesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154192,19 +157607,19 @@ func (vpc *VpcV1) NewIkePoliciesPager(options *ListIkePoliciesOptions) (pager *I } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *IkePoliciesPager) HasNext() bool { +func (pager *VolumesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *IkePoliciesPager) GetNextWithContext(ctx context.Context) (page []IkePolicy, err error) { +func (pager *VolumesPager) GetNextWithContext(ctx context.Context) (page []Volume, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListIkePoliciesWithContext(ctx, pager.options) + result, _, err := pager.client.ListVolumesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154223,16 +157638,16 @@ func (pager *IkePoliciesPager) GetNextWithContext(ctx context.Context) (page []I } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.IkePolicies + page = result.Volumes return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *IkePoliciesPager) GetAllWithContext(ctx context.Context) (allItems []IkePolicy, err error) { +func (pager *VolumesPager) GetAllWithContext(ctx context.Context) (allItems []Volume, err error) { for pager.HasNext() { - var nextPage []IkePolicy + var nextPage []Volume nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154244,38 +157659,38 @@ func (pager *IkePoliciesPager) GetAllWithContext(ctx context.Context) (allItems } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *IkePoliciesPager) GetNext() (page []IkePolicy, err error) { +func (pager *VolumesPager) GetNext() (page []Volume, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *IkePoliciesPager) GetAll() (allItems []IkePolicy, err error) { +func (pager *VolumesPager) GetAll() (allItems []Volume, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// IkePolicyConnectionsPager can be used to simplify the use of the "ListIkePolicyConnections" method. -type IkePolicyConnectionsPager struct { +// VolumeInstanceProfilesPager can be used to simplify the use of the "ListVolumeInstanceProfiles" method. +type VolumeInstanceProfilesPager struct { hasNext bool - options *ListIkePolicyConnectionsOptions + options *ListVolumeInstanceProfilesOptions client *VpcV1 pageContext struct { next *string } } -// NewIkePolicyConnectionsPager returns a new IkePolicyConnectionsPager instance. -func (vpc *VpcV1) NewIkePolicyConnectionsPager(options *ListIkePolicyConnectionsOptions) (pager *IkePolicyConnectionsPager, err error) { +// NewVolumeInstanceProfilesPager returns a new VolumeInstanceProfilesPager instance. +func (vpc *VpcV1) NewVolumeInstanceProfilesPager(options *ListVolumeInstanceProfilesOptions) (pager *VolumeInstanceProfilesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListIkePolicyConnectionsOptions = *options - pager = &IkePolicyConnectionsPager{ + var optionsCopy ListVolumeInstanceProfilesOptions = *options + pager = &VolumeInstanceProfilesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154284,19 +157699,19 @@ func (vpc *VpcV1) NewIkePolicyConnectionsPager(options *ListIkePolicyConnections } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *IkePolicyConnectionsPager) HasNext() bool { +func (pager *VolumeInstanceProfilesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *IkePolicyConnectionsPager) GetNextWithContext(ctx context.Context) (page []VPNGatewayConnectionIntf, err error) { +func (pager *VolumeInstanceProfilesPager) GetNextWithContext(ctx context.Context) (page []InstanceProfileReference, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListIkePolicyConnectionsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVolumeInstanceProfilesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154315,16 +157730,16 @@ func (pager *IkePolicyConnectionsPager) GetNextWithContext(ctx context.Context) } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Connections + page = result.InstanceProfiles return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *IkePolicyConnectionsPager) GetAllWithContext(ctx context.Context) (allItems []VPNGatewayConnectionIntf, err error) { +func (pager *VolumeInstanceProfilesPager) GetAllWithContext(ctx context.Context) (allItems []InstanceProfileReference, err error) { for pager.HasNext() { - var nextPage []VPNGatewayConnectionIntf + var nextPage []InstanceProfileReference nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154336,38 +157751,38 @@ func (pager *IkePolicyConnectionsPager) GetAllWithContext(ctx context.Context) ( } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *IkePolicyConnectionsPager) GetNext() (page []VPNGatewayConnectionIntf, err error) { +func (pager *VolumeInstanceProfilesPager) GetNext() (page []InstanceProfileReference, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *IkePolicyConnectionsPager) GetAll() (allItems []VPNGatewayConnectionIntf, err error) { +func (pager *VolumeInstanceProfilesPager) GetAll() (allItems []InstanceProfileReference, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// IpsecPoliciesPager can be used to simplify the use of the "ListIpsecPolicies" method. -type IpsecPoliciesPager struct { +// VpcsPager can be used to simplify the use of the "ListVpcs" method. +type VpcsPager struct { hasNext bool - options *ListIpsecPoliciesOptions + options *ListVpcsOptions client *VpcV1 pageContext struct { next *string } } -// NewIpsecPoliciesPager returns a new IpsecPoliciesPager instance. -func (vpc *VpcV1) NewIpsecPoliciesPager(options *ListIpsecPoliciesOptions) (pager *IpsecPoliciesPager, err error) { +// NewVpcsPager returns a new VpcsPager instance. +func (vpc *VpcV1) NewVpcsPager(options *ListVpcsOptions) (pager *VpcsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListIpsecPoliciesOptions = *options - pager = &IpsecPoliciesPager{ + var optionsCopy ListVpcsOptions = *options + pager = &VpcsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154376,19 +157791,19 @@ func (vpc *VpcV1) NewIpsecPoliciesPager(options *ListIpsecPoliciesOptions) (page } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *IpsecPoliciesPager) HasNext() bool { +func (pager *VpcsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *IpsecPoliciesPager) GetNextWithContext(ctx context.Context) (page []IPsecPolicy, err error) { +func (pager *VpcsPager) GetNextWithContext(ctx context.Context) (page []VPC, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListIpsecPoliciesWithContext(ctx, pager.options) + result, _, err := pager.client.ListVpcsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154407,16 +157822,16 @@ func (pager *IpsecPoliciesPager) GetNextWithContext(ctx context.Context) (page [ } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.IpsecPolicies + page = result.Vpcs return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *IpsecPoliciesPager) GetAllWithContext(ctx context.Context) (allItems []IPsecPolicy, err error) { +func (pager *VpcsPager) GetAllWithContext(ctx context.Context) (allItems []VPC, err error) { for pager.HasNext() { - var nextPage []IPsecPolicy + var nextPage []VPC nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154428,38 +157843,38 @@ func (pager *IpsecPoliciesPager) GetAllWithContext(ctx context.Context) (allItem } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *IpsecPoliciesPager) GetNext() (page []IPsecPolicy, err error) { +func (pager *VpcsPager) GetNext() (page []VPC, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *IpsecPoliciesPager) GetAll() (allItems []IPsecPolicy, err error) { +func (pager *VpcsPager) GetAll() (allItems []VPC, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// IpsecPolicyConnectionsPager can be used to simplify the use of the "ListIpsecPolicyConnections" method. -type IpsecPolicyConnectionsPager struct { +// VPCAddressPrefixesPager can be used to simplify the use of the "ListVPCAddressPrefixes" method. +type VPCAddressPrefixesPager struct { hasNext bool - options *ListIpsecPolicyConnectionsOptions + options *ListVPCAddressPrefixesOptions client *VpcV1 pageContext struct { next *string } } -// NewIpsecPolicyConnectionsPager returns a new IpsecPolicyConnectionsPager instance. -func (vpc *VpcV1) NewIpsecPolicyConnectionsPager(options *ListIpsecPolicyConnectionsOptions) (pager *IpsecPolicyConnectionsPager, err error) { +// NewVPCAddressPrefixesPager returns a new VPCAddressPrefixesPager instance. +func (vpc *VpcV1) NewVPCAddressPrefixesPager(options *ListVPCAddressPrefixesOptions) (pager *VPCAddressPrefixesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListIpsecPolicyConnectionsOptions = *options - pager = &IpsecPolicyConnectionsPager{ + var optionsCopy ListVPCAddressPrefixesOptions = *options + pager = &VPCAddressPrefixesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154468,19 +157883,19 @@ func (vpc *VpcV1) NewIpsecPolicyConnectionsPager(options *ListIpsecPolicyConnect } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *IpsecPolicyConnectionsPager) HasNext() bool { +func (pager *VPCAddressPrefixesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *IpsecPolicyConnectionsPager) GetNextWithContext(ctx context.Context) (page []VPNGatewayConnectionIntf, err error) { +func (pager *VPCAddressPrefixesPager) GetNextWithContext(ctx context.Context) (page []AddressPrefix, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListIpsecPolicyConnectionsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPCAddressPrefixesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154499,16 +157914,16 @@ func (pager *IpsecPolicyConnectionsPager) GetNextWithContext(ctx context.Context } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Connections + page = result.AddressPrefixes return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *IpsecPolicyConnectionsPager) GetAllWithContext(ctx context.Context) (allItems []VPNGatewayConnectionIntf, err error) { +func (pager *VPCAddressPrefixesPager) GetAllWithContext(ctx context.Context) (allItems []AddressPrefix, err error) { for pager.HasNext() { - var nextPage []VPNGatewayConnectionIntf + var nextPage []AddressPrefix nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154520,38 +157935,38 @@ func (pager *IpsecPolicyConnectionsPager) GetAllWithContext(ctx context.Context) } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *IpsecPolicyConnectionsPager) GetNext() (page []VPNGatewayConnectionIntf, err error) { +func (pager *VPCAddressPrefixesPager) GetNext() (page []AddressPrefix, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *IpsecPolicyConnectionsPager) GetAll() (allItems []VPNGatewayConnectionIntf, err error) { +func (pager *VPCAddressPrefixesPager) GetAll() (allItems []AddressPrefix, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPNGatewaysPager can be used to simplify the use of the "ListVPNGateways" method. -type VPNGatewaysPager struct { +// VPCDnsResolutionBindingsPager can be used to simplify the use of the "ListVPCDnsResolutionBindings" method. +type VPCDnsResolutionBindingsPager struct { hasNext bool - options *ListVPNGatewaysOptions + options *ListVPCDnsResolutionBindingsOptions client *VpcV1 pageContext struct { next *string } } -// NewVPNGatewaysPager returns a new VPNGatewaysPager instance. -func (vpc *VpcV1) NewVPNGatewaysPager(options *ListVPNGatewaysOptions) (pager *VPNGatewaysPager, err error) { +// NewVPCDnsResolutionBindingsPager returns a new VPCDnsResolutionBindingsPager instance. +func (vpc *VpcV1) NewVPCDnsResolutionBindingsPager(options *ListVPCDnsResolutionBindingsOptions) (pager *VPCDnsResolutionBindingsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPNGatewaysOptions = *options - pager = &VPNGatewaysPager{ + var optionsCopy ListVPCDnsResolutionBindingsOptions = *options + pager = &VPCDnsResolutionBindingsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154560,19 +157975,19 @@ func (vpc *VpcV1) NewVPNGatewaysPager(options *ListVPNGatewaysOptions) (pager *V } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPNGatewaysPager) HasNext() bool { +func (pager *VPCDnsResolutionBindingsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPNGatewaysPager) GetNextWithContext(ctx context.Context) (page []VPNGatewayIntf, err error) { +func (pager *VPCDnsResolutionBindingsPager) GetNextWithContext(ctx context.Context) (page []VpcdnsResolutionBinding, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPNGatewaysWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPCDnsResolutionBindingsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154591,16 +158006,16 @@ func (pager *VPNGatewaysPager) GetNextWithContext(ctx context.Context) (page []V } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.VPNGateways + page = result.DnsResolutionBindings return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPNGatewaysPager) GetAllWithContext(ctx context.Context) (allItems []VPNGatewayIntf, err error) { +func (pager *VPCDnsResolutionBindingsPager) GetAllWithContext(ctx context.Context) (allItems []VpcdnsResolutionBinding, err error) { for pager.HasNext() { - var nextPage []VPNGatewayIntf + var nextPage []VpcdnsResolutionBinding nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154612,38 +158027,38 @@ func (pager *VPNGatewaysPager) GetAllWithContext(ctx context.Context) (allItems } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPNGatewaysPager) GetNext() (page []VPNGatewayIntf, err error) { +func (pager *VPCDnsResolutionBindingsPager) GetNext() (page []VpcdnsResolutionBinding, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPNGatewaysPager) GetAll() (allItems []VPNGatewayIntf, err error) { +func (pager *VPCDnsResolutionBindingsPager) GetAll() (allItems []VpcdnsResolutionBinding, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPNGatewayConnectionsPager can be used to simplify the use of the "ListVPNGatewayConnections" method. -type VPNGatewayConnectionsPager struct { +// VPCRoutesPager can be used to simplify the use of the "ListVPCRoutes" method. +type VPCRoutesPager struct { hasNext bool - options *ListVPNGatewayConnectionsOptions + options *ListVPCRoutesOptions client *VpcV1 pageContext struct { next *string } } -// NewVPNGatewayConnectionsPager returns a new VPNGatewayConnectionsPager instance. -func (vpc *VpcV1) NewVPNGatewayConnectionsPager(options *ListVPNGatewayConnectionsOptions) (pager *VPNGatewayConnectionsPager, err error) { +// NewVPCRoutesPager returns a new VPCRoutesPager instance. +func (vpc *VpcV1) NewVPCRoutesPager(options *ListVPCRoutesOptions) (pager *VPCRoutesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPNGatewayConnectionsOptions = *options - pager = &VPNGatewayConnectionsPager{ + var optionsCopy ListVPCRoutesOptions = *options + pager = &VPCRoutesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154652,19 +158067,19 @@ func (vpc *VpcV1) NewVPNGatewayConnectionsPager(options *ListVPNGatewayConnectio } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPNGatewayConnectionsPager) HasNext() bool { +func (pager *VPCRoutesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPNGatewayConnectionsPager) GetNextWithContext(ctx context.Context) (page []VPNGatewayConnectionIntf, err error) { +func (pager *VPCRoutesPager) GetNextWithContext(ctx context.Context) (page []Route, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPNGatewayConnectionsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPCRoutesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154683,16 +158098,16 @@ func (pager *VPNGatewayConnectionsPager) GetNextWithContext(ctx context.Context) } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Connections + page = result.Routes return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPNGatewayConnectionsPager) GetAllWithContext(ctx context.Context) (allItems []VPNGatewayConnectionIntf, err error) { +func (pager *VPCRoutesPager) GetAllWithContext(ctx context.Context) (allItems []Route, err error) { for pager.HasNext() { - var nextPage []VPNGatewayConnectionIntf + var nextPage []Route nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154704,38 +158119,38 @@ func (pager *VPNGatewayConnectionsPager) GetAllWithContext(ctx context.Context) } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPNGatewayConnectionsPager) GetNext() (page []VPNGatewayConnectionIntf, err error) { +func (pager *VPCRoutesPager) GetNext() (page []Route, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPNGatewayConnectionsPager) GetAll() (allItems []VPNGatewayConnectionIntf, err error) { +func (pager *VPCRoutesPager) GetAll() (allItems []Route, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPNServersPager can be used to simplify the use of the "ListVPNServers" method. -type VPNServersPager struct { +// VPCRoutingTablesPager can be used to simplify the use of the "ListVPCRoutingTables" method. +type VPCRoutingTablesPager struct { hasNext bool - options *ListVPNServersOptions + options *ListVPCRoutingTablesOptions client *VpcV1 pageContext struct { next *string } } -// NewVPNServersPager returns a new VPNServersPager instance. -func (vpc *VpcV1) NewVPNServersPager(options *ListVPNServersOptions) (pager *VPNServersPager, err error) { +// NewVPCRoutingTablesPager returns a new VPCRoutingTablesPager instance. +func (vpc *VpcV1) NewVPCRoutingTablesPager(options *ListVPCRoutingTablesOptions) (pager *VPCRoutingTablesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPNServersOptions = *options - pager = &VPNServersPager{ + var optionsCopy ListVPCRoutingTablesOptions = *options + pager = &VPCRoutingTablesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154744,19 +158159,19 @@ func (vpc *VpcV1) NewVPNServersPager(options *ListVPNServersOptions) (pager *VPN } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPNServersPager) HasNext() bool { +func (pager *VPCRoutingTablesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPNServersPager) GetNextWithContext(ctx context.Context) (page []VPNServer, err error) { +func (pager *VPCRoutingTablesPager) GetNextWithContext(ctx context.Context) (page []RoutingTable, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPNServersWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPCRoutingTablesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154775,16 +158190,16 @@ func (pager *VPNServersPager) GetNextWithContext(ctx context.Context) (page []VP } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.VPNServers + page = result.RoutingTables return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPNServersPager) GetAllWithContext(ctx context.Context) (allItems []VPNServer, err error) { +func (pager *VPCRoutingTablesPager) GetAllWithContext(ctx context.Context) (allItems []RoutingTable, err error) { for pager.HasNext() { - var nextPage []VPNServer + var nextPage []RoutingTable nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154796,38 +158211,38 @@ func (pager *VPNServersPager) GetAllWithContext(ctx context.Context) (allItems [ } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPNServersPager) GetNext() (page []VPNServer, err error) { +func (pager *VPCRoutingTablesPager) GetNext() (page []RoutingTable, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPNServersPager) GetAll() (allItems []VPNServer, err error) { +func (pager *VPCRoutingTablesPager) GetAll() (allItems []RoutingTable, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPNServerClientsPager can be used to simplify the use of the "ListVPNServerClients" method. -type VPNServerClientsPager struct { +// VPCRoutingTableRoutesPager can be used to simplify the use of the "ListVPCRoutingTableRoutes" method. +type VPCRoutingTableRoutesPager struct { hasNext bool - options *ListVPNServerClientsOptions + options *ListVPCRoutingTableRoutesOptions client *VpcV1 pageContext struct { next *string } } -// NewVPNServerClientsPager returns a new VPNServerClientsPager instance. -func (vpc *VpcV1) NewVPNServerClientsPager(options *ListVPNServerClientsOptions) (pager *VPNServerClientsPager, err error) { +// NewVPCRoutingTableRoutesPager returns a new VPCRoutingTableRoutesPager instance. +func (vpc *VpcV1) NewVPCRoutingTableRoutesPager(options *ListVPCRoutingTableRoutesOptions) (pager *VPCRoutingTableRoutesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPNServerClientsOptions = *options - pager = &VPNServerClientsPager{ + var optionsCopy ListVPCRoutingTableRoutesOptions = *options + pager = &VPCRoutingTableRoutesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154836,19 +158251,19 @@ func (vpc *VpcV1) NewVPNServerClientsPager(options *ListVPNServerClientsOptions) } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPNServerClientsPager) HasNext() bool { +func (pager *VPCRoutingTableRoutesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPNServerClientsPager) GetNextWithContext(ctx context.Context) (page []VPNServerClient, err error) { +func (pager *VPCRoutingTableRoutesPager) GetNextWithContext(ctx context.Context) (page []Route, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPNServerClientsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPCRoutingTableRoutesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154867,16 +158282,16 @@ func (pager *VPNServerClientsPager) GetNextWithContext(ctx context.Context) (pag } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Clients + page = result.Routes return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPNServerClientsPager) GetAllWithContext(ctx context.Context) (allItems []VPNServerClient, err error) { +func (pager *VPCRoutingTableRoutesPager) GetAllWithContext(ctx context.Context) (allItems []Route, err error) { for pager.HasNext() { - var nextPage []VPNServerClient + var nextPage []Route nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154888,38 +158303,38 @@ func (pager *VPNServerClientsPager) GetAllWithContext(ctx context.Context) (allI } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPNServerClientsPager) GetNext() (page []VPNServerClient, err error) { +func (pager *VPCRoutingTableRoutesPager) GetNext() (page []Route, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPNServerClientsPager) GetAll() (allItems []VPNServerClient, err error) { +func (pager *VPCRoutingTableRoutesPager) GetAll() (allItems []Route, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// VPNServerRoutesPager can be used to simplify the use of the "ListVPNServerRoutes" method. -type VPNServerRoutesPager struct { +// IkePoliciesPager can be used to simplify the use of the "ListIkePolicies" method. +type IkePoliciesPager struct { hasNext bool - options *ListVPNServerRoutesOptions + options *ListIkePoliciesOptions client *VpcV1 pageContext struct { next *string } } -// NewVPNServerRoutesPager returns a new VPNServerRoutesPager instance. -func (vpc *VpcV1) NewVPNServerRoutesPager(options *ListVPNServerRoutesOptions) (pager *VPNServerRoutesPager, err error) { +// NewIkePoliciesPager returns a new IkePoliciesPager instance. +func (vpc *VpcV1) NewIkePoliciesPager(options *ListIkePoliciesOptions) (pager *IkePoliciesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListVPNServerRoutesOptions = *options - pager = &VPNServerRoutesPager{ + var optionsCopy ListIkePoliciesOptions = *options + pager = &IkePoliciesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -154928,19 +158343,19 @@ func (vpc *VpcV1) NewVPNServerRoutesPager(options *ListVPNServerRoutesOptions) ( } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *VPNServerRoutesPager) HasNext() bool { +func (pager *IkePoliciesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *VPNServerRoutesPager) GetNextWithContext(ctx context.Context) (page []VPNServerRoute, err error) { +func (pager *IkePoliciesPager) GetNextWithContext(ctx context.Context) (page []IkePolicy, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListVPNServerRoutesWithContext(ctx, pager.options) + result, _, err := pager.client.ListIkePoliciesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -154959,16 +158374,16 @@ func (pager *VPNServerRoutesPager) GetNextWithContext(ctx context.Context) (page } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Routes + page = result.IkePolicies return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *VPNServerRoutesPager) GetAllWithContext(ctx context.Context) (allItems []VPNServerRoute, err error) { +func (pager *IkePoliciesPager) GetAllWithContext(ctx context.Context) (allItems []IkePolicy, err error) { for pager.HasNext() { - var nextPage []VPNServerRoute + var nextPage []IkePolicy nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -154980,38 +158395,38 @@ func (pager *VPNServerRoutesPager) GetAllWithContext(ctx context.Context) (allIt } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *VPNServerRoutesPager) GetNext() (page []VPNServerRoute, err error) { +func (pager *IkePoliciesPager) GetNext() (page []IkePolicy, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *VPNServerRoutesPager) GetAll() (allItems []VPNServerRoute, err error) { +func (pager *IkePoliciesPager) GetAll() (allItems []IkePolicy, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// LoadBalancerProfilesPager can be used to simplify the use of the "ListLoadBalancerProfiles" method. -type LoadBalancerProfilesPager struct { +// IkePolicyConnectionsPager can be used to simplify the use of the "ListIkePolicyConnections" method. +type IkePolicyConnectionsPager struct { hasNext bool - options *ListLoadBalancerProfilesOptions + options *ListIkePolicyConnectionsOptions client *VpcV1 pageContext struct { next *string } } -// NewLoadBalancerProfilesPager returns a new LoadBalancerProfilesPager instance. -func (vpc *VpcV1) NewLoadBalancerProfilesPager(options *ListLoadBalancerProfilesOptions) (pager *LoadBalancerProfilesPager, err error) { +// NewIkePolicyConnectionsPager returns a new IkePolicyConnectionsPager instance. +func (vpc *VpcV1) NewIkePolicyConnectionsPager(options *ListIkePolicyConnectionsOptions) (pager *IkePolicyConnectionsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListLoadBalancerProfilesOptions = *options - pager = &LoadBalancerProfilesPager{ + var optionsCopy ListIkePolicyConnectionsOptions = *options + pager = &IkePolicyConnectionsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -155020,19 +158435,19 @@ func (vpc *VpcV1) NewLoadBalancerProfilesPager(options *ListLoadBalancerProfiles } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *LoadBalancerProfilesPager) HasNext() bool { +func (pager *IkePolicyConnectionsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *LoadBalancerProfilesPager) GetNextWithContext(ctx context.Context) (page []LoadBalancerProfile, err error) { +func (pager *IkePolicyConnectionsPager) GetNextWithContext(ctx context.Context) (page []VPNGatewayConnectionIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListLoadBalancerProfilesWithContext(ctx, pager.options) + result, _, err := pager.client.ListIkePolicyConnectionsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -155051,16 +158466,16 @@ func (pager *LoadBalancerProfilesPager) GetNextWithContext(ctx context.Context) } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Profiles + page = result.Connections return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *LoadBalancerProfilesPager) GetAllWithContext(ctx context.Context) (allItems []LoadBalancerProfile, err error) { +func (pager *IkePolicyConnectionsPager) GetAllWithContext(ctx context.Context) (allItems []VPNGatewayConnectionIntf, err error) { for pager.HasNext() { - var nextPage []LoadBalancerProfile + var nextPage []VPNGatewayConnectionIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -155072,38 +158487,38 @@ func (pager *LoadBalancerProfilesPager) GetAllWithContext(ctx context.Context) ( } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *LoadBalancerProfilesPager) GetNext() (page []LoadBalancerProfile, err error) { +func (pager *IkePolicyConnectionsPager) GetNext() (page []VPNGatewayConnectionIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *LoadBalancerProfilesPager) GetAll() (allItems []LoadBalancerProfile, err error) { +func (pager *IkePolicyConnectionsPager) GetAll() (allItems []VPNGatewayConnectionIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// LoadBalancersPager can be used to simplify the use of the "ListLoadBalancers" method. -type LoadBalancersPager struct { +// IpsecPoliciesPager can be used to simplify the use of the "ListIpsecPolicies" method. +type IpsecPoliciesPager struct { hasNext bool - options *ListLoadBalancersOptions + options *ListIpsecPoliciesOptions client *VpcV1 pageContext struct { next *string } } -// NewLoadBalancersPager returns a new LoadBalancersPager instance. -func (vpc *VpcV1) NewLoadBalancersPager(options *ListLoadBalancersOptions) (pager *LoadBalancersPager, err error) { +// NewIpsecPoliciesPager returns a new IpsecPoliciesPager instance. +func (vpc *VpcV1) NewIpsecPoliciesPager(options *ListIpsecPoliciesOptions) (pager *IpsecPoliciesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListLoadBalancersOptions = *options - pager = &LoadBalancersPager{ + var optionsCopy ListIpsecPoliciesOptions = *options + pager = &IpsecPoliciesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -155112,19 +158527,19 @@ func (vpc *VpcV1) NewLoadBalancersPager(options *ListLoadBalancersOptions) (page } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *LoadBalancersPager) HasNext() bool { +func (pager *IpsecPoliciesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *LoadBalancersPager) GetNextWithContext(ctx context.Context) (page []LoadBalancer, err error) { +func (pager *IpsecPoliciesPager) GetNextWithContext(ctx context.Context) (page []IPsecPolicy, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListLoadBalancersWithContext(ctx, pager.options) + result, _, err := pager.client.ListIpsecPoliciesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -155143,16 +158558,16 @@ func (pager *LoadBalancersPager) GetNextWithContext(ctx context.Context) (page [ } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.LoadBalancers + page = result.IpsecPolicies return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *LoadBalancersPager) GetAllWithContext(ctx context.Context) (allItems []LoadBalancer, err error) { +func (pager *IpsecPoliciesPager) GetAllWithContext(ctx context.Context) (allItems []IPsecPolicy, err error) { for pager.HasNext() { - var nextPage []LoadBalancer + var nextPage []IPsecPolicy nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -155164,38 +158579,38 @@ func (pager *LoadBalancersPager) GetAllWithContext(ctx context.Context) (allItem } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *LoadBalancersPager) GetNext() (page []LoadBalancer, err error) { +func (pager *IpsecPoliciesPager) GetNext() (page []IPsecPolicy, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *LoadBalancersPager) GetAll() (allItems []LoadBalancer, err error) { +func (pager *IpsecPoliciesPager) GetAll() (allItems []IPsecPolicy, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// EndpointGatewaysPager can be used to simplify the use of the "ListEndpointGateways" method. -type EndpointGatewaysPager struct { +// IpsecPolicyConnectionsPager can be used to simplify the use of the "ListIpsecPolicyConnections" method. +type IpsecPolicyConnectionsPager struct { hasNext bool - options *ListEndpointGatewaysOptions + options *ListIpsecPolicyConnectionsOptions client *VpcV1 pageContext struct { next *string } } -// NewEndpointGatewaysPager returns a new EndpointGatewaysPager instance. -func (vpc *VpcV1) NewEndpointGatewaysPager(options *ListEndpointGatewaysOptions) (pager *EndpointGatewaysPager, err error) { +// NewIpsecPolicyConnectionsPager returns a new IpsecPolicyConnectionsPager instance. +func (vpc *VpcV1) NewIpsecPolicyConnectionsPager(options *ListIpsecPolicyConnectionsOptions) (pager *IpsecPolicyConnectionsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListEndpointGatewaysOptions = *options - pager = &EndpointGatewaysPager{ + var optionsCopy ListIpsecPolicyConnectionsOptions = *options + pager = &IpsecPolicyConnectionsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -155204,19 +158619,19 @@ func (vpc *VpcV1) NewEndpointGatewaysPager(options *ListEndpointGatewaysOptions) } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *EndpointGatewaysPager) HasNext() bool { +func (pager *IpsecPolicyConnectionsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *EndpointGatewaysPager) GetNextWithContext(ctx context.Context) (page []EndpointGateway, err error) { +func (pager *IpsecPolicyConnectionsPager) GetNextWithContext(ctx context.Context) (page []VPNGatewayConnectionIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListEndpointGatewaysWithContext(ctx, pager.options) + result, _, err := pager.client.ListIpsecPolicyConnectionsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -155235,16 +158650,16 @@ func (pager *EndpointGatewaysPager) GetNextWithContext(ctx context.Context) (pag } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.EndpointGateways + page = result.Connections return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *EndpointGatewaysPager) GetAllWithContext(ctx context.Context) (allItems []EndpointGateway, err error) { +func (pager *IpsecPolicyConnectionsPager) GetAllWithContext(ctx context.Context) (allItems []VPNGatewayConnectionIntf, err error) { for pager.HasNext() { - var nextPage []EndpointGateway + var nextPage []VPNGatewayConnectionIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -155256,38 +158671,38 @@ func (pager *EndpointGatewaysPager) GetAllWithContext(ctx context.Context) (allI } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *EndpointGatewaysPager) GetNext() (page []EndpointGateway, err error) { +func (pager *IpsecPolicyConnectionsPager) GetNext() (page []VPNGatewayConnectionIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *EndpointGatewaysPager) GetAll() (allItems []EndpointGateway, err error) { +func (pager *IpsecPolicyConnectionsPager) GetAll() (allItems []VPNGatewayConnectionIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// EndpointGatewayIpsPager can be used to simplify the use of the "ListEndpointGatewayIps" method. -type EndpointGatewayIpsPager struct { +// VPNGatewaysPager can be used to simplify the use of the "ListVPNGateways" method. +type VPNGatewaysPager struct { hasNext bool - options *ListEndpointGatewayIpsOptions + options *ListVPNGatewaysOptions client *VpcV1 pageContext struct { next *string } } -// NewEndpointGatewayIpsPager returns a new EndpointGatewayIpsPager instance. -func (vpc *VpcV1) NewEndpointGatewayIpsPager(options *ListEndpointGatewayIpsOptions) (pager *EndpointGatewayIpsPager, err error) { +// NewVPNGatewaysPager returns a new VPNGatewaysPager instance. +func (vpc *VpcV1) NewVPNGatewaysPager(options *ListVPNGatewaysOptions) (pager *VPNGatewaysPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListEndpointGatewayIpsOptions = *options - pager = &EndpointGatewayIpsPager{ + var optionsCopy ListVPNGatewaysOptions = *options + pager = &VPNGatewaysPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -155296,19 +158711,19 @@ func (vpc *VpcV1) NewEndpointGatewayIpsPager(options *ListEndpointGatewayIpsOpti } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *EndpointGatewayIpsPager) HasNext() bool { +func (pager *VPNGatewaysPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *EndpointGatewayIpsPager) GetNextWithContext(ctx context.Context) (page []ReservedIP, err error) { +func (pager *VPNGatewaysPager) GetNextWithContext(ctx context.Context) (page []VPNGatewayIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListEndpointGatewayIpsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPNGatewaysWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -155327,16 +158742,16 @@ func (pager *EndpointGatewayIpsPager) GetNextWithContext(ctx context.Context) (p } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.Ips + page = result.VPNGateways return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *EndpointGatewayIpsPager) GetAllWithContext(ctx context.Context) (allItems []ReservedIP, err error) { +func (pager *VPNGatewaysPager) GetAllWithContext(ctx context.Context) (allItems []VPNGatewayIntf, err error) { for pager.HasNext() { - var nextPage []ReservedIP + var nextPage []VPNGatewayIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -155348,38 +158763,38 @@ func (pager *EndpointGatewayIpsPager) GetAllWithContext(ctx context.Context) (al } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *EndpointGatewayIpsPager) GetNext() (page []ReservedIP, err error) { +func (pager *VPNGatewaysPager) GetNext() (page []VPNGatewayIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *EndpointGatewayIpsPager) GetAll() (allItems []ReservedIP, err error) { +func (pager *VPNGatewaysPager) GetAll() (allItems []VPNGatewayIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// FlowLogCollectorsPager can be used to simplify the use of the "ListFlowLogCollectors" method. -type FlowLogCollectorsPager struct { +// VPNGatewayConnectionsPager can be used to simplify the use of the "ListVPNGatewayConnections" method. +type VPNGatewayConnectionsPager struct { hasNext bool - options *ListFlowLogCollectorsOptions + options *ListVPNGatewayConnectionsOptions client *VpcV1 pageContext struct { next *string } } -// NewFlowLogCollectorsPager returns a new FlowLogCollectorsPager instance. -func (vpc *VpcV1) NewFlowLogCollectorsPager(options *ListFlowLogCollectorsOptions) (pager *FlowLogCollectorsPager, err error) { +// NewVPNGatewayConnectionsPager returns a new VPNGatewayConnectionsPager instance. +func (vpc *VpcV1) NewVPNGatewayConnectionsPager(options *ListVPNGatewayConnectionsOptions) (pager *VPNGatewayConnectionsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListFlowLogCollectorsOptions = *options - pager = &FlowLogCollectorsPager{ + var optionsCopy ListVPNGatewayConnectionsOptions = *options + pager = &VPNGatewayConnectionsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -155388,19 +158803,19 @@ func (vpc *VpcV1) NewFlowLogCollectorsPager(options *ListFlowLogCollectorsOption } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *FlowLogCollectorsPager) HasNext() bool { +func (pager *VPNGatewayConnectionsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *FlowLogCollectorsPager) GetNextWithContext(ctx context.Context) (page []FlowLogCollector, err error) { +func (pager *VPNGatewayConnectionsPager) GetNextWithContext(ctx context.Context) (page []VPNGatewayConnectionIntf, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListFlowLogCollectorsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPNGatewayConnectionsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -155419,16 +158834,16 @@ func (pager *FlowLogCollectorsPager) GetNextWithContext(ctx context.Context) (pa } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.FlowLogCollectors + page = result.Connections return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *FlowLogCollectorsPager) GetAllWithContext(ctx context.Context) (allItems []FlowLogCollector, err error) { +func (pager *VPNGatewayConnectionsPager) GetAllWithContext(ctx context.Context) (allItems []VPNGatewayConnectionIntf, err error) { for pager.HasNext() { - var nextPage []FlowLogCollector + var nextPage []VPNGatewayConnectionIntf nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -155440,38 +158855,38 @@ func (pager *FlowLogCollectorsPager) GetAllWithContext(ctx context.Context) (all } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *FlowLogCollectorsPager) GetNext() (page []FlowLogCollector, err error) { +func (pager *VPNGatewayConnectionsPager) GetNext() (page []VPNGatewayConnectionIntf, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *FlowLogCollectorsPager) GetAll() (allItems []FlowLogCollector, err error) { +func (pager *VPNGatewayConnectionsPager) GetAll() (allItems []VPNGatewayConnectionIntf, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// PrivatePathServiceGatewaysPager can be used to simplify the use of the "ListPrivatePathServiceGateways" method. -type PrivatePathServiceGatewaysPager struct { +// VPNServersPager can be used to simplify the use of the "ListVPNServers" method. +type VPNServersPager struct { hasNext bool - options *ListPrivatePathServiceGatewaysOptions + options *ListVPNServersOptions client *VpcV1 pageContext struct { next *string } } -// NewPrivatePathServiceGatewaysPager returns a new PrivatePathServiceGatewaysPager instance. -func (vpc *VpcV1) NewPrivatePathServiceGatewaysPager(options *ListPrivatePathServiceGatewaysOptions) (pager *PrivatePathServiceGatewaysPager, err error) { +// NewVPNServersPager returns a new VPNServersPager instance. +func (vpc *VpcV1) NewVPNServersPager(options *ListVPNServersOptions) (pager *VPNServersPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListPrivatePathServiceGatewaysOptions = *options - pager = &PrivatePathServiceGatewaysPager{ + var optionsCopy ListVPNServersOptions = *options + pager = &VPNServersPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -155480,19 +158895,19 @@ func (vpc *VpcV1) NewPrivatePathServiceGatewaysPager(options *ListPrivatePathSer } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *PrivatePathServiceGatewaysPager) HasNext() bool { +func (pager *VPNServersPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *PrivatePathServiceGatewaysPager) GetNextWithContext(ctx context.Context) (page []PrivatePathServiceGateway, err error) { +func (pager *VPNServersPager) GetNextWithContext(ctx context.Context) (page []VPNServer, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListPrivatePathServiceGatewaysWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPNServersWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -155511,16 +158926,16 @@ func (pager *PrivatePathServiceGatewaysPager) GetNextWithContext(ctx context.Con } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.PrivatePathServiceGateways + page = result.VPNServers return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *PrivatePathServiceGatewaysPager) GetAllWithContext(ctx context.Context) (allItems []PrivatePathServiceGateway, err error) { +func (pager *VPNServersPager) GetAllWithContext(ctx context.Context) (allItems []VPNServer, err error) { for pager.HasNext() { - var nextPage []PrivatePathServiceGateway + var nextPage []VPNServer nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -155532,38 +158947,38 @@ func (pager *PrivatePathServiceGatewaysPager) GetAllWithContext(ctx context.Cont } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *PrivatePathServiceGatewaysPager) GetNext() (page []PrivatePathServiceGateway, err error) { +func (pager *VPNServersPager) GetNext() (page []VPNServer, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *PrivatePathServiceGatewaysPager) GetAll() (allItems []PrivatePathServiceGateway, err error) { +func (pager *VPNServersPager) GetAll() (allItems []VPNServer, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// PrivatePathServiceGatewayAccountPoliciesPager can be used to simplify the use of the "ListPrivatePathServiceGatewayAccountPolicies" method. -type PrivatePathServiceGatewayAccountPoliciesPager struct { +// VPNServerClientsPager can be used to simplify the use of the "ListVPNServerClients" method. +type VPNServerClientsPager struct { hasNext bool - options *ListPrivatePathServiceGatewayAccountPoliciesOptions + options *ListVPNServerClientsOptions client *VpcV1 pageContext struct { next *string } } -// NewPrivatePathServiceGatewayAccountPoliciesPager returns a new PrivatePathServiceGatewayAccountPoliciesPager instance. -func (vpc *VpcV1) NewPrivatePathServiceGatewayAccountPoliciesPager(options *ListPrivatePathServiceGatewayAccountPoliciesOptions) (pager *PrivatePathServiceGatewayAccountPoliciesPager, err error) { +// NewVPNServerClientsPager returns a new VPNServerClientsPager instance. +func (vpc *VpcV1) NewVPNServerClientsPager(options *ListVPNServerClientsOptions) (pager *VPNServerClientsPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListPrivatePathServiceGatewayAccountPoliciesOptions = *options - pager = &PrivatePathServiceGatewayAccountPoliciesPager{ + var optionsCopy ListVPNServerClientsOptions = *options + pager = &VPNServerClientsPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -155572,19 +158987,19 @@ func (vpc *VpcV1) NewPrivatePathServiceGatewayAccountPoliciesPager(options *List } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *PrivatePathServiceGatewayAccountPoliciesPager) HasNext() bool { +func (pager *VPNServerClientsPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetNextWithContext(ctx context.Context) (page []PrivatePathServiceGatewayAccountPolicy, err error) { +func (pager *VPNServerClientsPager) GetNextWithContext(ctx context.Context) (page []VPNServerClient, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListPrivatePathServiceGatewayAccountPoliciesWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPNServerClientsWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -155603,16 +159018,16 @@ func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetNextWithContext(c } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.AccountPolicies + page = result.Clients return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetAllWithContext(ctx context.Context) (allItems []PrivatePathServiceGatewayAccountPolicy, err error) { +func (pager *VPNServerClientsPager) GetAllWithContext(ctx context.Context) (allItems []VPNServerClient, err error) { for pager.HasNext() { - var nextPage []PrivatePathServiceGatewayAccountPolicy + var nextPage []VPNServerClient nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -155624,38 +159039,38 @@ func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetAllWithContext(ct } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetNext() (page []PrivatePathServiceGatewayAccountPolicy, err error) { +func (pager *VPNServerClientsPager) GetNext() (page []VPNServerClient, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *PrivatePathServiceGatewayAccountPoliciesPager) GetAll() (allItems []PrivatePathServiceGatewayAccountPolicy, err error) { +func (pager *VPNServerClientsPager) GetAll() (allItems []VPNServerClient, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } -// PrivatePathServiceGatewayEndpointGatewayBindingsPager can be used to simplify the use of the "ListPrivatePathServiceGatewayEndpointGatewayBindings" method. -type PrivatePathServiceGatewayEndpointGatewayBindingsPager struct { +// VPNServerRoutesPager can be used to simplify the use of the "ListVPNServerRoutes" method. +type VPNServerRoutesPager struct { hasNext bool - options *ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions + options *ListVPNServerRoutesOptions client *VpcV1 pageContext struct { next *string } } -// NewPrivatePathServiceGatewayEndpointGatewayBindingsPager returns a new PrivatePathServiceGatewayEndpointGatewayBindingsPager instance. -func (vpc *VpcV1) NewPrivatePathServiceGatewayEndpointGatewayBindingsPager(options *ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions) (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager, err error) { +// NewVPNServerRoutesPager returns a new VPNServerRoutesPager instance. +func (vpc *VpcV1) NewVPNServerRoutesPager(options *ListVPNServerRoutesOptions) (pager *VPNServerRoutesPager, err error) { if options.Start != nil && *options.Start != "" { err = core.SDKErrorf(nil, "the 'options.Start' field should not be set", "no-query-setting", common.GetComponentInfo()) return } - var optionsCopy ListPrivatePathServiceGatewayEndpointGatewayBindingsOptions = *options - pager = &PrivatePathServiceGatewayEndpointGatewayBindingsPager{ + var optionsCopy ListVPNServerRoutesOptions = *options + pager = &VPNServerRoutesPager{ hasNext: true, options: &optionsCopy, client: vpc, @@ -155664,19 +159079,19 @@ func (vpc *VpcV1) NewPrivatePathServiceGatewayEndpointGatewayBindingsPager(optio } // HasNext returns true if there are potentially more results to be retrieved. -func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) HasNext() bool { +func (pager *VPNServerRoutesPager) HasNext() bool { return pager.hasNext } // GetNextWithContext returns the next page of results using the specified Context. -func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetNextWithContext(ctx context.Context) (page []PrivatePathServiceGatewayEndpointGatewayBinding, err error) { +func (pager *VPNServerRoutesPager) GetNextWithContext(ctx context.Context) (page []VPNServerRoute, err error) { if !pager.HasNext() { return nil, fmt.Errorf("no more results available") } pager.options.Start = pager.pageContext.next - result, _, err := pager.client.ListPrivatePathServiceGatewayEndpointGatewayBindingsWithContext(ctx, pager.options) + result, _, err := pager.client.ListVPNServerRoutesWithContext(ctx, pager.options) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") return @@ -155695,16 +159110,16 @@ func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetNextWithC } pager.pageContext.next = next pager.hasNext = (pager.pageContext.next != nil) - page = result.EndpointGatewayBindings + page = result.Routes return } // GetAllWithContext returns all results by invoking GetNextWithContext() repeatedly // until all pages of results have been retrieved. -func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetAllWithContext(ctx context.Context) (allItems []PrivatePathServiceGatewayEndpointGatewayBinding, err error) { +func (pager *VPNServerRoutesPager) GetAllWithContext(ctx context.Context) (allItems []VPNServerRoute, err error) { for pager.HasNext() { - var nextPage []PrivatePathServiceGatewayEndpointGatewayBinding + var nextPage []VPNServerRoute nextPage, err = pager.GetNextWithContext(ctx) if err != nil { err = core.RepurposeSDKProblem(err, "error-getting-next-page") @@ -155716,14 +159131,14 @@ func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetAllWithCo } // GetNext invokes GetNextWithContext() using context.Background() as the Context parameter. -func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetNext() (page []PrivatePathServiceGatewayEndpointGatewayBinding, err error) { +func (pager *VPNServerRoutesPager) GetNext() (page []VPNServerRoute, err error) { page, err = pager.GetNextWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return } // GetAll invokes GetAllWithContext() using context.Background() as the Context parameter. -func (pager *PrivatePathServiceGatewayEndpointGatewayBindingsPager) GetAll() (allItems []PrivatePathServiceGatewayEndpointGatewayBinding, err error) { +func (pager *VPNServerRoutesPager) GetAll() (allItems []VPNServerRoute, err error) { allItems, err = pager.GetAllWithContext(context.Background()) err = core.RepurposeSDKProblem(err, "") return diff --git a/vendor/github.com/cenkalti/backoff/v5/exponential.go b/vendor/github.com/cenkalti/backoff/v5/exponential.go index c1f3e442d364..79d425e87469 100644 --- a/vendor/github.com/cenkalti/backoff/v5/exponential.go +++ b/vendor/github.com/cenkalti/backoff/v5/exponential.go @@ -1,7 +1,7 @@ package backoff import ( - "math/rand" + "math/rand/v2" "time" ) @@ -28,13 +28,7 @@ multiplied by the exponential, that is, between 2 and 6 seconds. Note: MaxInterval caps the RetryInterval and not the randomized interval. -If the time elapsed since an ExponentialBackOff instance is created goes past the -MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop. - -The elapsed time can be reset by calling Reset(). - -Example: Given the following default arguments, for 10 tries the sequence will be, -and assuming we go over the MaxElapsedTime on the 10th try: +Example: Given the following default arguments, for 9 tries the sequence will be: Request # RetryInterval (seconds) Randomized Interval (seconds) @@ -47,7 +41,6 @@ and assuming we go over the MaxElapsedTime on the 10th try: 7 5.692 [2.846, 8.538] 8 8.538 [4.269, 12.807] 9 12.807 [6.403, 19.210] - 10 19.210 backoff.Stop Note: Implementation is not thread-safe. */ diff --git a/vendor/github.com/cenkalti/backoff/v5/retry.go b/vendor/github.com/cenkalti/backoff/v5/retry.go index e43f47fb8a55..32a7f988347d 100644 --- a/vendor/github.com/cenkalti/backoff/v5/retry.go +++ b/vendor/github.com/cenkalti/backoff/v5/retry.go @@ -47,7 +47,7 @@ func WithNotify(n Notify) RetryOption { } } -// WithMaxTries limits the number of retry attempts. +// WithMaxTries limits the number of all attempts. func WithMaxTries(n uint) RetryOption { return func(args *retryOptions) { args.MaxTries = n @@ -97,7 +97,7 @@ func Retry[T any](ctx context.Context, operation Operation[T], opts ...RetryOpti // Handle permanent errors without retrying. var permanent *PermanentError if errors.As(err, &permanent) { - return res, err + return res, permanent.Unwrap() } // Stop retrying if context is cancelled. diff --git a/vendor/github.com/emicklei/go-restful/v3/.travis.yml b/vendor/github.com/emicklei/go-restful/v3/.travis.yml deleted file mode 100644 index 3a0bf5ff1b81..000000000000 --- a/vendor/github.com/emicklei/go-restful/v3/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -go: - - 1.x - -before_install: - - go test -v - -script: - - go test -race -coverprofile=coverage.txt -covermode=atomic - -after_success: - - bash <(curl -s https://codecov.io/bash) \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/v3/CHANGES.md b/vendor/github.com/emicklei/go-restful/v3/CHANGES.md index 6f24dfff562e..4fcd920abea4 100644 --- a/vendor/github.com/emicklei/go-restful/v3/CHANGES.md +++ b/vendor/github.com/emicklei/go-restful/v3/CHANGES.md @@ -1,5 +1,9 @@ # Change history of go-restful +## [v3.13.0] - 2025-08-14 + +- optimize performance of path matching in CurlyRouter ( thanks @wenhuang, Wen Huang) + ## [v3.12.2] - 2025-02-21 - allow empty payloads in post,put,patch, issue #580 ( thanks @liggitt, Jordan Liggitt) diff --git a/vendor/github.com/emicklei/go-restful/v3/README.md b/vendor/github.com/emicklei/go-restful/v3/README.md index 3fb40d198087..50a79ab692d7 100644 --- a/vendor/github.com/emicklei/go-restful/v3/README.md +++ b/vendor/github.com/emicklei/go-restful/v3/README.md @@ -84,6 +84,7 @@ func (u UserResource) findUser(request *restful.Request, response *restful.Respo - Configurable (trace) logging - Customizable gzip/deflate readers and writers using CompressorProvider registration - Inject your own http.Handler using the `HttpMiddlewareHandlerToFilter` function +- Added `SetPathTokenCacheEnabled` and `SetCustomVerbCacheEnabled` to disable regexp caching (default=true) ## How to customize There are several hooks to customize the behavior of the go-restful package. diff --git a/vendor/github.com/emicklei/go-restful/v3/curly.go b/vendor/github.com/emicklei/go-restful/v3/curly.go index 6fd2bcd5a117..eec43bfd0674 100644 --- a/vendor/github.com/emicklei/go-restful/v3/curly.go +++ b/vendor/github.com/emicklei/go-restful/v3/curly.go @@ -9,11 +9,35 @@ import ( "regexp" "sort" "strings" + "sync" ) // CurlyRouter expects Routes with paths that contain zero or more parameters in curly brackets. type CurlyRouter struct{} +var ( + regexCache sync.Map // Cache for compiled regex patterns + pathTokenCacheEnabled = true // Enable/disable path token regex caching +) + +// SetPathTokenCacheEnabled enables or disables path token regex caching for CurlyRouter. +// When disabled, regex patterns will be compiled on every request. +// When enabled (default), compiled regex patterns are cached for better performance. +func SetPathTokenCacheEnabled(enabled bool) { + pathTokenCacheEnabled = enabled +} + +// getCachedRegexp retrieves a compiled regex from the cache if found and valid. +// Returns the regex and true if found and valid, nil and false otherwise. +func getCachedRegexp(cache *sync.Map, pattern string) (*regexp.Regexp, bool) { + if cached, found := cache.Load(pattern); found { + if regex, ok := cached.(*regexp.Regexp); ok { + return regex, true + } + } + return nil, false +} + // SelectRoute is part of the Router interface and returns the best match // for the WebService and its Route for the given Request. func (c CurlyRouter) SelectRoute( @@ -113,8 +137,28 @@ func (c CurlyRouter) regularMatchesPathToken(routeToken string, colon int, reque } return true, true } - matched, err := regexp.MatchString(regPart, requestToken) - return (matched && err == nil), false + + // Check cache first (if enabled) + if pathTokenCacheEnabled { + if regex, found := getCachedRegexp(®exCache, regPart); found { + matched := regex.MatchString(requestToken) + return matched, false + } + } + + // Compile the regex + regex, err := regexp.Compile(regPart) + if err != nil { + return false, false + } + + // Cache the regex (if enabled) + if pathTokenCacheEnabled { + regexCache.Store(regPart, regex) + } + + matched := regex.MatchString(requestToken) + return matched, false } var jsr311Router = RouterJSR311{} @@ -168,7 +212,7 @@ func (c CurlyRouter) computeWebserviceScore(requestTokens []string, routeTokens if matchesToken { score++ // extra score for regex match } - } + } } else { // not a parameter if eachRequestToken != eachRouteToken { diff --git a/vendor/github.com/emicklei/go-restful/v3/custom_verb.go b/vendor/github.com/emicklei/go-restful/v3/custom_verb.go index bfc17efde80f..0b98eeb091cd 100644 --- a/vendor/github.com/emicklei/go-restful/v3/custom_verb.go +++ b/vendor/github.com/emicklei/go-restful/v3/custom_verb.go @@ -1,14 +1,28 @@ package restful +// Copyright 2025 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + import ( "fmt" "regexp" + "sync" ) var ( - customVerbReg = regexp.MustCompile(":([A-Za-z]+)$") + customVerbReg = regexp.MustCompile(":([A-Za-z]+)$") + customVerbCache sync.Map // Cache for compiled custom verb regexes + customVerbCacheEnabled = true // Enable/disable custom verb regex caching ) +// SetCustomVerbCacheEnabled enables or disables custom verb regex caching. +// When disabled, custom verb regex patterns will be compiled on every request. +// When enabled (default), compiled custom verb regex patterns are cached for better performance. +func SetCustomVerbCacheEnabled(enabled bool) { + customVerbCacheEnabled = enabled +} + func hasCustomVerb(routeToken string) bool { return customVerbReg.MatchString(routeToken) } @@ -20,7 +34,23 @@ func isMatchCustomVerb(routeToken string, pathToken string) bool { } customVerb := rs[1] - specificVerbReg := regexp.MustCompile(fmt.Sprintf(":%s$", customVerb)) + regexPattern := fmt.Sprintf(":%s$", customVerb) + + // Check cache first (if enabled) + if customVerbCacheEnabled { + if specificVerbReg, found := getCachedRegexp(&customVerbCache, regexPattern); found { + return specificVerbReg.MatchString(pathToken) + } + } + + // Compile the regex + specificVerbReg := regexp.MustCompile(regexPattern) + + // Cache the regex (if enabled) + if customVerbCacheEnabled { + customVerbCache.Store(regexPattern, specificVerbReg) + } + return specificVerbReg.MatchString(pathToken) } diff --git a/vendor/github.com/emicklei/go-restful/v3/doc.go b/vendor/github.com/emicklei/go-restful/v3/doc.go index 69b13057d017..80809225b8d5 100644 --- a/vendor/github.com/emicklei/go-restful/v3/doc.go +++ b/vendor/github.com/emicklei/go-restful/v3/doc.go @@ -1,7 +1,7 @@ /* Package restful , a lean package for creating REST-style WebServices without magic. -WebServices and Routes +### WebServices and Routes A WebService has a collection of Route objects that dispatch incoming Http Requests to a function calls. Typically, a WebService has a root path (e.g. /users) and defines common MIME types for its routes. @@ -30,14 +30,14 @@ The (*Request, *Response) arguments provide functions for reading information fr See the example https://github.com/emicklei/go-restful/blob/v3/examples/user-resource/restful-user-resource.go with a full implementation. -Regular expression matching Routes +### Regular expression matching Routes A Route parameter can be specified using the format "uri/{var[:regexp]}" or the special version "uri/{var:*}" for matching the tail of the path. For example, /persons/{name:[A-Z][A-Z]} can be used to restrict values for the parameter "name" to only contain capital alphabetic characters. Regular expressions must use the standard Go syntax as described in the regexp package. (https://code.google.com/p/re2/wiki/Syntax) This feature requires the use of a CurlyRouter. -Containers +### Containers A Container holds a collection of WebServices, Filters and a http.ServeMux for multiplexing http requests. Using the statements "restful.Add(...) and restful.Filter(...)" will register WebServices and Filters to the Default Container. @@ -47,7 +47,7 @@ You can create your own Container and create a new http.Server for that particul container := restful.NewContainer() server := &http.Server{Addr: ":8081", Handler: container} -Filters +### Filters A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. You can use filters to perform generic logging, measurement, authentication, redirect, set response headers etc. @@ -60,22 +60,21 @@ Use the following statement to pass the request,response pair to the next filter chain.ProcessFilter(req, resp) -Container Filters +### Container Filters These are processed before any registered WebService. // install a (global) filter for the default container (processed before any webservice) restful.Filter(globalLogging) -WebService Filters +### WebService Filters These are processed before any Route of a WebService. // install a webservice filter (processed before any route) ws.Filter(webserviceLogging).Filter(measureTime) - -Route Filters +### Route Filters These are processed before calling the function associated with the Route. @@ -84,7 +83,7 @@ These are processed before calling the function associated with the Route. See the example https://github.com/emicklei/go-restful/blob/v3/examples/filters/restful-filters.go with full implementations. -Response Encoding +### Response Encoding Two encodings are supported: gzip and deflate. To enable this for all responses: @@ -95,20 +94,20 @@ Alternatively, you can create a Filter that performs the encoding and install it See the example https://github.com/emicklei/go-restful/blob/v3/examples/encoding/restful-encoding-filter.go -OPTIONS support +### OPTIONS support By installing a pre-defined container filter, your Webservice(s) can respond to the OPTIONS Http request. Filter(OPTIONSFilter()) -CORS +### CORS By installing the filter of a CrossOriginResourceSharing (CORS), your WebService(s) can handle CORS requests. cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} Filter(cors.Filter) -Error Handling +### Error Handling Unexpected things happen. If a request cannot be processed because of a failure, your service needs to tell via the response what happened and why. For this reason HTTP status codes exist and it is important to use the correct code in every exceptional situation. @@ -137,11 +136,11 @@ The request does not have or has an unknown Accept Header set for this operation The request does not have or has an unknown Content-Type Header set for this operation. -ServiceError +### ServiceError In addition to setting the correct (error) Http status code, you can choose to write a ServiceError message on the response. -Performance options +### Performance options This package has several options that affect the performance of your service. It is important to understand them and how you can change it. @@ -156,30 +155,27 @@ Default value is true If content encoding is enabled then the default strategy for getting new gzip/zlib writers and readers is to use a sync.Pool. Because writers are expensive structures, performance is even more improved when using a preloaded cache. You can also inject your own implementation. -Trouble shooting +### Trouble shooting This package has the means to produce detail logging of the complete Http request matching process and filter invocation. Enabling this feature requires you to set an implementation of restful.StdLogger (e.g. log.Logger) instance such as: restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) -Logging +### Logging The restful.SetLogger() method allows you to override the logger used by the package. By default restful uses the standard library `log` package and logs to stdout. Different logging packages are supported as long as they conform to `StdLogger` interface defined in the `log` sub-package, writing an adapter for your preferred package is simple. -Resources +### Resources -[project]: https://github.com/emicklei/go-restful +(c) 2012-2025, http://ernestmicklei.com. MIT License +[project]: https://github.com/emicklei/go-restful [examples]: https://github.com/emicklei/go-restful/blob/master/examples - -[design]: http://ernestmicklei.com/2012/11/11/go-restful-api-design/ - +[design]: http://ernestmicklei.com/2012/11/11/go-restful-api-design/ [showcases]: https://github.com/emicklei/mora, https://github.com/emicklei/landskape - -(c) 2012-2015, http://ernestmicklei.com. MIT License */ package restful diff --git a/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml b/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml new file mode 100644 index 000000000000..f2058ccc573d --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml @@ -0,0 +1,5 @@ +version: "2" +linters: + exclusions: + presets: + - std-error-handling diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/json/json.go b/vendor/github.com/gabriel-vasile/mimetype/internal/json/json.go deleted file mode 100644 index 5b2ecee443e3..000000000000 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/json/json.go +++ /dev/null @@ -1,567 +0,0 @@ -// Copyright (c) 2009 The Go Authors. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Package json provides a JSON value parser state machine. -// This package is almost entirely copied from the Go stdlib. -// Changes made to it permit users of the package to tell -// if some slice of bytes is a valid beginning of a json string. -package json - -import ( - "fmt" - "sync" -) - -type ( - scanStatus int -) - -const ( - parseObjectKey = iota // parsing object key (before colon) - parseObjectValue // parsing object value (after colon) - parseArrayValue // parsing array value - - scanContinue scanStatus = iota // uninteresting byte - scanBeginLiteral // end implied by next result != scanContinue - scanBeginObject // begin object - scanObjectKey // just finished object key (string) - scanObjectValue // just finished non-last object value - scanEndObject // end object (implies scanObjectValue if possible) - scanBeginArray // begin array - scanArrayValue // just finished array value - scanEndArray // end array (implies scanArrayValue if possible) - scanSkipSpace // space byte; can skip; known to be last "continue" result - scanEnd // top-level value ended *before* this byte; known to be first "stop" result - scanError // hit an error, scanner.err. - - // This limits the max nesting depth to prevent stack overflow. - // This is permitted by https://tools.ietf.org/html/rfc7159#section-9 - maxNestingDepth = 10000 -) - -type ( - scanner struct { - step func(*scanner, byte) scanStatus - parseState []int - endTop bool - err error - index int - } -) - -var scannerPool = sync.Pool{ - New: func() any { - return &scanner{} - }, -} - -func newScanner() *scanner { - s := scannerPool.Get().(*scanner) - s.reset() - return s -} - -func freeScanner(s *scanner) { - // Avoid hanging on to too much memory in extreme cases. - if len(s.parseState) > 1024 { - s.parseState = nil - } - scannerPool.Put(s) -} - -// Scan returns the number of bytes scanned and if there was any error -// in trying to reach the end of data. -func Scan(data []byte) (int, error) { - s := newScanner() - defer freeScanner(s) - _ = checkValid(data, s) - return s.index, s.err -} - -// checkValid verifies that data is valid JSON-encoded data. -// scan is passed in for use by checkValid to avoid an allocation. -func checkValid(data []byte, scan *scanner) error { - for _, c := range data { - scan.index++ - if scan.step(scan, c) == scanError { - return scan.err - } - } - if scan.eof() == scanError { - return scan.err - } - return nil -} - -func isSpace(c byte) bool { - return c == ' ' || c == '\t' || c == '\r' || c == '\n' -} - -func (s *scanner) reset() { - s.step = stateBeginValue - s.parseState = s.parseState[0:0] - s.err = nil - s.endTop = false - s.index = 0 -} - -// eof tells the scanner that the end of input has been reached. -// It returns a scan status just as s.step does. -func (s *scanner) eof() scanStatus { - if s.err != nil { - return scanError - } - if s.endTop { - return scanEnd - } - s.step(s, ' ') - if s.endTop { - return scanEnd - } - if s.err == nil { - s.err = fmt.Errorf("unexpected end of JSON input") - } - return scanError -} - -// pushParseState pushes a new parse state p onto the parse stack. -// an error state is returned if maxNestingDepth was exceeded, otherwise successState is returned. -func (s *scanner) pushParseState(c byte, newParseState int, successState scanStatus) scanStatus { - s.parseState = append(s.parseState, newParseState) - if len(s.parseState) <= maxNestingDepth { - return successState - } - return s.error(c, "exceeded max depth") -} - -// popParseState pops a parse state (already obtained) off the stack -// and updates s.step accordingly. -func (s *scanner) popParseState() { - n := len(s.parseState) - 1 - s.parseState = s.parseState[0:n] - if n == 0 { - s.step = stateEndTop - s.endTop = true - } else { - s.step = stateEndValue - } -} - -// stateBeginValueOrEmpty is the state after reading `[`. -func stateBeginValueOrEmpty(s *scanner, c byte) scanStatus { - if c <= ' ' && isSpace(c) { - return scanSkipSpace - } - if c == ']' { - return stateEndValue(s, c) - } - return stateBeginValue(s, c) -} - -// stateBeginValue is the state at the beginning of the input. -func stateBeginValue(s *scanner, c byte) scanStatus { - if c <= ' ' && isSpace(c) { - return scanSkipSpace - } - switch c { - case '{': - s.step = stateBeginStringOrEmpty - return s.pushParseState(c, parseObjectKey, scanBeginObject) - case '[': - s.step = stateBeginValueOrEmpty - return s.pushParseState(c, parseArrayValue, scanBeginArray) - case '"': - s.step = stateInString - return scanBeginLiteral - case '-': - s.step = stateNeg - return scanBeginLiteral - case '0': // beginning of 0.123 - s.step = state0 - return scanBeginLiteral - case 't': // beginning of true - s.step = stateT - return scanBeginLiteral - case 'f': // beginning of false - s.step = stateF - return scanBeginLiteral - case 'n': // beginning of null - s.step = stateN - return scanBeginLiteral - } - if '1' <= c && c <= '9' { // beginning of 1234.5 - s.step = state1 - return scanBeginLiteral - } - return s.error(c, "looking for beginning of value") -} - -// stateBeginStringOrEmpty is the state after reading `{`. -func stateBeginStringOrEmpty(s *scanner, c byte) scanStatus { - if c <= ' ' && isSpace(c) { - return scanSkipSpace - } - if c == '}' { - n := len(s.parseState) - s.parseState[n-1] = parseObjectValue - return stateEndValue(s, c) - } - return stateBeginString(s, c) -} - -// stateBeginString is the state after reading `{"key": value,`. -func stateBeginString(s *scanner, c byte) scanStatus { - if c <= ' ' && isSpace(c) { - return scanSkipSpace - } - if c == '"' { - s.step = stateInString - return scanBeginLiteral - } - return s.error(c, "looking for beginning of object key string") -} - -// stateEndValue is the state after completing a value, -// such as after reading `{}` or `true` or `["x"`. -func stateEndValue(s *scanner, c byte) scanStatus { - n := len(s.parseState) - if n == 0 { - // Completed top-level before the current byte. - s.step = stateEndTop - s.endTop = true - return stateEndTop(s, c) - } - if c <= ' ' && isSpace(c) { - s.step = stateEndValue - return scanSkipSpace - } - ps := s.parseState[n-1] - switch ps { - case parseObjectKey: - if c == ':' { - s.parseState[n-1] = parseObjectValue - s.step = stateBeginValue - return scanObjectKey - } - return s.error(c, "after object key") - case parseObjectValue: - if c == ',' { - s.parseState[n-1] = parseObjectKey - s.step = stateBeginString - return scanObjectValue - } - if c == '}' { - s.popParseState() - return scanEndObject - } - return s.error(c, "after object key:value pair") - case parseArrayValue: - if c == ',' { - s.step = stateBeginValue - return scanArrayValue - } - if c == ']' { - s.popParseState() - return scanEndArray - } - return s.error(c, "after array element") - } - return s.error(c, "") -} - -// stateEndTop is the state after finishing the top-level value, -// such as after reading `{}` or `[1,2,3]`. -// Only space characters should be seen now. -func stateEndTop(s *scanner, c byte) scanStatus { - if c != ' ' && c != '\t' && c != '\r' && c != '\n' { - // Complain about non-space byte on next call. - s.error(c, "after top-level value") - } - return scanEnd -} - -// stateInString is the state after reading `"`. -func stateInString(s *scanner, c byte) scanStatus { - if c == '"' { - s.step = stateEndValue - return scanContinue - } - if c == '\\' { - s.step = stateInStringEsc - return scanContinue - } - if c < 0x20 { - return s.error(c, "in string literal") - } - return scanContinue -} - -// stateInStringEsc is the state after reading `"\` during a quoted string. -func stateInStringEsc(s *scanner, c byte) scanStatus { - switch c { - case 'b', 'f', 'n', 'r', 't', '\\', '/', '"': - s.step = stateInString - return scanContinue - case 'u': - s.step = stateInStringEscU - return scanContinue - } - return s.error(c, "in string escape code") -} - -// stateInStringEscU is the state after reading `"\u` during a quoted string. -func stateInStringEscU(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { - s.step = stateInStringEscU1 - return scanContinue - } - // numbers - return s.error(c, "in \\u hexadecimal character escape") -} - -// stateInStringEscU1 is the state after reading `"\u1` during a quoted string. -func stateInStringEscU1(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { - s.step = stateInStringEscU12 - return scanContinue - } - // numbers - return s.error(c, "in \\u hexadecimal character escape") -} - -// stateInStringEscU12 is the state after reading `"\u12` during a quoted string. -func stateInStringEscU12(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { - s.step = stateInStringEscU123 - return scanContinue - } - // numbers - return s.error(c, "in \\u hexadecimal character escape") -} - -// stateInStringEscU123 is the state after reading `"\u123` during a quoted string. -func stateInStringEscU123(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { - s.step = stateInString - return scanContinue - } - // numbers - return s.error(c, "in \\u hexadecimal character escape") -} - -// stateNeg is the state after reading `-` during a number. -func stateNeg(s *scanner, c byte) scanStatus { - if c == '0' { - s.step = state0 - return scanContinue - } - if '1' <= c && c <= '9' { - s.step = state1 - return scanContinue - } - return s.error(c, "in numeric literal") -} - -// state1 is the state after reading a non-zero integer during a number, -// such as after reading `1` or `100` but not `0`. -func state1(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' { - s.step = state1 - return scanContinue - } - return state0(s, c) -} - -// state0 is the state after reading `0` during a number. -func state0(s *scanner, c byte) scanStatus { - if c == '.' { - s.step = stateDot - return scanContinue - } - if c == 'e' || c == 'E' { - s.step = stateE - return scanContinue - } - return stateEndValue(s, c) -} - -// stateDot is the state after reading the integer and decimal point in a number, -// such as after reading `1.`. -func stateDot(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' { - s.step = stateDot0 - return scanContinue - } - return s.error(c, "after decimal point in numeric literal") -} - -// stateDot0 is the state after reading the integer, decimal point, and subsequent -// digits of a number, such as after reading `3.14`. -func stateDot0(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' { - return scanContinue - } - if c == 'e' || c == 'E' { - s.step = stateE - return scanContinue - } - return stateEndValue(s, c) -} - -// stateE is the state after reading the mantissa and e in a number, -// such as after reading `314e` or `0.314e`. -func stateE(s *scanner, c byte) scanStatus { - if c == '+' || c == '-' { - s.step = stateESign - return scanContinue - } - return stateESign(s, c) -} - -// stateESign is the state after reading the mantissa, e, and sign in a number, -// such as after reading `314e-` or `0.314e+`. -func stateESign(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' { - s.step = stateE0 - return scanContinue - } - return s.error(c, "in exponent of numeric literal") -} - -// stateE0 is the state after reading the mantissa, e, optional sign, -// and at least one digit of the exponent in a number, -// such as after reading `314e-2` or `0.314e+1` or `3.14e0`. -func stateE0(s *scanner, c byte) scanStatus { - if '0' <= c && c <= '9' { - return scanContinue - } - return stateEndValue(s, c) -} - -// stateT is the state after reading `t`. -func stateT(s *scanner, c byte) scanStatus { - if c == 'r' { - s.step = stateTr - return scanContinue - } - return s.error(c, "in literal true (expecting 'r')") -} - -// stateTr is the state after reading `tr`. -func stateTr(s *scanner, c byte) scanStatus { - if c == 'u' { - s.step = stateTru - return scanContinue - } - return s.error(c, "in literal true (expecting 'u')") -} - -// stateTru is the state after reading `tru`. -func stateTru(s *scanner, c byte) scanStatus { - if c == 'e' { - s.step = stateEndValue - return scanContinue - } - return s.error(c, "in literal true (expecting 'e')") -} - -// stateF is the state after reading `f`. -func stateF(s *scanner, c byte) scanStatus { - if c == 'a' { - s.step = stateFa - return scanContinue - } - return s.error(c, "in literal false (expecting 'a')") -} - -// stateFa is the state after reading `fa`. -func stateFa(s *scanner, c byte) scanStatus { - if c == 'l' { - s.step = stateFal - return scanContinue - } - return s.error(c, "in literal false (expecting 'l')") -} - -// stateFal is the state after reading `fal`. -func stateFal(s *scanner, c byte) scanStatus { - if c == 's' { - s.step = stateFals - return scanContinue - } - return s.error(c, "in literal false (expecting 's')") -} - -// stateFals is the state after reading `fals`. -func stateFals(s *scanner, c byte) scanStatus { - if c == 'e' { - s.step = stateEndValue - return scanContinue - } - return s.error(c, "in literal false (expecting 'e')") -} - -// stateN is the state after reading `n`. -func stateN(s *scanner, c byte) scanStatus { - if c == 'u' { - s.step = stateNu - return scanContinue - } - return s.error(c, "in literal null (expecting 'u')") -} - -// stateNu is the state after reading `nu`. -func stateNu(s *scanner, c byte) scanStatus { - if c == 'l' { - s.step = stateNul - return scanContinue - } - return s.error(c, "in literal null (expecting 'l')") -} - -// stateNul is the state after reading `nul`. -func stateNul(s *scanner, c byte) scanStatus { - if c == 'l' { - s.step = stateEndValue - return scanContinue - } - return s.error(c, "in literal null (expecting 'l')") -} - -// stateError is the state after reaching a syntax error, -// such as after reading `[1}` or `5.1.2`. -func stateError(s *scanner, c byte) scanStatus { - return scanError -} - -// error records an error and switches to the error state. -func (s *scanner) error(c byte, context string) scanStatus { - s.step = stateError - s.err = fmt.Errorf("invalid character <<%c>> %s", c, context) - return scanError -} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go b/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go new file mode 100644 index 000000000000..fd8dd520280f --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go @@ -0,0 +1,464 @@ +package json + +import ( + "bytes" + "sync" +) + +const ( + QueryNone = "json" + QueryGeo = "geo" + QueryHAR = "har" + QueryGLTF = "gltf" + maxRecursion = 4096 +) + +var queries = map[string][]query{ + QueryNone: nil, + QueryGeo: {{ + SearchPath: [][]byte{[]byte("type")}, + SearchVals: [][]byte{ + []byte(`"Feature"`), + []byte(`"FeatureCollection"`), + []byte(`"Point"`), + []byte(`"LineString"`), + []byte(`"Polygon"`), + []byte(`"MultiPoint"`), + []byte(`"MultiLineString"`), + []byte(`"MultiPolygon"`), + []byte(`"GeometryCollection"`), + }, + }}, + QueryHAR: {{ + SearchPath: [][]byte{[]byte("log"), []byte("version")}, + }, { + SearchPath: [][]byte{[]byte("log"), []byte("creator")}, + }, { + SearchPath: [][]byte{[]byte("log"), []byte("entries")}, + }}, + QueryGLTF: {{ + SearchPath: [][]byte{[]byte("asset"), []byte("version")}, + SearchVals: [][]byte{[]byte(`"1.0"`), []byte(`"2.0"`)}, + }}, +} + +var parserPool = sync.Pool{ + New: func() any { + return &parserState{maxRecursion: maxRecursion} + }, +} + +// parserState holds the state of JSON parsing. The number of inspected bytes, +// the current path inside the JSON object, etc. +type parserState struct { + // ib represents the number of inspected bytes. + // Because mimetype limits itself to only reading the header of the file, + // it means sometimes the input JSON can be truncated. In that case, we want + // to still detect it as JSON, even if it's invalid/truncated. + // When ib == len(input) it means the JSON was valid (at least the header). + ib int + maxRecursion int + // currPath keeps a track of the JSON keys parsed up. + // It works only for JSON objects. JSON arrays are ignored + // mainly because the functionality is not needed. + currPath [][]byte + // firstToken stores the first JSON token encountered in input. + // TODO: performance would be better if we would stop parsing as soon + // as we see that first token is not what we are interested in. + firstToken int + // querySatisfied is true if both path and value of any queries passed to + // consumeAny are satisfied. + querySatisfied bool +} + +// query holds information about a combination of {"key": "val"} that we're trying +// to search for inside the JSON. +type query struct { + // SearchPath represents the whole path to look for inside the JSON. + // ex: [][]byte{[]byte("foo"), []byte("bar")} matches {"foo": {"bar": "baz"}} + SearchPath [][]byte + // SearchVals represents values to look for when the SearchPath is found. + // Each SearchVal element is tried until one of them matches (logical OR.) + SearchVals [][]byte +} + +func eq(path1, path2 [][]byte) bool { + if len(path1) != len(path2) { + return false + } + for i := range path1 { + if !bytes.Equal(path1[i], path2[i]) { + return false + } + } + return true +} + +// LooksLikeObjectOrArray reports if first non white space character from raw +// is either { or [. Parsing raw as JSON is a heavy operation. When receiving some +// text input we can skip parsing if the input does not even look like JSON. +func LooksLikeObjectOrArray(raw []byte) bool { + for i := range raw { + if isSpace(raw[i]) { + continue + } + return raw[i] == '{' || raw[i] == '[' + } + + return false +} + +// Parse will take out a parser from the pool depending on queryType and tries +// to parse raw bytes as JSON. +func Parse(queryType string, raw []byte) (parsed, inspected, firstToken int, querySatisfied bool) { + p := parserPool.Get().(*parserState) + defer func() { + // Avoid hanging on to too much memory in extreme input cases. + if len(p.currPath) > 128 { + p.currPath = nil + } + parserPool.Put(p) + }() + p.reset() + + qs := queries[queryType] + got := p.consumeAny(raw, qs, 0) + return got, p.ib, p.firstToken, p.querySatisfied +} + +func (p *parserState) reset() { + p.ib = 0 + p.currPath = p.currPath[0:0] + p.firstToken = TokInvalid + p.querySatisfied = false +} + +func (p *parserState) consumeSpace(b []byte) (n int) { + for len(b) > 0 && isSpace(b[0]) { + b = b[1:] + n++ + p.ib++ + } + return n +} + +func (p *parserState) consumeConst(b, cnst []byte) int { + lb := len(b) + for i, c := range cnst { + if lb > i && b[i] == c { + p.ib++ + } else { + return 0 + } + } + return len(cnst) +} + +func (p *parserState) consumeString(b []byte) (n int) { + var c byte + for len(b[n:]) > 0 { + c, n = b[n], n+1 + p.ib++ + switch c { + case '\\': + if len(b[n:]) == 0 { + return 0 + } + switch b[n] { + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + n++ + p.ib++ + continue + case 'u': + n++ + p.ib++ + for j := 0; j < 4 && len(b[n:]) > 0; j++ { + if !isXDigit(b[n]) { + return 0 + } + n++ + p.ib++ + } + continue + default: + return 0 + } + case '"': + return n + default: + continue + } + } + return 0 +} + +func (p *parserState) consumeNumber(b []byte) (n int) { + got := false + var i int + + if len(b) == 0 { + goto out + } + if b[0] == '-' { + b, i = b[1:], i+1 + p.ib++ + } + + for len(b) > 0 { + if !isDigit(b[0]) { + break + } + got = true + b, i = b[1:], i+1 + p.ib++ + } + if len(b) == 0 { + goto out + } + if b[0] == '.' { + b, i = b[1:], i+1 + p.ib++ + } + for len(b) > 0 { + if !isDigit(b[0]) { + break + } + got = true + b, i = b[1:], i+1 + p.ib++ + } + if len(b) == 0 { + goto out + } + if got && (b[0] == 'e' || b[0] == 'E') { + b, i = b[1:], i+1 + p.ib++ + got = false + if len(b) == 0 { + goto out + } + if b[0] == '+' || b[0] == '-' { + b, i = b[1:], i+1 + p.ib++ + } + for len(b) > 0 { + if !isDigit(b[0]) { + break + } + got = true + b, i = b[1:], i+1 + p.ib++ + } + } +out: + if got { + return i + } + return 0 +} + +func (p *parserState) consumeArray(b []byte, qs []query, lvl int) (n int) { + p.currPath = append(p.currPath, []byte{'['}) + if len(b) == 0 { + return 0 + } + + for n < len(b) { + n += p.consumeSpace(b[n:]) + if len(b[n:]) == 0 { + return 0 + } + if b[n] == ']' { + p.ib++ + p.currPath = p.currPath[:len(p.currPath)-1] + return n + 1 + } + innerParsed := p.consumeAny(b[n:], qs, lvl) + if innerParsed == 0 { + return 0 + } + n += innerParsed + if len(b[n:]) == 0 { + return 0 + } + switch b[n] { + case ',': + n += 1 + p.ib++ + continue + case ']': + p.ib++ + return n + 1 + default: + return 0 + } + } + return 0 +} + +func queryPathMatch(qs []query, path [][]byte) int { + for i := range qs { + if eq(qs[i].SearchPath, path) { + return i + } + } + return -1 +} + +func (p *parserState) consumeObject(b []byte, qs []query, lvl int) (n int) { + for n < len(b) { + n += p.consumeSpace(b[n:]) + if len(b[n:]) == 0 { + return 0 + } + if b[n] == '}' { + p.ib++ + return n + 1 + } + if b[n] != '"' { + return 0 + } else { + n += 1 + p.ib++ + } + // queryMatched stores the index of the query satisfying the current path. + queryMatched := -1 + if keyLen := p.consumeString(b[n:]); keyLen == 0 { + return 0 + } else { + p.currPath = append(p.currPath, b[n:n+keyLen-1]) + if !p.querySatisfied { + queryMatched = queryPathMatch(qs, p.currPath) + } + n += keyLen + } + n += p.consumeSpace(b[n:]) + if len(b[n:]) == 0 { + return 0 + } + if b[n] != ':' { + return 0 + } else { + n += 1 + p.ib++ + } + n += p.consumeSpace(b[n:]) + if len(b[n:]) == 0 { + return 0 + } + + if valLen := p.consumeAny(b[n:], qs, lvl); valLen == 0 { + return 0 + } else { + if queryMatched != -1 { + q := qs[queryMatched] + if len(q.SearchVals) == 0 { + p.querySatisfied = true + } + for _, val := range q.SearchVals { + if bytes.Equal(val, bytes.TrimSpace(b[n:n+valLen])) { + p.querySatisfied = true + } + } + } + n += valLen + } + if len(b[n:]) == 0 { + return 0 + } + switch b[n] { + case ',': + p.currPath = p.currPath[:len(p.currPath)-1] + n++ + p.ib++ + continue + case '}': + p.currPath = p.currPath[:len(p.currPath)-1] + p.ib++ + return n + 1 + default: + return 0 + } + } + return 0 +} + +func (p *parserState) consumeAny(b []byte, qs []query, lvl int) (n int) { + // Avoid too much recursion. + if p.maxRecursion != 0 && lvl > p.maxRecursion { + return 0 + } + n += p.consumeSpace(b) + if len(b[n:]) == 0 { + return 0 + } + + var t, rv int + switch b[n] { + case '"': + n++ + p.ib++ + rv = p.consumeString(b[n:]) + t = TokString + case '[': + n++ + p.ib++ + rv = p.consumeArray(b[n:], qs, lvl+1) + t = TokArray + case '{': + n++ + p.ib++ + rv = p.consumeObject(b[n:], qs, lvl+1) + t = TokObject + case 't': + rv = p.consumeConst(b[n:], []byte("true")) + t = TokTrue + case 'f': + rv = p.consumeConst(b[n:], []byte("false")) + t = TokFalse + case 'n': + rv = p.consumeConst(b[n:], []byte("null")) + t = TokNull + default: + rv = p.consumeNumber(b[n:]) + t = TokNumber + } + if lvl == 0 { + p.firstToken = t + } + if len(qs) == 0 { + p.querySatisfied = true + } + if rv <= 0 { + return n + } + n += rv + n += p.consumeSpace(b[n:]) + return n +} + +func isSpace(c byte) bool { + return c == ' ' || c == '\t' || c == '\r' || c == '\n' +} +func isDigit(c byte) bool { + return '0' <= c && c <= '9' +} + +func isXDigit(c byte) bool { + if isDigit(c) { + return true + } + return ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') +} + +const ( + TokInvalid = 0 + TokNull = 1 << iota + TokTrue + TokFalse + TokNumber + TokString + TokArray + TokObject + TokComma +) diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go index 068d00f79aeb..dd7f2417c6ef 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go @@ -137,7 +137,7 @@ func tarParseOctal(b []byte) int64 { if b == 0 { break } - if !(b >= '0' && b <= '7') { + if b < '0' || b > '7' { return -1 } ret = (ret << 3) | int64(b-'0') diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go index 76973201806b..70599b342094 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go @@ -71,7 +71,7 @@ func Dbf(raw []byte, limit uint32) bool { } // 3rd and 4th bytes contain the last update month and day of month. - if !(0 < raw[2] && raw[2] < 13 && 0 < raw[3] && raw[3] < 32) { + if raw[2] == 0 || raw[2] > 12 || raw[3] == 0 || raw[3] > 31 { return false } @@ -153,7 +153,7 @@ func Marc(raw []byte, limit uint32) bool { return bytes.Contains(raw[:min(2048, len(raw))], []byte{0x1E}) } -// Glb matches a glTF model format file. +// GLB matches a glTF model format file. // GLB is the binary file format representation of 3D models saved in // the GL transmission Format (glTF). // GLB uses little endian and its header structure is as follows: @@ -168,7 +168,7 @@ func Marc(raw []byte, limit uint32) bool { // // [glTF specification]: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html // [IANA glTF entry]: https://www.iana.org/assignments/media-types/model/gltf-binary -var Glb = prefix([]byte("\x67\x6C\x54\x46\x02\x00\x00\x00"), +var GLB = prefix([]byte("\x67\x6C\x54\x46\x02\x00\x00\x00"), []byte("\x67\x6C\x54\x46\x01\x00\x00\x00")) // TzIf matches a Time Zone Information Format (TZif) file. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go index f077e16724d6..cade91f18c26 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go @@ -12,13 +12,13 @@ func Shp(raw []byte, limit uint32) bool { return false } - if !(binary.BigEndian.Uint32(raw[0:4]) == 9994 && - binary.BigEndian.Uint32(raw[4:8]) == 0 && - binary.BigEndian.Uint32(raw[8:12]) == 0 && - binary.BigEndian.Uint32(raw[12:16]) == 0 && - binary.BigEndian.Uint32(raw[16:20]) == 0 && - binary.BigEndian.Uint32(raw[20:24]) == 0 && - binary.LittleEndian.Uint32(raw[28:32]) == 1000) { + if binary.BigEndian.Uint32(raw[0:4]) != 9994 || + binary.BigEndian.Uint32(raw[4:8]) != 0 || + binary.BigEndian.Uint32(raw[8:12]) != 0 || + binary.BigEndian.Uint32(raw[12:16]) != 0 || + binary.BigEndian.Uint32(raw[16:20]) != 0 || + binary.BigEndian.Uint32(raw[20:24]) != 0 || + binary.LittleEndian.Uint32(raw[28:32]) != 1000 { return false } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go index cf6446397fef..8178e4707c7a 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go @@ -2,7 +2,6 @@ package magic import ( "bytes" - "strings" "time" "github.com/gabriel-vasile/mimetype/internal/charset" @@ -154,145 +153,75 @@ func Php(raw []byte, limit uint32) bool { // JSON matches a JavaScript Object Notation file. func JSON(raw []byte, limit uint32) bool { - raw = trimLWS(raw) // #175 A single JSON string, number or bool is not considered JSON. // JSON objects and arrays are reported as JSON. - if len(raw) < 2 || (raw[0] != '[' && raw[0] != '{') { - return false - } - parsed, err := json.Scan(raw) - // If the full file content was provided, check there is no error. - if limit == 0 || len(raw) < int(limit) { - return err == nil - } - - // If a section of the file was provided, check if all of it was parsed. - return parsed == len(raw) && len(raw) > 0 + return jsonHelper(raw, limit, json.QueryNone, json.TokObject|json.TokArray) } // GeoJSON matches a RFC 7946 GeoJSON file. // // GeoJSON detection implies searching for key:value pairs like: `"type": "Feature"` // in the input. -// BUG(gabriel-vasile): The "type" key should be searched for in the root object. func GeoJSON(raw []byte, limit uint32) bool { - raw = trimLWS(raw) - if len(raw) == 0 { - return false - } - // GeoJSON is always a JSON object, not a JSON array or any other JSON value. - if raw[0] != '{' { - return false - } + return jsonHelper(raw, limit, json.QueryGeo, json.TokObject) +} - s := []byte(`"type"`) - si, sl := bytes.Index(raw, s), len(s) +// HAR matches a HAR Spec file. +// Spec: http://www.softwareishard.com/blog/har-12-spec/ +func HAR(raw []byte, limit uint32) bool { + return jsonHelper(raw, limit, json.QueryHAR, json.TokObject) +} - if si == -1 { - return false - } +// GLTF matches a GL Transmission Format (JSON) file. +// Visit [glTF specification] and [IANA glTF entry] for more details. +// +// [glTF specification]: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html +// [IANA glTF entry]: https://www.iana.org/assignments/media-types/model/gltf+json +func GLTF(raw []byte, limit uint32) bool { + return jsonHelper(raw, limit, json.QueryGLTF, json.TokObject) +} - // If the "type" string is the suffix of the input, - // there is no need to search for the value of the key. - if si+sl == len(raw) { +func jsonHelper(raw []byte, limit uint32, q string, wantTok int) bool { + if !json.LooksLikeObjectOrArray(raw) { return false } - // Skip the "type" part. - raw = raw[si+sl:] - // Skip any whitespace before the colon. - raw = trimLWS(raw) - // Check for colon. - if len(raw) == 0 || raw[0] != ':' { + lraw := len(raw) + parsed, inspected, firstToken, querySatisfied := json.Parse(q, raw) + if !querySatisfied || firstToken&wantTok == 0 { return false } - // Skip any whitespace after the colon. - raw = trimLWS(raw[1:]) - geoJSONTypes := [][]byte{ - []byte(`"Feature"`), - []byte(`"FeatureCollection"`), - []byte(`"Point"`), - []byte(`"LineString"`), - []byte(`"Polygon"`), - []byte(`"MultiPoint"`), - []byte(`"MultiLineString"`), - []byte(`"MultiPolygon"`), - []byte(`"GeometryCollection"`), - } - for _, t := range geoJSONTypes { - if bytes.HasPrefix(raw, t) { - return true - } + // If the full file content was provided, check that the whole input was parsed. + if limit == 0 || lraw < int(limit) { + return parsed == lraw } - return false + // If a section of the file was provided, check if all of it was inspected. + // In other words, check that if there was a problem parsing, that problem + // occured at the last byte in the input. + return inspected == lraw && lraw > 0 } // NdJSON matches a Newline delimited JSON file. All complete lines from raw // must be valid JSON documents meaning they contain one of the valid JSON data // types. func NdJSON(raw []byte, limit uint32) bool { - lCount, hasObjOrArr := 0, false + lCount, objOrArr := 0, 0 raw = dropLastLine(raw, limit) var l []byte for len(raw) != 0 { l, raw = scanLine(raw) - // Empty lines are allowed in NDJSON. - if l = trimRWS(trimLWS(l)); len(l) == 0 { - continue - } - _, err := json.Scan(l) - if err != nil { + _, inspected, firstToken, _ := json.Parse(json.QueryNone, l) + if len(l) != inspected { return false } - if l[0] == '[' || l[0] == '{' { - hasObjOrArr = true + if firstToken == json.TokArray || firstToken == json.TokObject { + objOrArr++ } lCount++ } - return lCount > 1 && hasObjOrArr -} - -// HAR matches a HAR Spec file. -// Spec: http://www.softwareishard.com/blog/har-12-spec/ -func HAR(raw []byte, limit uint32) bool { - s := []byte(`"log"`) - si, sl := bytes.Index(raw, s), len(s) - - if si == -1 { - return false - } - - // If the "log" string is the suffix of the input, - // there is no need to search for the value of the key. - if si+sl == len(raw) { - return false - } - // Skip the "log" part. - raw = raw[si+sl:] - // Skip any whitespace before the colon. - raw = trimLWS(raw) - // Check for colon. - if len(raw) == 0 || raw[0] != ':' { - return false - } - // Skip any whitespace after the colon. - raw = trimLWS(raw[1:]) - - harJSONTypes := [][]byte{ - []byte(`"version"`), - []byte(`"creator"`), - []byte(`"entries"`), - } - for _, t := range harJSONTypes { - si := bytes.Index(raw, t) - if si > -1 { - return true - } - } - - return false + return lCount > 1 && objOrArr > 0 } // Svg matches a SVG file. @@ -305,32 +234,31 @@ func Srt(raw []byte, _ uint32) bool { line, raw := scanLine(raw) // First line must be 1. - if string(line) != "1" { + if len(line) != 1 || line[0] != '1' { return false } line, raw = scanLine(raw) - secondLine := string(line) - // Timestamp format (e.g: 00:02:16,612 --> 00:02:19,376) limits secondLine + // Timestamp format (e.g: 00:02:16,612 --> 00:02:19,376) limits second line // length to exactly 29 characters. - if len(secondLine) != 29 { + if len(line) != 29 { return false } // Decimal separator of fractional seconds in the timestamps must be a // comma, not a period. - if strings.Contains(secondLine, ".") { + if bytes.IndexByte(line, '.') != -1 { return false } - // Second line must be a time range. - ts := strings.Split(secondLine, " --> ") - if len(ts) != 2 { + sep := []byte(" --> ") + i := bytes.Index(line, sep) + if i == -1 { return false } const layout = "15:04:05,000" - t0, err := time.Parse(layout, ts[0]) + t0, err := time.Parse(layout, string(line[:i])) if err != nil { return false } - t1, err := time.Parse(layout, ts[1]) + t1, err := time.Parse(layout, string(line[i+len(sep):])) if err != nil { return false } diff --git a/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md index f9bf03cba6d6..6f45bfbb6480 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md +++ b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md @@ -1,4 +1,4 @@ -## 178 Supported MIME types +## 179 Supported MIME types This file is automatically generated when running tests. Do not edit manually. Extension | MIME type | Aliases @@ -171,6 +171,7 @@ Extension | MIME type | Aliases **.json** | application/json | - **.geojson** | application/geo+json | - **.har** | application/json | - +**.gltf** | model/gltf+json | - **.ndjson** | application/x-ndjson | - **.rtf** | text/rtf | application/rtf **.srt** | application/x-subrip | application/x-srt, text/x-srt diff --git a/vendor/github.com/gabriel-vasile/mimetype/tree.go b/vendor/github.com/gabriel-vasile/mimetype/tree.go index b5f5662277ab..63a2093a4b6f 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/tree.go +++ b/vendor/github.com/gabriel-vasile/mimetype/tree.go @@ -83,7 +83,7 @@ var ( text = newMIME("text/plain", ".txt", magic.Text, html, svg, xml, php, js, lua, perl, python, json, ndJSON, rtf, srt, tcl, csv, tsv, vCard, iCalendar, warc, vtt) xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2). alias("application/xml") - json = newMIME("application/json", ".json", magic.JSON, geoJSON, har) + json = newMIME("application/json", ".json", magic.JSON, geoJSON, har, gltf) har = newMIME("application/json", ".har", magic.HAR) csv = newMIME("text/csv", ".csv", magic.Csv) tsv = newMIME("text/tab-separated-values", ".tsv", magic.Tsv) @@ -262,7 +262,8 @@ var ( pat = newMIME("image/x-gimp-pat", ".pat", magic.Pat) gbr = newMIME("image/x-gimp-gbr", ".gbr", magic.Gbr) xfdf = newMIME("application/vnd.adobe.xfdf", ".xfdf", magic.Xfdf) - glb = newMIME("model/gltf-binary", ".glb", magic.Glb) + glb = newMIME("model/gltf-binary", ".glb", magic.GLB) + gltf = newMIME("model/gltf+json", ".gltf", magic.GLTF) jxr = newMIME("image/jxr", ".jxr", magic.Jxr).alias("image/vnd.ms-photo") parquet = newMIME("application/vnd.apache.parquet", ".parquet", magic.Par1). alias("application/x-parquet") diff --git a/vendor/github.com/go-openapi/analysis/flatten.go b/vendor/github.com/go-openapi/analysis/flatten.go index ecf7e36d6151..ebedcc9df325 100644 --- a/vendor/github.com/go-openapi/analysis/flatten.go +++ b/vendor/github.com/go-openapi/analysis/flatten.go @@ -267,6 +267,12 @@ func nameInlinedSchemas(opts *FlattenOpts) error { } func removeUnused(opts *FlattenOpts) { + for removeUnusedSinglePass(opts) { + // continue until no unused definition remains + } +} + +func removeUnusedSinglePass(opts *FlattenOpts) (hasRemoved bool) { expected := make(map[string]struct{}) for k := range opts.Swagger().Definitions { expected[path.Join(definitionsPath, jsonpointer.Escape(k))] = struct{}{} @@ -277,6 +283,7 @@ func removeUnused(opts *FlattenOpts) { } for k := range expected { + hasRemoved = true debugLog("removing unused definition %s", path.Base(k)) if opts.Verbose { log.Printf("info: removing unused definition: %s", path.Base(k)) @@ -285,6 +292,8 @@ func removeUnused(opts *FlattenOpts) { } opts.Spec.reload() // re-analyze + + return hasRemoved } func importKnownRef(entry sortref.RefRevIdx, refStr, newName string, opts *FlattenOpts) error { @@ -331,7 +340,7 @@ func importNewRef(entry sortref.RefRevIdx, refStr string, opts *FlattenOpts) err } // generate a unique name - isOAIGen means that a naming conflict was resolved by changing the name - newName, isOAIGen = uniqifyName(opts.Swagger().Definitions, nameFromRef(entry.Ref)) + newName, isOAIGen = uniqifyName(opts.Swagger().Definitions, nameFromRef(entry.Ref, opts)) debugLog("new name for [%s]: %s - with name conflict:%t", strings.Join(entry.Keys, ", "), newName, isOAIGen) opts.flattenContext.resolved[refStr] = newName @@ -649,6 +658,7 @@ func namePointers(opts *FlattenOpts) error { refsToReplace := make(map[string]SchemaRef, len(opts.Spec.references.schemas)) for k, ref := range opts.Spec.references.allRefs { + debugLog("name pointers: %q => %#v", k, ref) if path.Dir(ref.String()) == definitionsPath { // this a ref to a top-level definition: ok continue @@ -766,6 +776,10 @@ func flattenAnonPointer(key string, v SchemaRef, refsToReplace map[string]Schema // identifying edge case when the namer did nothing because we point to a non-schema object // no definition is created and we expand the $ref for all callers + debugLog("decide what to do with the schema pointed to: asch.IsSimpleSchema=%t, len(callers)=%d, parts.IsSharedParam=%t, parts.IsSharedResponse=%t", + asch.IsSimpleSchema, len(callers), parts.IsSharedParam(), parts.IsSharedResponse(), + ) + if (!asch.IsSimpleSchema || len(callers) > 1) && !parts.IsSharedParam() && !parts.IsSharedResponse() { debugLog("replace JSON pointer at [%s] by definition: %s", key, v.Ref.String()) if err := namer.Name(v.Ref.String(), v.Schema, asch); err != nil { @@ -788,6 +802,7 @@ func flattenAnonPointer(key string, v SchemaRef, refsToReplace map[string]Schema return nil } + // everything that is a simple schema and not factorizable is expanded debugLog("expand JSON pointer for key=%s", key) if err := replace.UpdateRefWithSchema(opts.Swagger(), key, v.Schema); err != nil { diff --git a/vendor/github.com/go-openapi/analysis/flatten_name.go b/vendor/github.com/go-openapi/analysis/flatten_name.go index 24840752e2f1..c7d7938ebe6b 100644 --- a/vendor/github.com/go-openapi/analysis/flatten_name.go +++ b/vendor/github.com/go-openapi/analysis/flatten_name.go @@ -33,12 +33,14 @@ func (isn *InlineSchemaNamer) Name(key string, schema *spec.Schema, aschema *Ana } // create unique name - newName, isOAIGen := uniqifyName(isn.Spec.Definitions, swag.ToJSONName(name)) + mangle := mangler(isn.opts) + newName, isOAIGen := uniqifyName(isn.Spec.Definitions, mangle(name)) // clone schema sch := schutils.Clone(schema) // replace values on schema + debugLog("rewriting schema to ref: key=%s with new name: %s", key, newName) if err := replace.RewriteSchemaToRef(isn.Spec, key, spec.MustCreateRef(path.Join(definitionsPath, newName))); err != nil { return fmt.Errorf("error while creating definition %q from inline schema: %w", newName, err) @@ -149,13 +151,15 @@ func namesFromKey(parts sortref.SplitKey, aschema *AnalyzedSchema, operations ma startIndex int ) - if parts.IsOperation() { + switch { + case parts.IsOperation(): baseNames, startIndex = namesForOperation(parts, operations) - } - - // definitions - if parts.IsDefinition() { + case parts.IsDefinition(): baseNames, startIndex = namesForDefinition(parts) + default: + // this a non-standard pointer: build a name by concatenating its parts + baseNames = [][]string{parts} + startIndex = len(baseNames) + 1 } result := make([]string, 0, len(baseNames)) @@ -169,6 +173,7 @@ func namesFromKey(parts sortref.SplitKey, aschema *AnalyzedSchema, operations ma } sort.Strings(result) + debugLog("names from parts: %v => %v", parts, result) return result } @@ -256,10 +261,20 @@ func partAdder(aschema *AnalyzedSchema) sortref.PartAdder { } } -func nameFromRef(ref spec.Ref) string { +func mangler(o *FlattenOpts) func(string) string { + if o.KeepNames { + return func(in string) string { return in } + } + + return swag.ToJSONName +} + +func nameFromRef(ref spec.Ref, o *FlattenOpts) string { + mangle := mangler(o) + u := ref.GetURL() if u.Fragment != "" { - return swag.ToJSONName(path.Base(u.Fragment)) + return mangle(path.Base(u.Fragment)) } if u.Path != "" { @@ -267,14 +282,14 @@ func nameFromRef(ref spec.Ref) string { if bn != "" && bn != "/" { ext := path.Ext(bn) if ext != "" { - return swag.ToJSONName(bn[:len(bn)-len(ext)]) + return mangle(bn[:len(bn)-len(ext)]) } - return swag.ToJSONName(bn) + return mangle(bn) } } - return swag.ToJSONName(strings.ReplaceAll(u.Host, ".", " ")) + return mangle(strings.ReplaceAll(u.Host, ".", " ")) } // GenLocation indicates from which section of the specification (models or operations) a definition has been created. diff --git a/vendor/github.com/go-openapi/analysis/flatten_options.go b/vendor/github.com/go-openapi/analysis/flatten_options.go index c5bb97b0a693..c943fe1e84a3 100644 --- a/vendor/github.com/go-openapi/analysis/flatten_options.go +++ b/vendor/github.com/go-openapi/analysis/flatten_options.go @@ -26,6 +26,7 @@ type FlattenOpts struct { Verbose bool // enable some reporting on possible name conflicts detected RemoveUnused bool // When true, remove unused parameters, responses and definitions after expansion/flattening ContinueOnError bool // Continue when spec expansion issues are found + KeepNames bool // Do not attempt to jsonify names from references when flattening /* Extra keys */ _ struct{} // require keys diff --git a/vendor/github.com/go-openapi/analysis/internal/debug/debug.go b/vendor/github.com/go-openapi/analysis/internal/debug/debug.go index ec0fec022986..39f55a97bfdc 100644 --- a/vendor/github.com/go-openapi/analysis/internal/debug/debug.go +++ b/vendor/github.com/go-openapi/analysis/internal/debug/debug.go @@ -29,7 +29,7 @@ var ( // GetLogger provides a prefix debug logger func GetLogger(prefix string, debug bool) func(string, ...interface{}) { if debug { - logger := log.New(output, fmt.Sprintf("%s:", prefix), log.LstdFlags) + logger := log.New(output, prefix+":", log.LstdFlags) return func(msg string, args ...interface{}) { _, file1, pos1, _ := runtime.Caller(1) @@ -37,5 +37,5 @@ func GetLogger(prefix string, debug bool) func(string, ...interface{}) { } } - return func(msg string, args ...interface{}) {} + return func(_ string, _ ...interface{}) {} } diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go index 545483bd624c..c0f43e728a3f 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go @@ -1,6 +1,7 @@ package replace import ( + "encoding/json" "fmt" "net/url" "os" @@ -40,6 +41,8 @@ func RewriteSchemaToRef(sp *spec.Swagger, key string, ref spec.Ref) error { if refable.Schema != nil { refable.Schema = &spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}} } + case map[string]interface{}: // this happens e.g. if a schema points to an extension unmarshaled as map[string]interface{} + return rewriteParentRef(sp, key, ref) default: return fmt.Errorf("no schema with ref found at %s for %T", key, value) } @@ -120,6 +123,9 @@ func rewriteParentRef(sp *spec.Swagger, key string, ref spec.Ref) error { case spec.SchemaProperties: container[entry] = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}} + case *interface{}: + *container = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}} + // NOTE: can't have case *spec.SchemaOrBool = parent in this case is *Schema default: @@ -385,8 +391,9 @@ DOWNREF: err := asSchema.UnmarshalJSON(asJSON) if err != nil { return nil, - fmt.Errorf("invalid type for resolved JSON pointer %s. Expected a schema a, got: %T", - currentRef.String(), value) + fmt.Errorf("invalid type for resolved JSON pointer %s. Expected a schema a, got: %T (%v)", + currentRef.String(), value, err, + ) } warnings = append(warnings, fmt.Sprintf("found $ref %q (response) interpreted as schema", currentRef.String())) @@ -402,8 +409,9 @@ DOWNREF: var asSchema spec.Schema if err := asSchema.UnmarshalJSON(asJSON); err != nil { return nil, - fmt.Errorf("invalid type for resolved JSON pointer %s. Expected a schema a, got: %T", - currentRef.String(), value) + fmt.Errorf("invalid type for resolved JSON pointer %s. Expected a schema a, got: %T (%v)", + currentRef.String(), value, err, + ) } warnings = append(warnings, fmt.Sprintf("found $ref %q (parameter) interpreted as schema", currentRef.String())) @@ -414,9 +422,25 @@ DOWNREF: currentRef = asSchema.Ref default: - return nil, - fmt.Errorf("unhandled type to resolve JSON pointer %s. Expected a Schema, got: %T", - currentRef.String(), value) + // fallback: attempts to resolve the pointer as a schema + if refable == nil { + break DOWNREF + } + + asJSON, _ := json.Marshal(refable) + var asSchema spec.Schema + if err := asSchema.UnmarshalJSON(asJSON); err != nil { + return nil, + fmt.Errorf("unhandled type to resolve JSON pointer %s. Expected a Schema, got: %T (%v)", + currentRef.String(), value, err, + ) + } + warnings = append(warnings, fmt.Sprintf("found $ref %q (%T) interpreted as schema", currentRef.String(), refable)) + + if asSchema.Ref.String() == "" { + break DOWNREF + } + currentRef = asSchema.Ref } } diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go index 18e552eadcef..ac80fc2e8320 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go @@ -69,7 +69,7 @@ func KeyParts(key string) SplitKey { return res } -// SplitKey holds of the parts of a /-separated key, soi that their location may be determined. +// SplitKey holds of the parts of a /-separated key, so that their location may be determined. type SplitKey []string // IsDefinition is true when the split key is in the #/definitions section of a spec diff --git a/vendor/github.com/go-openapi/analysis/mixin.go b/vendor/github.com/go-openapi/analysis/mixin.go index 57cb7a9dc32d..7785a29b27dd 100644 --- a/vendor/github.com/go-openapi/analysis/mixin.go +++ b/vendor/github.com/go-openapi/analysis/mixin.go @@ -53,7 +53,7 @@ import ( // collisions. func Mixin(primary *spec.Swagger, mixins ...*spec.Swagger) []string { skipped := make([]string, 0, len(mixins)) - opIds := getOpIds(primary) + opIDs := getOpIDs(primary) initPrimary(primary) for i, m := range mixins { @@ -74,7 +74,7 @@ func Mixin(primary *spec.Swagger, mixins ...*spec.Swagger) []string { skipped = append(skipped, mergeDefinitions(primary, m)...) // merging paths requires a map of operationIDs to work with - skipped = append(skipped, mergePaths(primary, m, opIds, i)...) + skipped = append(skipped, mergePaths(primary, m, opIDs, i)...) skipped = append(skipped, mergeParameters(primary, m)...) @@ -84,9 +84,9 @@ func Mixin(primary *spec.Swagger, mixins ...*spec.Swagger) []string { return skipped } -// getOpIds extracts all the paths..operationIds from the given +// getOpIDs extracts all the paths..operationIds from the given // spec and returns them as the keys in a map with 'true' values. -func getOpIds(s *spec.Swagger) map[string]bool { +func getOpIDs(s *spec.Swagger) map[string]bool { rv := make(map[string]bool) if s.Paths == nil { return rv @@ -179,7 +179,7 @@ func mergeDefinitions(primary *spec.Swagger, m *spec.Swagger) (skipped []string) return } -func mergePaths(primary *spec.Swagger, m *spec.Swagger, opIds map[string]bool, mixIndex int) (skipped []string) { +func mergePaths(primary *spec.Swagger, m *spec.Swagger, opIDs map[string]bool, mixIndex int) (skipped []string) { if m.Paths != nil { for k, v := range m.Paths.Paths { if _, exists := primary.Paths.Paths[k]; exists { @@ -198,10 +198,10 @@ func mergePaths(primary *spec.Swagger, m *spec.Swagger, opIds map[string]bool, m // all the proivded specs are already unique. piops := pathItemOps(v) for _, piop := range piops { - if opIds[piop.ID] { + if opIDs[piop.ID] { piop.ID = fmt.Sprintf("%v%v%v", piop.ID, "Mixin", mixIndex) } - opIds[piop.ID] = true + opIDs[piop.ID] = true } primary.Paths.Paths[k] = v } diff --git a/vendor/github.com/go-openapi/analysis/schema.go b/vendor/github.com/go-openapi/analysis/schema.go index 95f35dc756a3..ab190db5b785 100644 --- a/vendor/github.com/go-openapi/analysis/schema.go +++ b/vendor/github.com/go-openapi/analysis/schema.go @@ -1,7 +1,7 @@ package analysis import ( - "fmt" + "errors" "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" @@ -19,7 +19,7 @@ type SchemaOpts struct { // patterns. func Schema(opts SchemaOpts) (*AnalyzedSchema, error) { if opts.Schema == nil { - return nil, fmt.Errorf("no schema to analyze") + return nil, errors.New("no schema to analyze") } a := &AnalyzedSchema{ diff --git a/vendor/github.com/go-openapi/jsonpointer/.cliff.toml b/vendor/github.com/go-openapi/jsonpointer/.cliff.toml new file mode 100644 index 000000000000..702629f5dc30 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/.cliff.toml @@ -0,0 +1,181 @@ +# git-cliff ~ configuration file +# https://git-cliff.org/docs/configuration + +[changelog] +header = """ +""" + +footer = """ + +----- + +**[{{ remote.github.repo }}]({{ self::remote_url() }}) license terms** + +[![License][license-badge]][license-url] + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: {{ self::remote_url() }}/?tab=Apache-2.0-1-ov-file#readme + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" + +body = """ +{%- if version %} +## [{{ version | trim_start_matches(pat="v") }}]({{ self::remote_url() }}/tree/{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }} +{%- else %} +## [unreleased] +{%- endif %} +{%- if message %} + {%- raw %}\n{% endraw %} +{{ message }} + {%- raw %}\n{% endraw %} +{%- endif %} +{%- if version %} + {%- if previous.version %} + +**Full Changelog**: <{{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}> + {%- endif %} +{%- else %} + {%- raw %}\n{% endraw %} +{%- endif %} + +{%- if statistics %}{% if statistics.commit_count %} + {%- raw %}\n{% endraw %} +{{ statistics.commit_count }} commits in this release. + {%- raw %}\n{% endraw %} +{%- endif %}{% endif %} +----- + +{%- for group, commits in commits | group_by(attribute="group") %} + {%- raw %}\n{% endraw %} +### {{ group | upper_first }} + {%- raw %}\n{% endraw %} + {%- for commit in commits %} + {%- if commit.remote.pr_title %} + {%- set commit_message = commit.remote.pr_title %} + {%- else %} + {%- set commit_message = commit.message %} + {%- endif %} +* {{ commit_message | split(pat="\n") | first | trim }} + {%- if commit.remote.username %} +{%- raw %} {% endraw %}by [@{{ commit.remote.username }}](https://github.com/{{ commit.remote.username }}) + {%- endif %} + {%- if commit.remote.pr_number %} +{%- raw %} {% endraw %}in [#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) + {%- endif %} +{%- raw %} {% endraw %}[...]({{ self::remote_url() }}/commit/{{ commit.id }}) + {%- endfor %} +{%- endfor %} + +{%- if github %} +{%- raw %}\n{% endraw -%} + {%- set all_contributors = github.contributors | length %} + {%- if github.contributors | filter(attribute="username", value="dependabot[bot]") | length < all_contributors %} +----- + +### People who contributed to this release + {% endif %} + {%- for contributor in github.contributors | filter(attribute="username") | sort(attribute="username") %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* [@{{ contributor.username }}](https://github.com/{{ contributor.username }}) + {%- endif %} + {%- endfor %} + + {% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} +----- + {%- raw %}\n{% endraw %} + +### New Contributors + {%- endif %} + + {%- for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* @{{ contributor.username }} made their first contribution + {%- if contributor.pr_number %} + in [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ + {%- endif %} + {%- endif %} + {%- endfor %} +{%- endif %} + +{%- raw %}\n{% endraw %} + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" +# Remove leading and trailing whitespaces from the changelog's body. +trim = true +# Render body even when there are no releases to process. +render_always = true +# An array of regex based postprocessors to modify the changelog. +postprocessors = [ + # Replace the placeholder with a URL. + #{ pattern = '', replace = "https://github.com/orhun/git-cliff" }, +] +# output file path +# output = "test.md" + +[git] +# Parse commits according to the conventional commits specification. +# See https://www.conventionalcommits.org +conventional_commits = false +# Exclude commits that do not match the conventional commits specification. +filter_unconventional = false +# Require all commits to be conventional. +# Takes precedence over filter_unconventional. +require_conventional = false +# Split commits on newlines, treating each line as an individual commit. +split_commits = false +# An array of regex based parsers to modify commit messages prior to further processing. +commit_preprocessors = [ + # Replace issue numbers with link templates to be updated in `changelog.postprocessors`. + #{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, + # Check spelling of the commit message using https://github.com/crate-ci/typos. + # If the spelling is incorrect, it will be fixed automatically. + #{ pattern = '.*', replace_command = 'typos --write-changes -' } +] +# Prevent commits that are breaking from being excluded by commit parsers. +protect_breaking_commits = false +# An array of regex based parsers for extracting data from the commit message. +# Assigns commits to groups. +# Optionally sets the commit's scope and can decide to exclude commits from further processing. +commit_parsers = [ + { message = "^[Cc]hore\\([Rr]elease\\): prepare for", skip = true }, + { message = "(^[Mm]erge)|([Mm]erge conflict)", skip = true }, + { field = "author.name", pattern = "dependabot*", group = "Updates" }, + { message = "([Ss]ecurity)|([Vv]uln)", group = "Security" }, + { body = "(.*[Ss]ecurity)|([Vv]uln)", group = "Security" }, + { message = "([Cc]hore\\(lint\\))|(style)|(lint)|(codeql)|(golangci)", group = "Code quality" }, + { message = "(^[Dd]oc)|((?i)readme)|(badge)|(typo)|(documentation)", group = "Documentation" }, + { message = "(^[Ff]eat)|(^[Ee]nhancement)", group = "Implemented enhancements" }, + { message = "(^ci)|(\\(ci\\))|(fixup\\s+ci)|(fix\\s+ci)|(license)|(example)", group = "Miscellaneous tasks" }, + { message = "^test", group = "Testing" }, + { message = "(^fix)|(panic)", group = "Fixed bugs" }, + { message = "(^refact)|(rework)", group = "Refactor" }, + { message = "(^[Pp]erf)|(performance)", group = "Performance" }, + { message = "(^[Cc]hore)", group = "Miscellaneous tasks" }, + { message = "^[Rr]evert", group = "Reverted changes" }, + { message = "(upgrade.*?go)|(go\\s+version)", group = "Updates" }, + { message = ".*", group = "Other" }, +] +# Exclude commits that are not matched by any commit parser. +filter_commits = false +# An array of link parsers for extracting external references, and turning them into URLs, using regex. +link_parsers = [] +# Include only the tags that belong to the current branch. +use_branch_tags = false +# Order releases topologically instead of chronologically. +topo_order = false +# Order releases topologically instead of chronologically. +topo_order_commits = true +# Order of commits in each group/release within the changelog. +# Allowed values: newest, oldest +sort_commits = "newest" +# Process submodules commits +recurse_submodules = false + +#[remote.github] +#owner = "go-openapi" diff --git a/vendor/github.com/go-openapi/jsonpointer/.gitignore b/vendor/github.com/go-openapi/jsonpointer/.gitignore index 769c244007b5..59cd29489150 100644 --- a/vendor/github.com/go-openapi/jsonpointer/.gitignore +++ b/vendor/github.com/go-openapi/jsonpointer/.gitignore @@ -1 +1,4 @@ -secrets.yml +*.out +*.cov +.idea +.env diff --git a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml index d2fafb8a2bb0..fdae591bce71 100644 --- a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml +++ b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml @@ -1,56 +1,66 @@ -linters-settings: - gocyclo: - min-complexity: 45 - dupl: - threshold: 200 - goconst: - min-len: 2 - min-occurrences: 3 - +version: "2" linters: - enable-all: true + default: all disable: - - recvcheck - - unparam - - lll - - gochecknoinits - - gochecknoglobals + - depguard - funlen - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage + - exhaustruct - nlreturn - - errorlint - - nestif - - godot - - gofumpt + - nonamedreturns + - noinlineerr - paralleltest + - recvcheck + - testpackage - tparallel - - thelper - - exhaustruct - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - #- deadcode - #- interfacer - #- scopelint - #- varcheck - #- structcheck - #- golint - #- nosnakecase - #- maligned - #- goerr113 - #- ifshort - #- gomnd - #- exhaustivestruct + - whitespace + - wrapcheck + - wsl + - wsl_v5 + settings: + dupl: + threshold: 200 + goconst: + min-len: 2 + min-occurrences: 3 + cyclop: + max-complexity: 20 + gocyclo: + min-complexity: 20 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + - gofumpt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ +issues: + # Maximum issues count per one linter. + # Set to 0 to disable. + # Default: 50 + max-issues-per-linter: 0 + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 0 diff --git a/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md b/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md new file mode 100644 index 000000000000..03c098316d45 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md @@ -0,0 +1,24 @@ +# Contributors + +- Repository: ['go-openapi/jsonpointer'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 12 | 95 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 48 | https://github.com/go-openapi/jsonpointer/commits?author=fredbi | +| @casualjim | 33 | https://github.com/go-openapi/jsonpointer/commits?author=casualjim | +| @magodo | 3 | https://github.com/go-openapi/jsonpointer/commits?author=magodo | +| @youyuanwu | 3 | https://github.com/go-openapi/jsonpointer/commits?author=youyuanwu | +| @gaiaz-iusipov | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gaiaz-iusipov | +| @gbjk | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gbjk | +| @gordallott | 1 | https://github.com/go-openapi/jsonpointer/commits?author=gordallott | +| @ianlancetaylor | 1 | https://github.com/go-openapi/jsonpointer/commits?author=ianlancetaylor | +| @mfleader | 1 | https://github.com/go-openapi/jsonpointer/commits?author=mfleader | +| @Neo2308 | 1 | https://github.com/go-openapi/jsonpointer/commits?author=Neo2308 | +| @olivierlemasle | 1 | https://github.com/go-openapi/jsonpointer/commits?author=olivierlemasle | +| @testwill | 1 | https://github.com/go-openapi/jsonpointer/commits?author=testwill | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/jsonpointer/LICENSE b/vendor/github.com/go-openapi/jsonpointer/LICENSE index d64569567334..261eeb9e9f8b 100644 --- a/vendor/github.com/go-openapi/jsonpointer/LICENSE +++ b/vendor/github.com/go-openapi/jsonpointer/LICENSE @@ -1,4 +1,3 @@ - Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/vendor/github.com/go-openapi/jsonpointer/NOTICE b/vendor/github.com/go-openapi/jsonpointer/NOTICE new file mode 100644 index 000000000000..f3b51939a95b --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/NOTICE @@ -0,0 +1,39 @@ +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonpointer, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0. + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original software was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). + +github.com/sigh-399/jsonpointer +=========================== + +// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// SPDX-License-Identifier: Apache-2.0 + +Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md index 0108f1d572d7..b61b63fd9af8 100644 --- a/vendor/github.com/go-openapi/jsonpointer/README.md +++ b/vendor/github.com/go-openapi/jsonpointer/README.md @@ -1,19 +1,149 @@ -# gojsonpointer [![Build Status](https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/jsonpointer/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) +# jsonpointer -[![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/jsonpointer/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer.svg)](https://pkg.go.dev/github.com/go-openapi/jsonpointer) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/jsonpointer)](https://goreportcard.com/report/github.com/go-openapi/jsonpointer) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Slack Channel][slack-logo]![slack-badge]][slack-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -An implementation of JSON Pointer - Go language +--- + +An implementation of JSON Pointer for golang, which supports go `struct`. ## Status -Completed YES -Tested YES +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/jsonpointer +``` + +## Basic usage + +See also some [examples](./examples_test.go) + +### Retrieving a value + +```go + import ( + "github.com/go-openapi/jsonpointer" + ) + + + var doc any + + ... + + pointer, err := jsonpointer.New("/foo/1") + if err != nil { + ... // error: e.g. invalid JSON pointer specification + } + + value, kind, err := pointer.Get(doc) + if err != nil { + ... // error: e.g. key not found, index out of bounds, etc. + } + + ... +``` + +### Setting a value + +```go + ... + var doc any + ... + pointer, err := jsonpointer.New("/foo/1") + if err != nil { + ... // error: e.g. invalid JSON pointer specification + } + + doc, err = p.Set(doc, "value") + if err != nil { + ... // error: e.g. key not found, index out of bounds, etc. + } +``` + +## Change log + +See ## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 -### Note -The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. + + +also known as [RFC6901](https://www.rfc-editor.org/rfc/rfc6901) + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +See the license [NOTICE](./NOTICE), which recalls the licensing terms of all the pieces of software +on top of which it has been built. + +## Limitations + +The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, +the reference token MUST contain either...' is not implemented. + +That is because our implementation of the JSON pointer only supports explicit references to array elements: +the provision in the spec to resolve non-existent members as "the last element in the array", +using the special trailing character "-" is not implemented. + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/jsonpointer/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/jsonpointer +[vuln-scan-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/jsonpointer/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/jsonpointer/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fjsonpointer +[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonpointer.svg +[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonpointer + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonpointer +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonpointer +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonpointer +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonpointer + +[doc-badge]: https://img.shields.io/badge/doc-site-blue?link=https%3A%2F%2Fgoswagger.io%2Fgo-openapi%2F +[doc-url]: https://goswagger.io/go-openapi +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/jsonpointer +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/jsonpointer/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/jsonpointer +[goversion-url]: https://github.com/go-openapi/jsonpointer/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/jsonpointer +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/jsonpointer/latest diff --git a/vendor/github.com/go-openapi/jsonpointer/SECURITY.md b/vendor/github.com/go-openapi/jsonpointer/SECURITY.md new file mode 100644 index 000000000000..2a7b6f0910d9 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.22.x | :white_check_mark: | + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +please report it privately to the maintainers. + +Please follow the instructions provided by github to +[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). + +TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". diff --git a/vendor/github.com/go-openapi/jsonpointer/errors.go b/vendor/github.com/go-openapi/jsonpointer/errors.go index b84343d9d74e..8c50dde8bcf3 100644 --- a/vendor/github.com/go-openapi/jsonpointer/errors.go +++ b/vendor/github.com/go-openapi/jsonpointer/errors.go @@ -1,5 +1,10 @@ +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package jsonpointer +import "fmt" + type pointerError string func (e pointerError) Error() string { @@ -7,12 +12,24 @@ func (e pointerError) Error() string { } const ( - // ErrPointer is an error raised by the jsonpointer package + // ErrPointer is a sentinel error raised by all errors from this package. ErrPointer pointerError = "JSON pointer error" - // ErrInvalidStart states that a JSON pointer must start with a separator ("/") + // ErrInvalidStart states that a JSON pointer must start with a separator ("/"). ErrInvalidStart pointerError = `JSON pointer must be empty or start with a "` + pointerSeparator - // ErrUnsupportedValueType indicates that a value of the wrong type is being set + // ErrUnsupportedValueType indicates that a value of the wrong type is being set. ErrUnsupportedValueType pointerError = "only structs, pointers, maps and slices are supported for setting values" ) + +func errNoKey(key string) error { + return fmt.Errorf("object has no key %q: %w", key, ErrPointer) +} + +func errOutOfBounds(length, idx int) error { + return fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", length-1, idx, ErrPointer) +} + +func errInvalidReference(token string) error { + return fmt.Errorf("invalid token reference %q: %w", token, ErrPointer) +} diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go index a08cd68ac04e..7df49af3b96a 100644 --- a/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ b/vendor/github.com/go-openapi/jsonpointer/pointer.go @@ -1,28 +1,7 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonpointer -// repository-desc An implementation of JSON Pointer - Go language -// -// description Main and unique file. -// -// created 25-02-2013 +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 +// Package jsonpointer provides a golang implementation for json pointers. package jsonpointer import ( @@ -33,7 +12,7 @@ import ( "strconv" "strings" - "github.com/go-openapi/swag" + "github.com/go-openapi/swag/jsonname" ) const ( @@ -41,70 +20,273 @@ const ( pointerSeparator = `/` ) -var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() -var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() - -// JSONPointable is an interface for structs to implement when they need to customize the -// json pointer process +// JSONPointable is an interface for structs to implement, +// when they need to customize the json pointer process or want to avoid the use of reflection. type JSONPointable interface { - JSONLookup(string) (any, error) + // JSONLookup returns a value pointed at this (unescaped) key. + JSONLookup(key string) (any, error) } -// JSONSetable is an interface for structs to implement when they need to customize the -// json pointer process +// JSONSetable is an interface for structs to implement, +// when they need to customize the json pointer process or want to avoid the use of reflection. type JSONSetable interface { - JSONSet(string, any) error + // JSONSet sets the value pointed at the (unescaped) key. + JSONSet(key string, value any) error } -// New creates a new json pointer for the given string -func New(jsonPointerString string) (Pointer, error) { +// Pointer is a representation of a json pointer. +// +// Use [Pointer.Get] to retrieve a value or [Pointer.Set] to set a value. +// +// It works with any go type interpreted as a JSON document, which means: +// +// - if a type implements [JSONPointable], its [JSONPointable.JSONLookup] method is used to resolve [Pointer.Get] +// - if a type implements [JSONSetable], its [JSONPointable.JSONSet] method is used to resolve [Pointer.Set] +// - a go map[K]V is interpreted as an object, with type K assignable to a string +// - a go slice []T is interpreted as an array +// - a go struct is interpreted as an object, with exported fields interpreted as keys +// - promoted fields from an embedded struct are traversed +// - scalars (e.g. int, float64 ...), channels, functions and go arrays cannot be traversed +// +// For struct s resolved by reflection, key mappings honor the conventional struct tag `json`. +// +// Fields that do not specify a `json` tag, or specify an empty one, or are tagged as `json:"-"` are ignored. +// +// # Limitations +// +// - Unlike go standard marshaling, untagged fields do not default to the go field name and are ignored. +// - anonymous fields are not traversed if untagged +type Pointer struct { + referenceTokens []string +} +// New creates a new json pointer from its string representation. +func New(jsonPointerString string) (Pointer, error) { var p Pointer err := p.parse(jsonPointerString) + return p, err +} +// Get uses the pointer to retrieve a value from a JSON document. +// +// It returns the value with its type as a [reflect.Kind] or an error. +func (p *Pointer) Get(document any) (any, reflect.Kind, error) { + return p.get(document, jsonname.DefaultJSONNameProvider) } -// Pointer the json pointer reprsentation -type Pointer struct { - referenceTokens []string +// Set uses the pointer to set a value from a data type +// that represent a JSON document. +// +// It returns the updated document. +func (p *Pointer) Set(document any, value any) (any, error) { + return document, p.set(document, value, jsonname.DefaultJSONNameProvider) } -// "Constructor", parses the given string JSON pointer -func (p *Pointer) parse(jsonPointerString string) error { +// DecodedTokens returns the decoded (unescaped) tokens of this JSON pointer. +func (p *Pointer) DecodedTokens() []string { + result := make([]string, 0, len(p.referenceTokens)) + for _, token := range p.referenceTokens { + result = append(result, Unescape(token)) + } - var err error + return result +} - if jsonPointerString != emptyPointer { - if !strings.HasPrefix(jsonPointerString, pointerSeparator) { - err = errors.Join(ErrInvalidStart, ErrPointer) - } else { - referenceTokens := strings.Split(jsonPointerString, pointerSeparator) - p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) - } +// IsEmpty returns true if this is an empty json pointer. +// +// This indicates that it points to the root document. +func (p *Pointer) IsEmpty() bool { + return len(p.referenceTokens) == 0 +} + +// String representation of a pointer. +func (p *Pointer) String() string { + if len(p.referenceTokens) == 0 { + return emptyPointer } - return err + return pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) } -// Get uses the pointer to retrieve a value from a JSON document -func (p *Pointer) Get(document any) (any, reflect.Kind, error) { - return p.get(document, swag.DefaultJSONNameProvider) +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: %w", tk, ErrPointer) + } + default: + return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) + } + } + return offset, nil } -// Set uses the pointer to set a value from a JSON document -func (p *Pointer) Set(document any, value any) (any, error) { - return document, p.set(document, value, swag.DefaultJSONNameProvider) +// "Constructor", parses the given string JSON pointer. +func (p *Pointer) parse(jsonPointerString string) error { + if jsonPointerString == emptyPointer { + return nil + } + + if !strings.HasPrefix(jsonPointerString, pointerSeparator) { + // non empty pointer must start with "/" + return errors.Join(ErrInvalidStart, ErrPointer) + } + + referenceTokens := strings.Split(jsonPointerString, pointerSeparator) + p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) + + return nil } -// GetForToken gets a value for a json pointer token 1 level deep -func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { - return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) +func (p *Pointer) get(node any, nameProvider *jsonname.NameProvider) (any, reflect.Kind, error) { + if nameProvider == nil { + nameProvider = jsonname.DefaultJSONNameProvider + } + + kind := reflect.Invalid + + // full document when empty + if len(p.referenceTokens) == 0 { + return node, kind, nil + } + + for _, token := range p.referenceTokens { + decodedToken := Unescape(token) + + r, knd, err := getSingleImpl(node, decodedToken, nameProvider) + if err != nil { + return nil, knd, err + } + node = r + } + + rValue := reflect.ValueOf(node) + kind = rValue.Kind() + + return node, kind, nil } -// SetForToken gets a value for a json pointer token 1 level deep -func SetForToken(document any, decodedToken string, value any) (any, error) { - return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) +func (p *Pointer) set(node, data any, nameProvider *jsonname.NameProvider) error { + knd := reflect.ValueOf(node).Kind() + + if knd != reflect.Pointer && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { + return errors.Join( + fmt.Errorf("unexpected type: %T", node), //nolint:err113 // err wrapping is carried out by errors.Join, not fmt.Errorf. + ErrUnsupportedValueType, + ErrPointer, + ) + } + + l := len(p.referenceTokens) + + // full document when empty + if l == 0 { + return nil + } + + if nameProvider == nil { + nameProvider = jsonname.DefaultJSONNameProvider + } + + var decodedToken string + lastIndex := l - 1 + + if lastIndex > 0 { // skip if we only have one token in pointer + for _, token := range p.referenceTokens[:lastIndex] { + decodedToken = Unescape(token) + next, err := p.resolveNodeForToken(node, decodedToken, nameProvider) + if err != nil { + return err + } + + node = next + } + } + + // last token + decodedToken = Unescape(p.referenceTokens[lastIndex]) + + return setSingleImpl(node, data, decodedToken, nameProvider) +} + +func (p *Pointer) resolveNodeForToken(node any, decodedToken string, nameProvider *jsonname.NameProvider) (next any, err error) { + // check for nil during traversal + if isNil(node) { + return nil, fmt.Errorf("cannot traverse through nil value at %q: %w", decodedToken, ErrPointer) + } + + pointable, ok := node.(JSONPointable) + if ok { + r, err := pointable.JSONLookup(decodedToken) + if err != nil { + return nil, err + } + + fld := reflect.ValueOf(r) + if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Pointer { + return fld.Addr().Interface(), nil + } + + return r, nil + } + + rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() + + switch kind { + case reflect.Struct: + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return nil, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) + } + + return typeFromValue(rValue.FieldByName(nm)), nil + + case reflect.Map: + kv := reflect.ValueOf(decodedToken) + mv := rValue.MapIndex(kv) + + if !mv.IsValid() { + return nil, errNoKey(decodedToken) + } + + return typeFromValue(mv), nil + + case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return nil, errors.Join(err, ErrPointer) + } + + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return nil, errOutOfBounds(sLength, tokenIndex) + } + + return typeFromValue(rValue.Index(tokenIndex)), nil + + default: + return nil, errInvalidReference(decodedToken) + } } func isNil(input any) bool { @@ -113,15 +295,33 @@ func isNil(input any) bool { } kind := reflect.TypeOf(input).Kind() - switch kind { //nolint:exhaustive - case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: + switch kind { + case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Chan: return reflect.ValueOf(input).IsNil() default: return false } } -func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { +func typeFromValue(v reflect.Value) any { + if v.CanAddr() && v.Kind() != reflect.Interface && v.Kind() != reflect.Map && v.Kind() != reflect.Slice && v.Kind() != reflect.Pointer { + return v.Addr().Interface() + } + + return v.Interface() +} + +// GetForToken gets a value for a json pointer token 1 level deep. +func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { + return getSingleImpl(document, decodedToken, jsonname.DefaultJSONNameProvider) +} + +// SetForToken sets a value for a json pointer token 1 level deep. +func SetForToken(document any, decodedToken string, value any) (any, error) { + return document, setSingleImpl(document, value, decodedToken, jsonname.DefaultJSONNameProvider) +} + +func getSingleImpl(node any, decodedToken string, nameProvider *jsonname.NameProvider) (any, reflect.Kind, error) { rValue := reflect.Indirect(reflect.ValueOf(node)) kind := rValue.Kind() if isNil(node) { @@ -139,13 +339,15 @@ func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvide return getSingleImpl(*typed, decodedToken, nameProvider) } - switch kind { //nolint:exhaustive + switch kind { case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { return nil, kind, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } + fld := rValue.FieldByName(nm) + return fld.Interface(), kind, nil case reflect.Map: @@ -155,261 +357,100 @@ func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvide if mv.IsValid() { return mv.Interface(), kind, nil } - return nil, kind, fmt.Errorf("object has no key %q: %w", decodedToken, ErrPointer) + + return nil, kind, errNoKey(decodedToken) case reflect.Slice: tokenIndex, err := strconv.Atoi(decodedToken) if err != nil { - return nil, kind, err + return nil, kind, errors.Join(err, ErrPointer) } sLength := rValue.Len() if tokenIndex < 0 || tokenIndex >= sLength { - return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", sLength-1, tokenIndex, ErrPointer) + return nil, kind, errOutOfBounds(sLength, tokenIndex) } elem := rValue.Index(tokenIndex) return elem.Interface(), kind, nil default: - return nil, kind, fmt.Errorf("invalid token reference %q: %w", decodedToken, ErrPointer) + return nil, kind, errInvalidReference(decodedToken) } - } -func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameProvider) error { - rValue := reflect.Indirect(reflect.ValueOf(node)) +func setSingleImpl(node, data any, decodedToken string, nameProvider *jsonname.NameProvider) error { + // check for nil to prevent panic when calling rValue.Type() + if isNil(node) { + return fmt.Errorf("cannot set field %q on nil value: %w", decodedToken, ErrPointer) + } - if ns, ok := node.(JSONSetable); ok { // pointer impl + if ns, ok := node.(JSONSetable); ok { return ns.JSONSet(decodedToken, data) } - if rValue.Type().Implements(jsonSetableType) { - return node.(JSONSetable).JSONSet(decodedToken, data) - } + rValue := reflect.Indirect(reflect.ValueOf(node)) - switch rValue.Kind() { //nolint:exhaustive + switch rValue.Kind() { case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { return fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } + fld := rValue.FieldByName(nm) - if fld.IsValid() { - fld.Set(reflect.ValueOf(data)) + if !fld.CanSet() { + return fmt.Errorf("can't set struct field %s to %v: %w", nm, data, ErrPointer) } + + value := reflect.ValueOf(data) + valueType := value.Type() + assignedType := fld.Type() + + if !valueType.AssignableTo(assignedType) { + return fmt.Errorf("can't set value with type %T to field %s with type %v: %w", data, nm, assignedType, ErrPointer) + } + + fld.Set(value) + return nil case reflect.Map: kv := reflect.ValueOf(decodedToken) rValue.SetMapIndex(kv, reflect.ValueOf(data)) + return nil case reflect.Slice: tokenIndex, err := strconv.Atoi(decodedToken) if err != nil { - return err + return errors.Join(err, ErrPointer) } + sLength := rValue.Len() if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", sLength, tokenIndex, ErrPointer) + return errOutOfBounds(sLength, tokenIndex) } elem := rValue.Index(tokenIndex) if !elem.CanSet() { return fmt.Errorf("can't set slice index %s to %v: %w", decodedToken, data, ErrPointer) } - elem.Set(reflect.ValueOf(data)) - return nil - - default: - return fmt.Errorf("invalid token reference %q: %w", decodedToken, ErrPointer) - } - -} -func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { + value := reflect.ValueOf(data) + valueType := value.Type() + assignedType := elem.Type() - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - kind := reflect.Invalid - - // Full document when empty - if len(p.referenceTokens) == 0 { - return node, kind, nil - } - - for _, token := range p.referenceTokens { - decodedToken := Unescape(token) - - r, knd, err := getSingleImpl(node, decodedToken, nameProvider) - if err != nil { - return nil, knd, err + if !valueType.AssignableTo(assignedType) { + return fmt.Errorf("can't set value with type %T to slice element %d with type %v: %w", data, tokenIndex, assignedType, ErrPointer) } - node = r - } - - rValue := reflect.ValueOf(node) - kind = rValue.Kind() - return node, kind, nil -} + elem.Set(value) -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 { - return errors.Join( - ErrUnsupportedValueType, - ErrPointer, - ) - } - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - // Full document when empty - if len(p.referenceTokens) == 0 { return nil - } - - lastI := len(p.referenceTokens) - 1 - for i, token := range p.referenceTokens { - isLastToken := i == lastI - decodedToken := Unescape(token) - - if isLastToken { - - return setSingleImpl(node, data, decodedToken, nameProvider) - } - - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - - if rValue.Type().Implements(jsonPointableType) { - r, err := node.(JSONPointable).JSONLookup(decodedToken) - if err != nil { - return err - } - fld := reflect.ValueOf(r) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = r - continue - } - - switch kind { //nolint:exhaustive - case reflect.Struct: - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) - } - fld := rValue.FieldByName(nm) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = fld.Interface() - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if !mv.IsValid() { - return fmt.Errorf("object has no key %q: %w", decodedToken, ErrPointer) - } - if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr { - node = mv.Addr().Interface() - continue - } - node = mv.Interface() - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d': %w", sLength, tokenIndex, ErrPointer) - } - - elem := rValue.Index(tokenIndex) - if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr { - node = elem.Addr().Interface() - continue - } - node = elem.Interface() - - default: - return fmt.Errorf("invalid token reference %q: %w", decodedToken, ErrPointer) - } - - } - - return nil -} - -// DecodedTokens returns the decoded tokens -func (p *Pointer) DecodedTokens() []string { - result := make([]string, 0, len(p.referenceTokens)) - for _, t := range p.referenceTokens { - result = append(result, Unescape(t)) - } - return result -} - -// IsEmpty returns true if this is an empty json pointer -// this indicates that it points to the root document -func (p *Pointer) IsEmpty() bool { - return len(p.referenceTokens) == 0 -} - -// Pointer to string representation function -func (p *Pointer) String() string { - - if len(p.referenceTokens) == 0 { - return emptyPointer - } - pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) - - 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: %w", tk, ErrPointer) - } - default: - return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) - } + default: + return errInvalidReference(decodedToken) } - return offset, nil } func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { @@ -439,13 +480,14 @@ func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { return 0, fmt.Errorf("invalid token %#v: %w", tk, ErrPointer) } } + return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer) } 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: %w", decodedToken, err, ErrPointer) + return 0, fmt.Errorf("token reference %q is not a number: %w: %w", decodedToken, err, ErrPointer) } var i int for i = 0; i < idx && dec.More(); i++ { @@ -471,10 +513,12 @@ func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { if !dec.More() { return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer) } + return dec.InputOffset(), nil } // drainSingle drains a single level of object or array. +// // The decoder has to guarantee the beginning delim (i.e. '{' or '[') has been consumed. func drainSingle(dec *json.Decoder) error { for dec.More() { @@ -496,14 +540,15 @@ func drainSingle(dec *json.Decoder) error { } } - // Consumes the ending delim + // consumes the ending delim if _, err := dec.Token(); err != nil { return err } + return nil } -// Specific JSON pointer encoding here +// JSON pointer encoding: // ~0 => ~ // ~1 => / // ... and vice versa @@ -515,16 +560,24 @@ const ( decRefTok1 = `/` ) -// Unescape unescapes a json pointer reference token string to the original representation +var ( + encRefTokReplacer = strings.NewReplacer(encRefTok1, decRefTok1, encRefTok0, decRefTok0) //nolint:gochecknoglobals // it's okay to declare a replacer as a private global + decRefTokReplacer = strings.NewReplacer(decRefTok1, encRefTok1, decRefTok0, encRefTok0) //nolint:gochecknoglobals // it's okay to declare a replacer as a private global +) + +// Unescape unescapes a json pointer reference token string to the original representation. func Unescape(token string) string { - step1 := strings.ReplaceAll(token, encRefTok1, decRefTok1) - step2 := strings.ReplaceAll(step1, encRefTok0, decRefTok0) - return step2 + return encRefTokReplacer.Replace(token) } -// Escape escapes a pointer reference token string +// Escape escapes a pointer reference token string. +// +// The JSONPointer specification defines "/" as a separator and "~" as an escape prefix. +// +// Keys containing such characters are escaped with the following rules: +// +// - "~" is escaped as "~0" +// - "/" is escaped as "~1" func Escape(token string) string { - step1 := strings.ReplaceAll(token, decRefTok0, encRefTok0) - step2 := strings.ReplaceAll(step1, decRefTok1, encRefTok1) - return step2 + return decRefTokReplacer.Replace(token) } diff --git a/vendor/github.com/go-openapi/jsonreference/.cliff.toml b/vendor/github.com/go-openapi/jsonreference/.cliff.toml new file mode 100644 index 000000000000..702629f5dc30 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/.cliff.toml @@ -0,0 +1,181 @@ +# git-cliff ~ configuration file +# https://git-cliff.org/docs/configuration + +[changelog] +header = """ +""" + +footer = """ + +----- + +**[{{ remote.github.repo }}]({{ self::remote_url() }}) license terms** + +[![License][license-badge]][license-url] + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: {{ self::remote_url() }}/?tab=Apache-2.0-1-ov-file#readme + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" + +body = """ +{%- if version %} +## [{{ version | trim_start_matches(pat="v") }}]({{ self::remote_url() }}/tree/{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }} +{%- else %} +## [unreleased] +{%- endif %} +{%- if message %} + {%- raw %}\n{% endraw %} +{{ message }} + {%- raw %}\n{% endraw %} +{%- endif %} +{%- if version %} + {%- if previous.version %} + +**Full Changelog**: <{{ self::remote_url() }}/compare/{{ previous.version }}...{{ version }}> + {%- endif %} +{%- else %} + {%- raw %}\n{% endraw %} +{%- endif %} + +{%- if statistics %}{% if statistics.commit_count %} + {%- raw %}\n{% endraw %} +{{ statistics.commit_count }} commits in this release. + {%- raw %}\n{% endraw %} +{%- endif %}{% endif %} +----- + +{%- for group, commits in commits | group_by(attribute="group") %} + {%- raw %}\n{% endraw %} +### {{ group | upper_first }} + {%- raw %}\n{% endraw %} + {%- for commit in commits %} + {%- if commit.remote.pr_title %} + {%- set commit_message = commit.remote.pr_title %} + {%- else %} + {%- set commit_message = commit.message %} + {%- endif %} +* {{ commit_message | split(pat="\n") | first | trim }} + {%- if commit.remote.username %} +{%- raw %} {% endraw %}by [@{{ commit.remote.username }}](https://github.com/{{ commit.remote.username }}) + {%- endif %} + {%- if commit.remote.pr_number %} +{%- raw %} {% endraw %}in [#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) + {%- endif %} +{%- raw %} {% endraw %}[...]({{ self::remote_url() }}/commit/{{ commit.id }}) + {%- endfor %} +{%- endfor %} + +{%- if github %} +{%- raw %}\n{% endraw -%} + {%- set all_contributors = github.contributors | length %} + {%- if github.contributors | filter(attribute="username", value="dependabot[bot]") | length < all_contributors %} +----- + +### People who contributed to this release + {% endif %} + {%- for contributor in github.contributors | filter(attribute="username") | sort(attribute="username") %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* [@{{ contributor.username }}](https://github.com/{{ contributor.username }}) + {%- endif %} + {%- endfor %} + + {% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} +----- + {%- raw %}\n{% endraw %} + +### New Contributors + {%- endif %} + + {%- for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} + {%- if contributor.username != "dependabot[bot]" and contributor.username != "github-actions[bot]" %} +* @{{ contributor.username }} made their first contribution + {%- if contributor.pr_number %} + in [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ + {%- endif %} + {%- endif %} + {%- endfor %} +{%- endif %} + +{%- raw %}\n{% endraw %} + +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} +""" +# Remove leading and trailing whitespaces from the changelog's body. +trim = true +# Render body even when there are no releases to process. +render_always = true +# An array of regex based postprocessors to modify the changelog. +postprocessors = [ + # Replace the placeholder with a URL. + #{ pattern = '', replace = "https://github.com/orhun/git-cliff" }, +] +# output file path +# output = "test.md" + +[git] +# Parse commits according to the conventional commits specification. +# See https://www.conventionalcommits.org +conventional_commits = false +# Exclude commits that do not match the conventional commits specification. +filter_unconventional = false +# Require all commits to be conventional. +# Takes precedence over filter_unconventional. +require_conventional = false +# Split commits on newlines, treating each line as an individual commit. +split_commits = false +# An array of regex based parsers to modify commit messages prior to further processing. +commit_preprocessors = [ + # Replace issue numbers with link templates to be updated in `changelog.postprocessors`. + #{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, + # Check spelling of the commit message using https://github.com/crate-ci/typos. + # If the spelling is incorrect, it will be fixed automatically. + #{ pattern = '.*', replace_command = 'typos --write-changes -' } +] +# Prevent commits that are breaking from being excluded by commit parsers. +protect_breaking_commits = false +# An array of regex based parsers for extracting data from the commit message. +# Assigns commits to groups. +# Optionally sets the commit's scope and can decide to exclude commits from further processing. +commit_parsers = [ + { message = "^[Cc]hore\\([Rr]elease\\): prepare for", skip = true }, + { message = "(^[Mm]erge)|([Mm]erge conflict)", skip = true }, + { field = "author.name", pattern = "dependabot*", group = "Updates" }, + { message = "([Ss]ecurity)|([Vv]uln)", group = "Security" }, + { body = "(.*[Ss]ecurity)|([Vv]uln)", group = "Security" }, + { message = "([Cc]hore\\(lint\\))|(style)|(lint)|(codeql)|(golangci)", group = "Code quality" }, + { message = "(^[Dd]oc)|((?i)readme)|(badge)|(typo)|(documentation)", group = "Documentation" }, + { message = "(^[Ff]eat)|(^[Ee]nhancement)", group = "Implemented enhancements" }, + { message = "(^ci)|(\\(ci\\))|(fixup\\s+ci)|(fix\\s+ci)|(license)|(example)", group = "Miscellaneous tasks" }, + { message = "^test", group = "Testing" }, + { message = "(^fix)|(panic)", group = "Fixed bugs" }, + { message = "(^refact)|(rework)", group = "Refactor" }, + { message = "(^[Pp]erf)|(performance)", group = "Performance" }, + { message = "(^[Cc]hore)", group = "Miscellaneous tasks" }, + { message = "^[Rr]evert", group = "Reverted changes" }, + { message = "(upgrade.*?go)|(go\\s+version)", group = "Updates" }, + { message = ".*", group = "Other" }, +] +# Exclude commits that are not matched by any commit parser. +filter_commits = false +# An array of link parsers for extracting external references, and turning them into URLs, using regex. +link_parsers = [] +# Include only the tags that belong to the current branch. +use_branch_tags = false +# Order releases topologically instead of chronologically. +topo_order = false +# Order releases topologically instead of chronologically. +topo_order_commits = true +# Order of commits in each group/release within the changelog. +# Allowed values: newest, oldest +sort_commits = "newest" +# Process submodules commits +recurse_submodules = false + +#[remote.github] +#owner = "go-openapi" diff --git a/vendor/github.com/go-openapi/jsonreference/.editorconfig b/vendor/github.com/go-openapi/jsonreference/.editorconfig new file mode 100644 index 000000000000..3152da69a5d7 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/.editorconfig @@ -0,0 +1,26 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +# Set default charset +[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] +charset = utf-8 + +# Tab indentation (no size specified) +[*.go] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false + +# Matches the exact files either package.json or .travis.yml +[{package.json,.travis.yml}] +indent_style = space +indent_size = 2 diff --git a/vendor/github.com/go-openapi/jsonreference/.golangci.yml b/vendor/github.com/go-openapi/jsonreference/.golangci.yml index 22f8d21cca19..fdae591bce71 100644 --- a/vendor/github.com/go-openapi/jsonreference/.golangci.yml +++ b/vendor/github.com/go-openapi/jsonreference/.golangci.yml @@ -1,61 +1,66 @@ -linters-settings: - govet: - check-shadowing: true - golint: - min-confidence: 0 - gocyclo: - min-complexity: 45 - maligned: - suggest-new: true - dupl: - threshold: 200 - goconst: - min-len: 2 - min-occurrences: 3 - +version: "2" linters: - enable-all: true + default: all disable: - - maligned - - unparam - - lll - - gochecknoinits - - gochecknoglobals + - depguard - funlen - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage + - exhaustruct - nlreturn - - gomnd - - exhaustivestruct - - goerr113 - - errorlint - - nestif - - godot - - gofumpt + - nonamedreturns + - noinlineerr - paralleltest + - recvcheck + - testpackage - tparallel - - thelper - - ifshort - - exhaustruct - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - - deadcode - - interfacer - - scopelint - - varcheck - - structcheck - - golint - - nosnakecase + - whitespace + - wrapcheck + - wsl + - wsl_v5 + settings: + dupl: + threshold: 200 + goconst: + min-len: 2 + min-occurrences: 3 + cyclop: + max-complexity: 20 + gocyclo: + min-complexity: 20 + exhaustive: + default-signifies-exhaustive: true + default-case-required: true + lll: + line-length: 180 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + - gofumpt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ +issues: + # Maximum issues count per one linter. + # Set to 0 to disable. + # Default: 50 + max-issues-per-linter: 0 + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 0 diff --git a/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md b/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md new file mode 100644 index 000000000000..9907d5d21243 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md @@ -0,0 +1,21 @@ +# Contributors + +- Repository: ['go-openapi/jsonreference'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 9 | 68 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 31 | https://github.com/go-openapi/jsonreference/commits?author=fredbi | +| @casualjim | 25 | https://github.com/go-openapi/jsonreference/commits?author=casualjim | +| @youyuanwu | 5 | https://github.com/go-openapi/jsonreference/commits?author=youyuanwu | +| @olivierlemasle | 2 | https://github.com/go-openapi/jsonreference/commits?author=olivierlemasle | +| @apelisse | 1 | https://github.com/go-openapi/jsonreference/commits?author=apelisse | +| @gbjk | 1 | https://github.com/go-openapi/jsonreference/commits?author=gbjk | +| @honza | 1 | https://github.com/go-openapi/jsonreference/commits?author=honza | +| @Neo2308 | 1 | https://github.com/go-openapi/jsonreference/commits?author=Neo2308 | +| @erraggy | 1 | https://github.com/go-openapi/jsonreference/commits?author=erraggy | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github/contributors)_ diff --git a/vendor/github.com/go-openapi/jsonreference/NOTICE b/vendor/github.com/go-openapi/jsonreference/NOTICE new file mode 100644 index 000000000000..f3b51939a95b --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/NOTICE @@ -0,0 +1,39 @@ +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonpointer, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0. + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original software was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). + +github.com/sigh-399/jsonpointer +=========================== + +// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// SPDX-License-Identifier: Apache-2.0 + +Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/go-openapi/jsonreference/README.md b/vendor/github.com/go-openapi/jsonreference/README.md index c7fc2049c1d8..d479dbdc7318 100644 --- a/vendor/github.com/go-openapi/jsonreference/README.md +++ b/vendor/github.com/go-openapi/jsonreference/README.md @@ -1,19 +1,99 @@ -# gojsonreference [![Build Status](https://github.com/go-openapi/jsonreference/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/jsonreference/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonreference) +# jsonreference -[![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/jsonreference/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/jsonreference.svg)](https://pkg.go.dev/github.com/go-openapi/jsonreference) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/jsonreference)](https://goreportcard.com/report/github.com/go-openapi/jsonreference) + +[![Tests][test-badge]][test-url] [![Coverage][cov-badge]][cov-url] [![CI vuln scan][vuln-scan-badge]][vuln-scan-url] [![CodeQL][codeql-badge]][codeql-url] + + + +[![Release][release-badge]][release-url] [![Go Report Card][gocard-badge]][gocard-url] [![CodeFactor Grade][codefactor-badge]][codefactor-url] [![License][license-badge]][license-url] + + +[![GoDoc][godoc-badge]][godoc-url] [![Slack Channel][slack-logo]![slack-badge]][slack-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -An implementation of JSON Reference - Go language +--- + +An implementation of JSON Reference for golang. ## Status -Feature complete. Stable API + +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/jsonreference +``` ## Dependencies + * https://github.com/go-openapi/jsonpointer +## Basic usage + +## Change log + +See + ## References * http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 * http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +See the license [NOTICE](./NOTICE), which recalls the licensing terms of all the pieces of software +on top of which it has been built. + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines](.github/CONTRIBUTING.md) +* [Maintainers documentation](docs/MAINTAINERS.md) +* [Code style](docs/STYLE.md) + +## Cutting a new release + +Maintainers can cut a new release by either: + +* running [this workflow](https://github.com/go-openapi/jsonreference/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes + + +[test-badge]: https://github.com/go-openapi/jsonreference/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/jsonreference/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/jsonreference +[vuln-scan-badge]: https://github.com/go-openapi/jsonreference/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/jsonreference/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/jsonreference/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/jsonreference/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fjsonreference.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fjsonreference +[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonreference.svg +[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fjsonreference + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/jsonreference +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/jsonreference +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/jsonreference +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/jsonreference + +[doc-badge]: https://img.shields.io/badge/doc-site-blue?link=https%3A%2F%2Fgoswagger.io%2Fgo-openapi%2F +[doc-url]: https://goswagger.io/go-openapi +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/jsonreference +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/jsonreference +[slack-logo]: https://a.slack-edge.com/e6a93c1/img/icons/favicon-32.png +[slack-badge]: https://img.shields.io/badge/slack-blue?link=https%3A%2F%2Fgoswagger.slack.com%2Farchives%2FC04R30YM +[slack-url]: https://goswagger.slack.com/archives/C04R30YMU + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/jsonreference/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/jsonreference +[goversion-url]: https://github.com/go-openapi/jsonreference/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/jsonreference +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/jsonreference/latest diff --git a/vendor/github.com/go-openapi/jsonreference/SECURITY.md b/vendor/github.com/go-openapi/jsonreference/SECURITY.md new file mode 100644 index 000000000000..2a7b6f0910d9 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.22.x | :white_check_mark: | + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +please report it privately to the maintainers. + +Please follow the instructions provided by github to +[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). + +TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". diff --git a/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go b/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go index f0610cf1e577..a08b47320e7d 100644 --- a/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go +++ b/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package internal import ( @@ -11,9 +14,11 @@ const ( defaultHTTPSPort = ":443" ) -// Regular expressions used by the normalizations -var rxPort = regexp.MustCompile(`(:\d+)/?$`) -var rxDupSlashes = regexp.MustCompile(`/{2,}`) +// Regular expressions used by the normalizations. +var ( + rxPort = regexp.MustCompile(`(:\d+)/?$`) + rxDupSlashes = regexp.MustCompile(`/{2,}`) +) // NormalizeURL will normalize the specified URL // This was added to replace a previous call to the no longer maintained purell library: diff --git a/vendor/github.com/go-openapi/jsonreference/reference.go b/vendor/github.com/go-openapi/jsonreference/reference.go index cfdef03e5d94..6e3ae4995154 100644 --- a/vendor/github.com/go-openapi/jsonreference/reference.go +++ b/vendor/github.com/go-openapi/jsonreference/reference.go @@ -1,27 +1,5 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonreference -// repository-desc An implementation of JSON Reference - Go language -// -// description Main and unique file. -// -// created 26-02-2013 +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package jsonreference @@ -38,50 +16,50 @@ const ( fragmentRune = `#` ) -// New creates a new reference for the given string -func New(jsonReferenceString string) (Ref, error) { +var ErrChildURL = errors.New("child url is nil") + +// Ref represents a json reference object. +type Ref struct { + referenceURL *url.URL + referencePointer jsonpointer.Pointer + + HasFullURL bool + HasURLPathOnly bool + HasFragmentOnly bool + HasFileScheme bool + HasFullFilePath bool +} +// New creates a new reference for the given string. +func New(jsonReferenceString string) (Ref, error) { var r Ref err := r.parse(jsonReferenceString) return r, err - } // MustCreateRef parses the ref string and panics when it's invalid. -// Use the New method for a version that returns an error +// Use the New method for a version that returns an error. func MustCreateRef(ref string) Ref { r, err := New(ref) if err != nil { panic(err) } - return r -} -// Ref represents a json reference object -type Ref struct { - referenceURL *url.URL - referencePointer jsonpointer.Pointer - - HasFullURL bool - HasURLPathOnly bool - HasFragmentOnly bool - HasFileScheme bool - HasFullFilePath bool + return r } -// GetURL gets the URL for this reference +// GetURL gets the URL for this reference. func (r *Ref) GetURL() *url.URL { return r.referenceURL } -// GetPointer gets the json pointer for this reference +// GetPointer gets the json pointer for this reference. func (r *Ref) GetPointer() *jsonpointer.Pointer { return &r.referencePointer } -// String returns the best version of the url for this reference +// String returns the best version of the url for this reference. func (r *Ref) String() string { - if r.referenceURL != nil { return r.referenceURL.String() } @@ -93,7 +71,7 @@ func (r *Ref) String() string { return r.referencePointer.String() } -// IsRoot returns true if this reference is a root document +// IsRoot returns true if this reference is a root document. func (r *Ref) IsRoot() bool { return r.referenceURL != nil && !r.IsCanonical() && @@ -101,14 +79,32 @@ func (r *Ref) IsRoot() bool { r.referenceURL.Fragment == "" } -// IsCanonical returns true when this pointer starts with http(s):// or file:// +// IsCanonical returns true when this pointer starts with http(s):// or file://. func (r *Ref) IsCanonical() bool { return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL) } -// "Constructor", parses the given string JSON reference -func (r *Ref) parse(jsonReferenceString string) error { +// Inherits creates a new reference from a parent and a child +// If the child cannot inherit from the parent, an error is returned. +func (r *Ref) Inherits(child Ref) (*Ref, error) { + childURL := child.GetURL() + parentURL := r.GetURL() + if childURL == nil { + return nil, ErrChildURL + } + if parentURL == nil { + return &child, nil + } + + ref, err := New(parentURL.ResolveReference(childURL).String()) + if err != nil { + return nil, err + } + return &ref, nil +} +// "Constructor", parses the given string JSON reference. +func (r *Ref) parse(jsonReferenceString string) error { parsed, err := url.Parse(jsonReferenceString) if err != nil { return err @@ -137,22 +133,3 @@ func (r *Ref) parse(jsonReferenceString string) error { return nil } - -// Inherits creates a new reference from a parent and a child -// If the child cannot inherit from the parent, an error is returned -func (r *Ref) Inherits(child Ref) (*Ref, error) { - childURL := child.GetURL() - parentURL := r.GetURL() - if childURL == nil { - return nil, errors.New("child url is nil") - } - if parentURL == nil { - return &child, nil - } - - ref, err := New(parentURL.ResolveReference(childURL).String()) - if err != nil { - return nil, err - } - return &ref, nil -} diff --git a/vendor/github.com/go-openapi/loads/README.md b/vendor/github.com/go-openapi/loads/README.md index 6b8307c84d13..f8bd440dfc27 100644 --- a/vendor/github.com/go-openapi/loads/README.md +++ b/vendor/github.com/go-openapi/loads/README.md @@ -1,4 +1,4 @@ -# Loads OAI specs [![Build Status](https://github.com/go-openapi/loads/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/loads/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/loads/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/lods) +# Loads OAI specs [![Build Status](https://github.com/go-openapi/loads/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/loads/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/loads/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/loads) [![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/loads/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/loads?status.svg)](http://godoc.org/github.com/go-openapi/loads) [![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/loads)](https://goreportcard.com/report/github.com/go-openapi/loads) diff --git a/vendor/github.com/go-openapi/loads/TODO.md b/vendor/github.com/go-openapi/loads/TODO.md deleted file mode 100644 index 103937acdf3e..000000000000 --- a/vendor/github.com/go-openapi/loads/TODO.md +++ /dev/null @@ -1,3 +0,0 @@ -[x] why not filepath in JSONDoc() -[] integration tests package -[] relint diff --git a/vendor/github.com/go-openapi/loads/loaders.go b/vendor/github.com/go-openapi/loads/loaders.go index 705275cb6e68..b2d1e034c523 100644 --- a/vendor/github.com/go-openapi/loads/loaders.go +++ b/vendor/github.com/go-openapi/loads/loaders.go @@ -21,7 +21,7 @@ var ( func init() { jsonLoader := &loader{ DocLoaderWithMatch: DocLoaderWithMatch{ - Match: func(pth string) bool { + Match: func(_ string) bool { return true }, Fn: JSONDoc, diff --git a/vendor/github.com/go-openapi/loads/spec.go b/vendor/github.com/go-openapi/loads/spec.go index 30ce449961b9..c9039cd5d7ed 100644 --- a/vendor/github.com/go-openapi/loads/spec.go +++ b/vendor/github.com/go-openapi/loads/spec.go @@ -248,7 +248,8 @@ func (d *Document) ResetDefinitions() *Document { // Pristine creates a new pristine document instance based on the input data func (d *Document) Pristine() *Document { - dd, _ := Analyzed(d.Raw(), d.Version()) + raw, _ := json.Marshal(d.Spec()) + dd, _ := Analyzed(raw, d.Version()) dd.pathLoader = d.pathLoader dd.specFilePath = d.specFilePath diff --git a/vendor/github.com/go-openapi/runtime/bytestream.go b/vendor/github.com/go-openapi/runtime/bytestream.go index 0a6b8ec6e7ab..f8fb482232b4 100644 --- a/vendor/github.com/go-openapi/runtime/bytestream.go +++ b/vendor/github.com/go-openapi/runtime/bytestream.go @@ -38,9 +38,16 @@ type byteStreamOpts struct { Close bool } -// ByteStreamConsumer creates a consumer for byte streams, -// takes a Writer/BinaryUnmarshaler interface or binary slice by reference, -// and reads from the provided reader +// ByteStreamConsumer creates a consumer for byte streams. +// +// The consumer consumes from a provided reader into the data passed by reference. +// +// Supported output underlying types and interfaces, prioritized in this order: +// - io.ReaderFrom (for maximum control) +// - io.Writer (performs io.Copy) +// - encoding.BinaryUnmarshaler +// - *string +// - *[]byte func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { var vals byteStreamOpts for _, opt := range opts { @@ -51,10 +58,13 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { if reader == nil { return errors.New("ByteStreamConsumer requires a reader") // early exit } + if data == nil { + return errors.New("nil destination for ByteStreamConsumer") + } closer := defaultCloser if vals.Close { - if cl, ok := reader.(io.Closer); ok { + if cl, isReaderCloser := reader.(io.Closer); isReaderCloser { closer = cl.Close } } @@ -62,34 +72,56 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { _ = closer() }() - if wrtr, ok := data.(io.Writer); ok { - _, err := io.Copy(wrtr, reader) + if readerFrom, isReaderFrom := data.(io.ReaderFrom); isReaderFrom { + _, err := readerFrom.ReadFrom(reader) return err } - buf := new(bytes.Buffer) + if writer, isDataWriter := data.(io.Writer); isDataWriter { + _, err := io.Copy(writer, reader) + return err + } + + // buffers input before writing to data + var buf bytes.Buffer _, err := buf.ReadFrom(reader) if err != nil { return err } b := buf.Bytes() - if bu, ok := data.(encoding.BinaryUnmarshaler); ok { - return bu.UnmarshalBinary(b) - } + switch destinationPointer := data.(type) { + case encoding.BinaryUnmarshaler: + return destinationPointer.UnmarshalBinary(b) + case *any: + switch (*destinationPointer).(type) { + case string: + *destinationPointer = string(b) + + return nil + + case []byte: + *destinationPointer = b - if data != nil { - if str, ok := data.(*string); ok { - *str = string(b) return nil } - } + default: + // check for the underlying type to be pointer to []byte or string, + if ptr := reflect.TypeOf(data); ptr.Kind() != reflect.Ptr { + return errors.New("destination must be a pointer") + } - if t := reflect.TypeOf(data); data != nil && t.Kind() == reflect.Ptr { v := reflect.Indirect(reflect.ValueOf(data)) - if t = v.Type(); t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 { + t := v.Type() + + switch { + case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8: v.SetBytes(b) return nil + + case t.Kind() == reflect.String: + v.SetString(string(b)) + return nil } } @@ -98,21 +130,35 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { }) } -// ByteStreamProducer creates a producer for byte streams, -// takes a Reader/BinaryMarshaler interface or binary slice, -// and writes to a writer (essentially a pipe) +// ByteStreamProducer creates a producer for byte streams. +// +// The producer takes input data then writes to an output writer (essentially as a pipe). +// +// Supported input underlying types and interfaces, prioritized in this order: +// - io.WriterTo (for maximum control) +// - io.Reader (performs io.Copy). A ReadCloser is closed before exiting. +// - encoding.BinaryMarshaler +// - error (writes as a string) +// - []byte +// - string +// - struct, other slices: writes as JSON func ByteStreamProducer(opts ...byteStreamOpt) Producer { var vals byteStreamOpts for _, opt := range opts { opt(&vals) } + return ProducerFunc(func(writer io.Writer, data interface{}) error { if writer == nil { return errors.New("ByteStreamProducer requires a writer") // early exit } + if data == nil { + return errors.New("nil data for ByteStreamProducer") + } + closer := defaultCloser if vals.Close { - if cl, ok := writer.(io.Closer); ok { + if cl, isWriterCloser := writer.(io.Closer); isWriterCloser { closer = cl.Close } } @@ -120,46 +166,51 @@ func ByteStreamProducer(opts ...byteStreamOpt) Producer { _ = closer() }() - if rc, ok := data.(io.ReadCloser); ok { + if rc, isDataCloser := data.(io.ReadCloser); isDataCloser { defer rc.Close() } - if rdr, ok := data.(io.Reader); ok { - _, err := io.Copy(writer, rdr) + switch origin := data.(type) { + case io.WriterTo: + _, err := origin.WriteTo(writer) + return err + + case io.Reader: + _, err := io.Copy(writer, origin) return err - } - if bm, ok := data.(encoding.BinaryMarshaler); ok { - bytes, err := bm.MarshalBinary() + case encoding.BinaryMarshaler: + bytes, err := origin.MarshalBinary() if err != nil { return err } _, err = writer.Write(bytes) return err - } - - if data != nil { - if str, ok := data.(string); ok { - _, err := writer.Write([]byte(str)) - return err - } - if e, ok := data.(error); ok { - _, err := writer.Write([]byte(e.Error())) - return err - } + case error: + _, err := writer.Write([]byte(origin.Error())) + return err + default: v := reflect.Indirect(reflect.ValueOf(data)) - if t := v.Type(); t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 { + t := v.Type() + + switch { + case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8: _, err := writer.Write(v.Bytes()) return err - } - if t := v.Type(); t.Kind() == reflect.Struct || t.Kind() == reflect.Slice { + + case t.Kind() == reflect.String: + _, err := writer.Write([]byte(v.String())) + return err + + case t.Kind() == reflect.Struct || t.Kind() == reflect.Slice: b, err := swag.WriteJSON(data) if err != nil { return err } + _, err = writer.Write(b) return err } diff --git a/vendor/github.com/go-openapi/runtime/client/request.go b/vendor/github.com/go-openapi/runtime/client/request.go index c238953f3849..c4a891d0bc59 100644 --- a/vendor/github.com/go-openapi/runtime/client/request.go +++ b/vendor/github.com/go-openapi/runtime/client/request.go @@ -36,7 +36,7 @@ import ( ) // NewRequest creates a new swagger http client request -func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) (*request, error) { +func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) *request { return &request{ pathPattern: pathPattern, method: method, @@ -45,7 +45,7 @@ func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) query: make(url.Values), timeout: DefaultTimeout, getBody: getRequestBuffer, - }, nil + } } // Request represents a swagger client request. diff --git a/vendor/github.com/go-openapi/runtime/client/runtime.go b/vendor/github.com/go-openapi/runtime/client/runtime.go index 8d293a593290..5bd4d75d9062 100644 --- a/vendor/github.com/go-openapi/runtime/client/runtime.go +++ b/vendor/github.com/go-openapi/runtime/client/runtime.go @@ -22,6 +22,7 @@ import ( "crypto/tls" "crypto/x509" "encoding/pem" + "errors" "fmt" "mime" "net/http" @@ -31,12 +32,13 @@ import ( "sync" "time" + "github.com/go-openapi/strfmt" + "github.com/opentracing/opentracing-go" + "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/logger" "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/runtime/yamlpc" - "github.com/go-openapi/strfmt" - "github.com/opentracing/opentracing-go" ) const ( @@ -142,7 +144,7 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { return nil, fmt.Errorf("tls client priv key: %v", err) } default: - return nil, fmt.Errorf("tls client priv key: unsupported key type") + return nil, errors.New("tls client priv key: unsupported key type") } block = pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes} @@ -378,14 +380,11 @@ func (r *Runtime) EnableConnectionReuse() { func (r *Runtime) createHttpRequest(operation *runtime.ClientOperation) (*request, *http.Request, error) { //nolint:revive,stylecheck params, _, auth := operation.Params, operation.Reader, operation.AuthInfo - request, err := newRequest(operation.Method, operation.PathPattern, params) - if err != nil { - return nil, nil, err - } + request := newRequest(operation.Method, operation.PathPattern, params) var accept []string accept = append(accept, operation.ProducesMediaTypes...) - if err = request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil { + if err := request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil { return nil, nil, err } @@ -457,27 +456,36 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error r.logger.Debugf("%s\n", string(b)) } - var hasTimeout bool - pctx := operation.Context - if pctx == nil { - pctx = r.Context - } else { - hasTimeout = true - } - if pctx == nil { - pctx = context.Background() + var parentCtx context.Context + switch { + case operation.Context != nil: + parentCtx = operation.Context + case r.Context != nil: + parentCtx = r.Context + default: + parentCtx = context.Background() } - var ctx context.Context - var cancel context.CancelFunc - if hasTimeout { - ctx, cancel = context.WithCancel(pctx) + + var ( + ctx context.Context + cancel context.CancelFunc + ) + if request.timeout == 0 { + // There may be a deadline in the context passed to the operation. + // Otherwise, there is no timeout set. + ctx, cancel = context.WithCancel(parentCtx) } else { - ctx, cancel = context.WithTimeout(pctx, request.timeout) + // Sets the timeout passed from request params (by default runtime.DefaultTimeout). + // If there is already a deadline in the parent context, the shortest will + // apply. + ctx, cancel = context.WithTimeout(parentCtx, request.timeout) } defer cancel() - client := operation.Client - if client == nil { + var client *http.Client + if operation.Client != nil { + client = operation.Client + } else { client = r.client } req = req.WithContext(ctx) diff --git a/vendor/github.com/go-openapi/runtime/csv.go b/vendor/github.com/go-openapi/runtime/csv.go index d807bd915b44..c9597bcd6e0e 100644 --- a/vendor/github.com/go-openapi/runtime/csv.go +++ b/vendor/github.com/go-openapi/runtime/csv.go @@ -16,62 +16,335 @@ package runtime import ( "bytes" + "context" + "encoding" "encoding/csv" "errors" + "fmt" "io" + "reflect" + + "golang.org/x/sync/errgroup" ) -// CSVConsumer creates a new CSV consumer -func CSVConsumer() Consumer { +// CSVConsumer creates a new CSV consumer. +// +// The consumer consumes CSV records from a provided reader into the data passed by reference. +// +// CSVOpts options may be specified to alter the default CSV behavior on the reader and the writer side (e.g. separator, skip header, ...). +// The defaults are those of the standard library's csv.Reader and csv.Writer. +// +// Supported output underlying types and interfaces, prioritized in this order: +// - *csv.Writer +// - CSVWriter (writer options are ignored) +// - io.Writer (as raw bytes) +// - io.ReaderFrom (as raw bytes) +// - encoding.BinaryUnmarshaler (as raw bytes) +// - *[][]string (as a collection of records) +// - *[]byte (as raw bytes) +// - *string (a raw bytes) +// +// The consumer prioritizes situations where buffering the input is not required. +func CSVConsumer(opts ...CSVOpt) Consumer { + o := csvOptsWithDefaults(opts) + return ConsumerFunc(func(reader io.Reader, data interface{}) error { if reader == nil { return errors.New("CSVConsumer requires a reader") } + if data == nil { + return errors.New("nil destination for CSVConsumer") + } csvReader := csv.NewReader(reader) - writer, ok := data.(io.Writer) - if !ok { - return errors.New("data type must be io.Writer") + o.applyToReader(csvReader) + closer := defaultCloser + if o.closeStream { + if cl, isReaderCloser := reader.(io.Closer); isReaderCloser { + closer = cl.Close + } } - csvWriter := csv.NewWriter(writer) - records, err := csvReader.ReadAll() - if err != nil { + defer func() { + _ = closer() + }() + + switch destination := data.(type) { + case *csv.Writer: + csvWriter := destination + o.applyToWriter(csvWriter) + + return pipeCSV(csvWriter, csvReader, o) + + case CSVWriter: + csvWriter := destination + // no writer options available + + return pipeCSV(csvWriter, csvReader, o) + + case io.Writer: + csvWriter := csv.NewWriter(destination) + o.applyToWriter(csvWriter) + + return pipeCSV(csvWriter, csvReader, o) + + case io.ReaderFrom: + var buf bytes.Buffer + csvWriter := csv.NewWriter(&buf) + o.applyToWriter(csvWriter) + if err := bufferedCSV(csvWriter, csvReader, o); err != nil { + return err + } + _, err := destination.ReadFrom(&buf) + return err - } - for _, r := range records { - if err := csvWriter.Write(r); err != nil { + + case encoding.BinaryUnmarshaler: + var buf bytes.Buffer + csvWriter := csv.NewWriter(&buf) + o.applyToWriter(csvWriter) + if err := bufferedCSV(csvWriter, csvReader, o); err != nil { return err } + + return destination.UnmarshalBinary(buf.Bytes()) + + default: + // support *[][]string, *[]byte, *string + if ptr := reflect.TypeOf(data); ptr.Kind() != reflect.Ptr { + return errors.New("destination must be a pointer") + } + + v := reflect.Indirect(reflect.ValueOf(data)) + t := v.Type() + + switch { + case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Slice && t.Elem().Elem().Kind() == reflect.String: + csvWriter := &csvRecordsWriter{} + // writer options are ignored + if err := pipeCSV(csvWriter, csvReader, o); err != nil { + return err + } + + v.Grow(len(csvWriter.records)) + v.SetCap(len(csvWriter.records)) // in case Grow was unnessary, trim down the capacity + v.SetLen(len(csvWriter.records)) + reflect.Copy(v, reflect.ValueOf(csvWriter.records)) + + return nil + + case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8: + var buf bytes.Buffer + csvWriter := csv.NewWriter(&buf) + o.applyToWriter(csvWriter) + if err := bufferedCSV(csvWriter, csvReader, o); err != nil { + return err + } + v.SetBytes(buf.Bytes()) + + return nil + + case t.Kind() == reflect.String: + var buf bytes.Buffer + csvWriter := csv.NewWriter(&buf) + o.applyToWriter(csvWriter) + if err := bufferedCSV(csvWriter, csvReader, o); err != nil { + return err + } + v.SetString(buf.String()) + + return nil + + default: + return fmt.Errorf("%v (%T) is not supported by the CSVConsumer, %s", + data, data, "can be resolved by supporting CSVWriter/Writer/BinaryUnmarshaler interface", + ) + } } - csvWriter.Flush() - return nil }) } -// CSVProducer creates a new CSV producer -func CSVProducer() Producer { +// CSVProducer creates a new CSV producer. +// +// The producer takes input data then writes as CSV to an output writer (essentially as a pipe). +// +// Supported input underlying types and interfaces, prioritized in this order: +// - *csv.Reader +// - CSVReader (reader options are ignored) +// - io.Reader +// - io.WriterTo +// - encoding.BinaryMarshaler +// - [][]string +// - []byte +// - string +// +// The producer prioritizes situations where buffering the input is not required. +func CSVProducer(opts ...CSVOpt) Producer { + o := csvOptsWithDefaults(opts) + return ProducerFunc(func(writer io.Writer, data interface{}) error { if writer == nil { return errors.New("CSVProducer requires a writer") } + if data == nil { + return errors.New("nil data for CSVProducer") + } - dataBytes, ok := data.([]byte) - if !ok { - return errors.New("data type must be byte array") + csvWriter := csv.NewWriter(writer) + o.applyToWriter(csvWriter) + closer := defaultCloser + if o.closeStream { + if cl, isWriterCloser := writer.(io.Closer); isWriterCloser { + closer = cl.Close + } } + defer func() { + _ = closer() + }() - csvReader := csv.NewReader(bytes.NewBuffer(dataBytes)) - records, err := csvReader.ReadAll() - if err != nil { - return err + if rc, isDataCloser := data.(io.ReadCloser); isDataCloser { + defer rc.Close() } - csvWriter := csv.NewWriter(writer) - for _, r := range records { - if err := csvWriter.Write(r); err != nil { + + switch origin := data.(type) { + case *csv.Reader: + csvReader := origin + o.applyToReader(csvReader) + + return pipeCSV(csvWriter, csvReader, o) + + case CSVReader: + csvReader := origin + // no reader options available + + return pipeCSV(csvWriter, csvReader, o) + + case io.Reader: + csvReader := csv.NewReader(origin) + o.applyToReader(csvReader) + + return pipeCSV(csvWriter, csvReader, o) + + case io.WriterTo: + // async piping of the writes performed by WriteTo + r, w := io.Pipe() + csvReader := csv.NewReader(r) + o.applyToReader(csvReader) + + pipe, _ := errgroup.WithContext(context.Background()) + pipe.Go(func() error { + _, err := origin.WriteTo(w) + _ = w.Close() + return err + }) + + pipe.Go(func() error { + defer func() { + _ = r.Close() + }() + + return pipeCSV(csvWriter, csvReader, o) + }) + + return pipe.Wait() + + case encoding.BinaryMarshaler: + buf, err := origin.MarshalBinary() + if err != nil { return err } + rdr := bytes.NewBuffer(buf) + csvReader := csv.NewReader(rdr) + + return bufferedCSV(csvWriter, csvReader, o) + + default: + // support [][]string, []byte, string (or pointers to those) + v := reflect.Indirect(reflect.ValueOf(data)) + t := v.Type() + + switch { + case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Slice && t.Elem().Elem().Kind() == reflect.String: + csvReader := &csvRecordsWriter{ + records: make([][]string, v.Len()), + } + reflect.Copy(reflect.ValueOf(csvReader.records), v) + + return pipeCSV(csvWriter, csvReader, o) + + case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8: + buf := bytes.NewBuffer(v.Bytes()) + csvReader := csv.NewReader(buf) + o.applyToReader(csvReader) + + return bufferedCSV(csvWriter, csvReader, o) + + case t.Kind() == reflect.String: + buf := bytes.NewBufferString(v.String()) + csvReader := csv.NewReader(buf) + o.applyToReader(csvReader) + + return bufferedCSV(csvWriter, csvReader, o) + + default: + return fmt.Errorf("%v (%T) is not supported by the CSVProducer, %s", + data, data, "can be resolved by supporting CSVReader/Reader/BinaryMarshaler interface", + ) + } } - csvWriter.Flush() - return nil }) } + +// pipeCSV copies CSV records from a CSV reader to a CSV writer +func pipeCSV(csvWriter CSVWriter, csvReader CSVReader, opts csvOpts) error { + for ; opts.skippedLines > 0; opts.skippedLines-- { + _, err := csvReader.Read() + if err != nil { + if errors.Is(err, io.EOF) { + return nil + } + + return err + } + } + + for { + record, err := csvReader.Read() + if err != nil { + if errors.Is(err, io.EOF) { + break + } + + return err + } + + if err := csvWriter.Write(record); err != nil { + return err + } + } + + csvWriter.Flush() + + return csvWriter.Error() +} + +// bufferedCSV copies CSV records from a CSV reader to a CSV writer, +// by first reading all records then writing them at once. +func bufferedCSV(csvWriter *csv.Writer, csvReader *csv.Reader, opts csvOpts) error { + for ; opts.skippedLines > 0; opts.skippedLines-- { + _, err := csvReader.Read() + if err != nil { + if errors.Is(err, io.EOF) { + return nil + } + + return err + } + } + + records, err := csvReader.ReadAll() + if err != nil { + return err + } + + return csvWriter.WriteAll(records) +} diff --git a/vendor/github.com/go-openapi/runtime/csv_options.go b/vendor/github.com/go-openapi/runtime/csv_options.go new file mode 100644 index 000000000000..c16464c57842 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/csv_options.go @@ -0,0 +1,121 @@ +package runtime + +import ( + "encoding/csv" + "io" +) + +// CSVOpts alter the behavior of the CSV consumer or producer. +type CSVOpt func(*csvOpts) + +type csvOpts struct { + csvReader csv.Reader + csvWriter csv.Writer + skippedLines int + closeStream bool +} + +// WithCSVReaderOpts specifies the options to csv.Reader +// when reading CSV. +func WithCSVReaderOpts(reader csv.Reader) CSVOpt { + return func(o *csvOpts) { + o.csvReader = reader + } +} + +// WithCSVWriterOpts specifies the options to csv.Writer +// when writing CSV. +func WithCSVWriterOpts(writer csv.Writer) CSVOpt { + return func(o *csvOpts) { + o.csvWriter = writer + } +} + +// WithCSVSkipLines will skip header lines. +func WithCSVSkipLines(skipped int) CSVOpt { + return func(o *csvOpts) { + o.skippedLines = skipped + } +} + +func WithCSVClosesStream() CSVOpt { + return func(o *csvOpts) { + o.closeStream = true + } +} + +func (o csvOpts) applyToReader(in *csv.Reader) { + if o.csvReader.Comma != 0 { + in.Comma = o.csvReader.Comma + } + if o.csvReader.Comment != 0 { + in.Comment = o.csvReader.Comment + } + if o.csvReader.FieldsPerRecord != 0 { + in.FieldsPerRecord = o.csvReader.FieldsPerRecord + } + + in.LazyQuotes = o.csvReader.LazyQuotes + in.TrimLeadingSpace = o.csvReader.TrimLeadingSpace + in.ReuseRecord = o.csvReader.ReuseRecord +} + +func (o csvOpts) applyToWriter(in *csv.Writer) { + if o.csvWriter.Comma != 0 { + in.Comma = o.csvWriter.Comma + } + in.UseCRLF = o.csvWriter.UseCRLF +} + +func csvOptsWithDefaults(opts []CSVOpt) csvOpts { + var o csvOpts + for _, apply := range opts { + apply(&o) + } + + return o +} + +type CSVWriter interface { + Write([]string) error + Flush() + Error() error +} + +type CSVReader interface { + Read() ([]string, error) +} + +var ( + _ CSVWriter = &csvRecordsWriter{} + _ CSVReader = &csvRecordsWriter{} +) + +// csvRecordsWriter is an internal container to move CSV records back and forth +type csvRecordsWriter struct { + i int + records [][]string +} + +func (w *csvRecordsWriter) Write(record []string) error { + w.records = append(w.records, record) + + return nil +} + +func (w *csvRecordsWriter) Read() ([]string, error) { + if w.i >= len(w.records) { + return nil, io.EOF + } + defer func() { + w.i++ + }() + + return w.records[w.i], nil +} + +func (w *csvRecordsWriter) Flush() {} + +func (w *csvRecordsWriter) Error() error { + return nil +} diff --git a/vendor/github.com/go-openapi/runtime/logger/standard.go b/vendor/github.com/go-openapi/runtime/logger/standard.go index f7e67ebb9e75..30035a777707 100644 --- a/vendor/github.com/go-openapi/runtime/logger/standard.go +++ b/vendor/github.com/go-openapi/runtime/logger/standard.go @@ -5,6 +5,8 @@ import ( "os" ) +var _ Logger = StandardLogger{} + type StandardLogger struct{} func (StandardLogger) Printf(format string, args ...interface{}) { diff --git a/vendor/github.com/go-openapi/runtime/middleware/context.go b/vendor/github.com/go-openapi/runtime/middleware/context.go index d890ed3b370a..44cecf1181e4 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/context.go +++ b/vendor/github.com/go-openapi/runtime/middleware/context.go @@ -18,6 +18,8 @@ import ( stdContext "context" "fmt" "net/http" + "net/url" + "path" "strings" "sync" @@ -35,12 +37,21 @@ import ( // Debug when true turns on verbose logging var Debug = logger.DebugEnabled() + +// Logger is the standard libray logger used for printing debug messages var Logger logger.Logger = logger.StandardLogger{} -func debugLog(format string, args ...interface{}) { //nolint:goprintffuncname - if Debug { - Logger.Printf(format, args...) +func debugLogfFunc(lg logger.Logger) func(string, ...any) { + if logger.DebugEnabled() { + if lg == nil { + return Logger.Debugf + } + + return lg.Debugf } + + // muted logger + return func(_ string, _ ...any) {} } // A Builder can create middlewares @@ -73,10 +84,11 @@ func (fn ResponderFunc) WriteResponse(rw http.ResponseWriter, pr runtime.Produce // used throughout to store request context with the standard context attached // to the http.Request type Context struct { - spec *loads.Document - analyzer *analysis.Spec - api RoutableAPI - router Router + spec *loads.Document + analyzer *analysis.Spec + api RoutableAPI + router Router + debugLogf func(string, ...any) // a logging function to debug context and all components using it } type routableUntypedAPI struct { @@ -189,7 +201,9 @@ func (r *routableUntypedAPI) DefaultConsumes() string { return r.defaultConsumes } -// NewRoutableContext creates a new context for a routable API +// NewRoutableContext creates a new context for a routable API. +// +// If a nil Router is provided, the DefaultRouter (denco-based) will be used. func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Router) *Context { var an *analysis.Spec if spec != nil { @@ -199,26 +213,40 @@ func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Ro return NewRoutableContextWithAnalyzedSpec(spec, an, routableAPI, routes) } -// NewRoutableContextWithAnalyzedSpec is like NewRoutableContext but takes in input the analysed spec too +// NewRoutableContextWithAnalyzedSpec is like NewRoutableContext but takes as input an already analysed spec. +// +// If a nil Router is provided, the DefaultRouter (denco-based) will be used. func NewRoutableContextWithAnalyzedSpec(spec *loads.Document, an *analysis.Spec, routableAPI RoutableAPI, routes Router) *Context { // Either there are no spec doc and analysis, or both of them. if !((spec == nil && an == nil) || (spec != nil && an != nil)) { panic(errors.New(http.StatusInternalServerError, "routable context requires either both spec doc and analysis, or none of them")) } - ctx := &Context{spec: spec, api: routableAPI, analyzer: an, router: routes} - return ctx + return &Context{ + spec: spec, + api: routableAPI, + analyzer: an, + router: routes, + debugLogf: debugLogfFunc(nil), + } } -// NewContext creates a new context wrapper +// NewContext creates a new context wrapper. +// +// If a nil Router is provided, the DefaultRouter (denco-based) will be used. func NewContext(spec *loads.Document, api *untyped.API, routes Router) *Context { var an *analysis.Spec if spec != nil { an = analysis.New(spec.Spec()) } - ctx := &Context{spec: spec, analyzer: an} + ctx := &Context{ + spec: spec, + analyzer: an, + router: routes, + debugLogf: debugLogfFunc(nil), + } ctx.api = newRoutableUntypedAPI(spec, api, ctx) - ctx.router = routes + return ctx } @@ -282,6 +310,13 @@ func (c *Context) BasePath() string { return c.spec.BasePath() } +// SetLogger allows for injecting a logger to catch debug entries. +// +// The logger is enabled in DEBUG mode only. +func (c *Context) SetLogger(lg logger.Logger) { + c.debugLogf = debugLogfFunc(lg) +} + // RequiredProduces returns the accepted content types for responses func (c *Context) RequiredProduces() []string { return c.analyzer.RequiredProduces() @@ -299,6 +334,7 @@ func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, b if err != nil { res = append(res, err) } else { + c.debugLogf("validating content type for %q against [%s]", ct, strings.Join(route.Consumes, ", ")) if err := validateContentType(route.Consumes, ct); err != nil { res = append(res, err) } @@ -397,16 +433,16 @@ func (c *Context) ResponseFormat(r *http.Request, offers []string) (string, *htt var rCtx = r.Context() if v, ok := rCtx.Value(ctxResponseFormat).(string); ok { - debugLog("[%s %s] found response format %q in context", r.Method, r.URL.Path, v) + c.debugLogf("[%s %s] found response format %q in context", r.Method, r.URL.Path, v) return v, r } format := NegotiateContentType(r, offers, "") if format != "" { - debugLog("[%s %s] set response format %q in context", r.Method, r.URL.Path, format) + c.debugLogf("[%s %s] set response format %q in context", r.Method, r.URL.Path, format) r = r.WithContext(stdContext.WithValue(rCtx, ctxResponseFormat, format)) } - debugLog("[%s %s] negotiated response format %q", r.Method, r.URL.Path, format) + c.debugLogf("[%s %s] negotiated response format %q", r.Method, r.URL.Path, format) return format, r } @@ -469,7 +505,7 @@ func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) var rCtx = request.Context() if v, ok := rCtx.Value(ctxBoundParams).(*validation); ok { - debugLog("got cached validation (valid: %t)", len(v.result) == 0) + c.debugLogf("got cached validation (valid: %t)", len(v.result) == 0) if len(v.result) > 0 { return v.bound, request, errors.CompositeValidationError(v.result...) } @@ -481,7 +517,7 @@ func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) if len(result.result) > 0 { return result.bound, request, errors.CompositeValidationError(result.result...) } - debugLog("no validation errors found") + c.debugLogf("no validation errors found") return result.bound, request, nil } @@ -492,7 +528,7 @@ func (c *Context) NotFound(rw http.ResponseWriter, r *http.Request) { // Respond renders the response after doing some content negotiation func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, route *MatchedRoute, data interface{}) { - debugLog("responding to %s %s with produces: %v", r.Method, r.URL.Path, produces) + c.debugLogf("responding to %s %s with produces: %v", r.Method, r.URL.Path, produces) offers := []string{} for _, mt := range produces { if mt != c.api.DefaultProduces() { @@ -501,7 +537,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st } // the default producer is last so more specific producers take precedence offers = append(offers, c.api.DefaultProduces()) - debugLog("offers: %v", offers) + c.debugLogf("offers: %v", offers) var format string format, r = c.ResponseFormat(r, offers) @@ -584,45 +620,92 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st c.api.ServeErrorFor(route.Operation.ID)(rw, r, errors.New(http.StatusInternalServerError, "can't produce response")) } -func (c *Context) APIHandlerSwaggerUI(builder Builder) http.Handler { +// APIHandlerSwaggerUI returns a handler to serve the API. +// +// This handler includes a swagger spec, router and the contract defined in the swagger spec. +// +// A spec UI (SwaggerUI) is served at {API base path}/docs and the spec document at /swagger.json +// (these can be modified with uiOptions). +func (c *Context) APIHandlerSwaggerUI(builder Builder, opts ...UIOption) http.Handler { b := builder if b == nil { b = PassthroughBuilder } - var title string - sp := c.spec.Spec() - if sp != nil && sp.Info != nil && sp.Info.Title != "" { - title = sp.Info.Title - } + specPath, uiOpts, specOpts := c.uiOptionsForHandler(opts) + var swaggerUIOpts SwaggerUIOpts + fromCommonToAnyOptions(uiOpts, &swaggerUIOpts) - swaggerUIOpts := SwaggerUIOpts{ - BasePath: c.BasePath(), - Title: title, + return Spec(specPath, c.spec.Raw(), SwaggerUI(swaggerUIOpts, c.RoutesHandler(b)), specOpts...) +} + +// APIHandlerRapiDoc returns a handler to serve the API. +// +// This handler includes a swagger spec, router and the contract defined in the swagger spec. +// +// A spec UI (RapiDoc) is served at {API base path}/docs and the spec document at /swagger.json +// (these can be modified with uiOptions). +func (c *Context) APIHandlerRapiDoc(builder Builder, opts ...UIOption) http.Handler { + b := builder + if b == nil { + b = PassthroughBuilder } - return Spec("", c.spec.Raw(), SwaggerUI(swaggerUIOpts, c.RoutesHandler(b))) + specPath, uiOpts, specOpts := c.uiOptionsForHandler(opts) + var rapidocUIOpts RapiDocOpts + fromCommonToAnyOptions(uiOpts, &rapidocUIOpts) + + return Spec(specPath, c.spec.Raw(), RapiDoc(rapidocUIOpts, c.RoutesHandler(b)), specOpts...) } -// APIHandler returns a handler to serve the API, this includes a swagger spec, router and the contract defined in the swagger spec -func (c *Context) APIHandler(builder Builder) http.Handler { +// APIHandler returns a handler to serve the API. +// +// This handler includes a swagger spec, router and the contract defined in the swagger spec. +// +// A spec UI (Redoc) is served at {API base path}/docs and the spec document at /swagger.json +// (these can be modified with uiOptions). +func (c *Context) APIHandler(builder Builder, opts ...UIOption) http.Handler { b := builder if b == nil { b = PassthroughBuilder } + specPath, uiOpts, specOpts := c.uiOptionsForHandler(opts) + var redocOpts RedocOpts + fromCommonToAnyOptions(uiOpts, &redocOpts) + + return Spec(specPath, c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b)), specOpts...) +} + +func (c Context) uiOptionsForHandler(opts []UIOption) (string, uiOptions, []SpecOption) { var title string sp := c.spec.Spec() if sp != nil && sp.Info != nil && sp.Info.Title != "" { title = sp.Info.Title } - redocOpts := RedocOpts{ - BasePath: c.BasePath(), - Title: title, + // default options (may be overridden) + optsForContext := []UIOption{ + WithUIBasePath(c.BasePath()), + WithUITitle(title), + } + optsForContext = append(optsForContext, opts...) + uiOpts := uiOptionsWithDefaults(optsForContext) + + // If spec URL is provided, there is a non-default path to serve the spec. + // This makes sure that the UI middleware is aligned with the Spec middleware. + u, _ := url.Parse(uiOpts.SpecURL) + var specPath string + if u != nil { + specPath = u.Path + } + + pth, doc := path.Split(specPath) + if pth == "." { + pth = "" } - return Spec("", c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b))) + return pth, uiOpts, []SpecOption{WithSpecDocument(doc)} } // RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go index 1bfa5c619a44..4377f77a466f 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go @@ -2,6 +2,7 @@ package denco import ( + "errors" "fmt" "sort" "strings" @@ -29,13 +30,13 @@ const ( // Router represents a URL router. type Router struct { + param *doubleArray // SizeHint expects the maximum number of path parameters in records to Build. // SizeHint will be used to determine the capacity of the memory to allocate. // By default, SizeHint will be determined from given records to Build. SizeHint int static map[string]interface{} - param *doubleArray } // New returns a new Router. @@ -71,7 +72,7 @@ func (rt *Router) Lookup(path string) (data interface{}, params Params, found bo func (rt *Router) Build(records []Record) error { statics, params := makeRecords(records) if len(params) > MaxSize { - return fmt.Errorf("denco: too many records") + return errors.New("denco: too many records") } if rt.SizeHint < 0 { rt.SizeHint = 0 @@ -197,24 +198,29 @@ func (da *doubleArray) lookup(path string, params []Param, idx int) (*node, []Pa if next := nextIndex(da.bc[idx].Base(), TerminationCharacter); next < len(da.bc) && da.bc[next].Check() == TerminationCharacter { return da.node[da.bc[next].Base()], params, true } + BACKTRACKING: for j := len(indices) - 1; j >= 0; j-- { i, idx := int(indices[j]>>32), int(indices[j]&0xffffffff) if da.bc[idx].IsSingleParam() { - idx := nextIndex(da.bc[idx].Base(), ParamCharacter) //nolint:govet - if idx >= len(da.bc) { + nextIdx := nextIndex(da.bc[idx].Base(), ParamCharacter) + if nextIdx >= len(da.bc) { break } + next := NextSeparator(path, i) - params := append(params, Param{Value: path[i:next]}) //nolint:govet - if nd, params, found := da.lookup(path[next:], params, idx); found { //nolint:govet - return nd, params, true + nextParams := params + nextParams = append(nextParams, Param{Value: path[i:next]}) + if nd, nextNextParams, found := da.lookup(path[next:], nextParams, nextIdx); found { + return nd, nextNextParams, true } } + if da.bc[idx].IsWildcardParam() { - idx := nextIndex(da.bc[idx].Base(), WildcardCharacter) //nolint:govet - params := append(params, Param{Value: path[i:]}) //nolint:govet - return da.node[da.bc[idx].Base()], params, true + nextIdx := nextIndex(da.bc[idx].Base(), WildcardCharacter) + nextParams := params + nextParams = append(nextParams, Param{Value: path[i:]}) + return da.node[da.bc[nextIdx].Base()], nextParams, true } } return nil, nil, false @@ -326,7 +332,7 @@ func (da *doubleArray) arrange(records []*record, idx, depth int, usedBase map[i } base = da.findBase(siblings, idx, usedBase) if base > MaxSize { - return -1, nil, nil, fmt.Errorf("denco: too many elements of internal slice") + return -1, nil, nil, errors.New("denco: too many elements of internal slice") } da.setBase(idx, base) return base, siblings, leaf, err @@ -387,7 +393,7 @@ func makeSiblings(records []*record, depth int) (sib []sibling, leaf *record, er case pc == c: continue default: - return nil, nil, fmt.Errorf("denco: BUG: routing table hasn't been sorted") + return nil, nil, errors.New("denco: BUG: routing table hasn't been sorted") } if n > 0 { sib[n-1].end = i diff --git a/vendor/github.com/go-openapi/runtime/middleware/go18.go b/vendor/github.com/go-openapi/runtime/middleware/go18.go deleted file mode 100644 index 1bf4939c4c98..000000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/go18.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go1.8 -// +build go1.8 - -package middleware - -import "net/url" - -func pathUnescape(path string) (string, error) { - return url.PathUnescape(path) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/pre_go18.go b/vendor/github.com/go-openapi/runtime/middleware/pre_go18.go deleted file mode 100644 index 03385251e195..000000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/pre_go18.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build !go1.8 - -package middleware - -import "net/url" - -func pathUnescape(path string) (string, error) { - return url.QueryUnescape(path) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go b/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go index 5cb5314db467..ef75e7441fc9 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go @@ -1,4 +1,3 @@ -//nolint:dupl package middleware import ( @@ -11,66 +10,57 @@ import ( // RapiDocOpts configures the RapiDoc middlewares type RapiDocOpts struct { - // BasePath for the UI path, defaults to: / + // BasePath for the UI, defaults to: / BasePath string - // Path combines with BasePath for the full UI path, defaults to: docs + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". Path string - // SpecURL the url to find the spec for + + // SpecURL is the URL of the spec document. + // + // Defaults to: /swagger.json SpecURL string - // RapiDocURL for the js that generates the rapidoc site, defaults to: https://cdn.jsdelivr.net/npm/rapidoc/bundles/rapidoc.standalone.js - RapiDocURL string + // Title for the documentation site, default to: API documentation Title string + + // Template specifies a custom template to serve the UI + Template string + + // RapiDocURL points to the js asset that generates the rapidoc site. + // + // Defaults to https://unpkg.com/rapidoc/dist/rapidoc-min.js + RapiDocURL string } -// EnsureDefaults in case some options are missing func (r *RapiDocOpts) EnsureDefaults() { - if r.BasePath == "" { - r.BasePath = "/" - } - if r.Path == "" { - r.Path = defaultDocsPath - } - if r.SpecURL == "" { - r.SpecURL = defaultDocsURL - } + common := toCommonUIOptions(r) + common.EnsureDefaults() + fromCommonToAnyOptions(common, r) + + // rapidoc-specifics if r.RapiDocURL == "" { r.RapiDocURL = rapidocLatest } - if r.Title == "" { - r.Title = defaultDocsTitle + if r.Template == "" { + r.Template = rapidocTemplate } } // RapiDoc creates a middleware to serve a documentation site for a swagger spec. +// // This allows for altering the spec before starting the http listener. func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler { opts.EnsureDefaults() pth := path.Join(opts.BasePath, opts.Path) - tmpl := template.Must(template.New("rapidoc").Parse(rapidocTemplate)) - - buf := bytes.NewBuffer(nil) - _ = tmpl.Execute(buf, opts) - b := buf.Bytes() - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if r.URL.Path == pth { - rw.Header().Set("Content-Type", "text/html; charset=utf-8") - rw.WriteHeader(http.StatusOK) - - _, _ = rw.Write(b) - return - } + tmpl := template.Must(template.New("rapidoc").Parse(opts.Template)) + assets := bytes.NewBuffer(nil) + if err := tmpl.Execute(assets, opts); err != nil { + panic(fmt.Errorf("cannot execute template: %w", err)) + } - if next == nil { - rw.Header().Set("Content-Type", "text/plain") - rw.WriteHeader(http.StatusNotFound) - _, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth))) - return - } - next.ServeHTTP(rw, r) - }) + return serveUI(pth, assets.Bytes(), next) } const ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/redoc.go b/vendor/github.com/go-openapi/runtime/middleware/redoc.go index ca1d4edca9ae..b96b01e7f3fe 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/redoc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/redoc.go @@ -1,4 +1,3 @@ -//nolint:dupl package middleware import ( @@ -11,66 +10,58 @@ import ( // RedocOpts configures the Redoc middlewares type RedocOpts struct { - // BasePath for the UI path, defaults to: / + // BasePath for the UI, defaults to: / BasePath string - // Path combines with BasePath for the full UI path, defaults to: docs + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". Path string - // SpecURL the url to find the spec for + + // SpecURL is the URL of the spec document. + // + // Defaults to: /swagger.json SpecURL string - // RedocURL for the js that generates the redoc site, defaults to: https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js - RedocURL string + // Title for the documentation site, default to: API documentation Title string + + // Template specifies a custom template to serve the UI + Template string + + // RedocURL points to the js that generates the redoc site. + // + // Defaults to: https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js + RedocURL string } // EnsureDefaults in case some options are missing func (r *RedocOpts) EnsureDefaults() { - if r.BasePath == "" { - r.BasePath = "/" - } - if r.Path == "" { - r.Path = defaultDocsPath - } - if r.SpecURL == "" { - r.SpecURL = defaultDocsURL - } + common := toCommonUIOptions(r) + common.EnsureDefaults() + fromCommonToAnyOptions(common, r) + + // redoc-specifics if r.RedocURL == "" { r.RedocURL = redocLatest } - if r.Title == "" { - r.Title = defaultDocsTitle + if r.Template == "" { + r.Template = redocTemplate } } // Redoc creates a middleware to serve a documentation site for a swagger spec. +// // This allows for altering the spec before starting the http listener. func Redoc(opts RedocOpts, next http.Handler) http.Handler { opts.EnsureDefaults() pth := path.Join(opts.BasePath, opts.Path) - tmpl := template.Must(template.New("redoc").Parse(redocTemplate)) - - buf := bytes.NewBuffer(nil) - _ = tmpl.Execute(buf, opts) - b := buf.Bytes() - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if r.URL.Path == pth { - rw.Header().Set("Content-Type", "text/html; charset=utf-8") - rw.WriteHeader(http.StatusOK) - - _, _ = rw.Write(b) - return - } + tmpl := template.Must(template.New("redoc").Parse(opts.Template)) + assets := bytes.NewBuffer(nil) + if err := tmpl.Execute(assets, opts); err != nil { + panic(fmt.Errorf("cannot execute template: %w", err)) + } - if next == nil { - rw.Header().Set("Content-Type", "text/plain") - rw.WriteHeader(http.StatusNotFound) - _, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth))) - return - } - next.ServeHTTP(rw, r) - }) + return serveUI(pth, assets.Bytes(), next) } const ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/request.go b/vendor/github.com/go-openapi/runtime/middleware/request.go index d4b9fc6a29c7..82e14366523f 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/request.go +++ b/vendor/github.com/go-openapi/runtime/middleware/request.go @@ -19,10 +19,10 @@ import ( "reflect" "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/logger" "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" - - "github.com/go-openapi/runtime" ) // UntypedRequestBinder binds and validates the data from a http request @@ -31,6 +31,7 @@ type UntypedRequestBinder struct { Parameters map[string]spec.Parameter Formats strfmt.Registry paramBinders map[string]*untypedParamBinder + debugLogf func(string, ...any) // a logging function to debug context and all components using it } // NewUntypedRequestBinder creates a new binder for reading a request. @@ -44,6 +45,7 @@ func NewUntypedRequestBinder(parameters map[string]spec.Parameter, spec *spec.Sw paramBinders: binders, Spec: spec, Formats: formats, + debugLogf: debugLogfFunc(nil), } } @@ -52,10 +54,10 @@ func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RoutePara val := reflect.Indirect(reflect.ValueOf(data)) isMap := val.Kind() == reflect.Map var result []error - debugLog("binding %d parameters for %s %s", len(o.Parameters), request.Method, request.URL.EscapedPath()) + o.debugLogf("binding %d parameters for %s %s", len(o.Parameters), request.Method, request.URL.EscapedPath()) for fieldName, param := range o.Parameters { binder := o.paramBinders[fieldName] - debugLog("binding parameter %s for %s %s", fieldName, request.Method, request.URL.EscapedPath()) + o.debugLogf("binding parameter %s for %s %s", fieldName, request.Method, request.URL.EscapedPath()) var target reflect.Value if !isMap { binder.Name = fieldName @@ -102,3 +104,14 @@ func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RoutePara return nil } + +// SetLogger allows for injecting a logger to catch debug entries. +// +// The logger is enabled in DEBUG mode only. +func (o *UntypedRequestBinder) SetLogger(lg logger.Logger) { + o.debugLogf = debugLogfFunc(lg) +} + +func (o *UntypedRequestBinder) setDebugLogf(fn func(string, ...any)) { + o.debugLogf = fn +} diff --git a/vendor/github.com/go-openapi/runtime/middleware/router.go b/vendor/github.com/go-openapi/runtime/middleware/router.go index 46b8f87cc725..3a6aee90e50d 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/router.go +++ b/vendor/github.com/go-openapi/runtime/middleware/router.go @@ -17,10 +17,12 @@ package middleware import ( "fmt" "net/http" + "net/url" fpath "path" "regexp" "strings" + "github.com/go-openapi/runtime/logger" "github.com/go-openapi/runtime/security" "github.com/go-openapi/swag" @@ -67,10 +69,10 @@ func (r RouteParams) GetOK(name string) ([]string, bool, bool) { return nil, false, false } -// NewRouter creates a new context aware router middleware +// NewRouter creates a new context-aware router middleware func NewRouter(ctx *Context, next http.Handler) http.Handler { if ctx.router == nil { - ctx.router = DefaultRouter(ctx.spec, ctx.api) + ctx.router = DefaultRouter(ctx.spec, ctx.api, WithDefaultRouterLoggerFunc(ctx.debugLogf)) } return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { @@ -103,41 +105,75 @@ type RoutableAPI interface { DefaultConsumes() string } -// Router represents a swagger aware router +// Router represents a swagger-aware router type Router interface { Lookup(method, path string) (*MatchedRoute, bool) OtherMethods(method, path string) []string } type defaultRouteBuilder struct { - spec *loads.Document - analyzer *analysis.Spec - api RoutableAPI - records map[string][]denco.Record + spec *loads.Document + analyzer *analysis.Spec + api RoutableAPI + records map[string][]denco.Record + debugLogf func(string, ...any) // a logging function to debug context and all components using it } type defaultRouter struct { - spec *loads.Document - routers map[string]*denco.Router + spec *loads.Document + routers map[string]*denco.Router + debugLogf func(string, ...any) // a logging function to debug context and all components using it } -func newDefaultRouteBuilder(spec *loads.Document, api RoutableAPI) *defaultRouteBuilder { +func newDefaultRouteBuilder(spec *loads.Document, api RoutableAPI, opts ...DefaultRouterOpt) *defaultRouteBuilder { + var o defaultRouterOpts + for _, apply := range opts { + apply(&o) + } + if o.debugLogf == nil { + o.debugLogf = debugLogfFunc(nil) // defaults to standard logger + } + return &defaultRouteBuilder{ - spec: spec, - analyzer: analysis.New(spec.Spec()), - api: api, - records: make(map[string][]denco.Record), + spec: spec, + analyzer: analysis.New(spec.Spec()), + api: api, + records: make(map[string][]denco.Record), + debugLogf: o.debugLogf, } } -// DefaultRouter creates a default implemenation of the router -func DefaultRouter(spec *loads.Document, api RoutableAPI) Router { - builder := newDefaultRouteBuilder(spec, api) +// DefaultRouterOpt allows to inject optional behavior to the default router. +type DefaultRouterOpt func(*defaultRouterOpts) + +type defaultRouterOpts struct { + debugLogf func(string, ...any) +} + +// WithDefaultRouterLogger sets the debug logger for the default router. +// +// This is enabled only in DEBUG mode. +func WithDefaultRouterLogger(lg logger.Logger) DefaultRouterOpt { + return func(o *defaultRouterOpts) { + o.debugLogf = debugLogfFunc(lg) + } +} + +// WithDefaultRouterLoggerFunc sets a logging debug method for the default router. +func WithDefaultRouterLoggerFunc(fn func(string, ...any)) DefaultRouterOpt { + return func(o *defaultRouterOpts) { + o.debugLogf = fn + } +} + +// DefaultRouter creates a default implementation of the router +func DefaultRouter(spec *loads.Document, api RoutableAPI, opts ...DefaultRouterOpt) Router { + builder := newDefaultRouteBuilder(spec, api, opts...) if spec != nil { for method, paths := range builder.analyzer.Operations() { for path, operation := range paths { fp := fpath.Join(spec.BasePath(), path) - debugLog("adding route %s %s %q", method, fp, operation.ID) + builder.debugLogf("adding route %s %s %q", method, fp, operation.ID) builder.AddRoute(method, fp, operation) } } @@ -319,24 +355,24 @@ func (m *MatchedRoute) NeedsAuth() bool { func (d *defaultRouter) Lookup(method, path string) (*MatchedRoute, bool) { mth := strings.ToUpper(method) - debugLog("looking up route for %s %s", method, path) + d.debugLogf("looking up route for %s %s", method, path) if Debug { if len(d.routers) == 0 { - debugLog("there are no known routers") + d.debugLogf("there are no known routers") } for meth := range d.routers { - debugLog("got a router for %s", meth) + d.debugLogf("got a router for %s", meth) } } if router, ok := d.routers[mth]; ok { if m, rp, ok := router.Lookup(fpath.Clean(path)); ok && m != nil { if entry, ok := m.(*routeEntry); ok { - debugLog("found a route for %s %s with %d parameters", method, path, len(entry.Parameters)) + d.debugLogf("found a route for %s %s with %d parameters", method, path, len(entry.Parameters)) var params RouteParams for _, p := range rp { - v, err := pathUnescape(p.Value) + v, err := url.PathUnescape(p.Value) if err != nil { - debugLog("failed to escape %q: %v", p.Value, err) + d.debugLogf("failed to escape %q: %v", p.Value, err) v = p.Value } // a workaround to handle fragment/composing parameters until they are supported in denco router @@ -356,10 +392,10 @@ func (d *defaultRouter) Lookup(method, path string) (*MatchedRoute, bool) { return &MatchedRoute{routeEntry: *entry, Params: params}, true } } else { - debugLog("couldn't find a route by path for %s %s", method, path) + d.debugLogf("couldn't find a route by path for %s %s", method, path) } } else { - debugLog("couldn't find a route by method for %s %s", method, path) + d.debugLogf("couldn't find a route by method for %s %s", method, path) } return nil, false } @@ -378,6 +414,10 @@ func (d *defaultRouter) OtherMethods(method, path string) []string { return methods } +func (d *defaultRouter) SetLogger(lg logger.Logger) { + d.debugLogf = debugLogfFunc(lg) +} + // convert swagger parameters per path segment into a denco parameter as multiple parameters per segment are not supported in denco var pathConverter = regexp.MustCompile(`{(.+?)}([^/]*)`) @@ -413,7 +453,7 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper bp = bp[:len(bp)-1] } - debugLog("operation: %#v", *operation) + d.debugLogf("operation: %#v", *operation) if handler, ok := d.api.HandlerFor(method, strings.TrimPrefix(path, bp)); ok { consumes := d.analyzer.ConsumesFor(operation) produces := d.analyzer.ProducesFor(operation) @@ -428,6 +468,8 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper produces = append(produces, defProduces) } + requestBinder := NewUntypedRequestBinder(parameters, d.spec.Spec(), d.api.Formats()) + requestBinder.setDebugLogf(d.debugLogf) record := denco.NewRecord(pathConverter.ReplaceAllString(path, ":$1"), &routeEntry{ BasePath: bp, PathPattern: path, @@ -439,7 +481,7 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper Producers: d.api.ProducersFor(normalizeOffers(produces)), Parameters: parameters, Formats: d.api.Formats(), - Binder: NewUntypedRequestBinder(parameters, d.spec.Spec(), d.api.Formats()), + Binder: requestBinder, Authenticators: d.buildAuthenticators(operation), Authorizer: d.api.Authorizer(), }) @@ -482,7 +524,8 @@ func (d *defaultRouteBuilder) Build() *defaultRouter { routers[method] = router } return &defaultRouter{ - spec: d.spec, - routers: routers, + spec: d.spec, + routers: routers, + debugLogf: d.debugLogf, } } diff --git a/vendor/github.com/go-openapi/runtime/middleware/spec.go b/vendor/github.com/go-openapi/runtime/middleware/spec.go index c288a2b1780b..87e17e342491 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/spec.go +++ b/vendor/github.com/go-openapi/runtime/middleware/spec.go @@ -19,29 +19,84 @@ import ( "path" ) -// Spec creates a middleware to serve a swagger spec. +const ( + contentTypeHeader = "Content-Type" + applicationJSON = "application/json" +) + +// SpecOption can be applied to the Spec serving middleware +type SpecOption func(*specOptions) + +var defaultSpecOptions = specOptions{ + Path: "", + Document: "swagger.json", +} + +type specOptions struct { + Path string + Document string +} + +func specOptionsWithDefaults(opts []SpecOption) specOptions { + o := defaultSpecOptions + for _, apply := range opts { + apply(&o) + } + + return o +} + +// Spec creates a middleware to serve a swagger spec as a JSON document. +// // This allows for altering the spec before starting the http listener. -// This can be useful if you want to serve the swagger spec from another path than /swagger.json -func Spec(basePath string, b []byte, next http.Handler) http.Handler { +// +// The basePath argument indicates the path of the spec document (defaults to "/"). +// Additional SpecOption can be used to change the name of the document (defaults to "swagger.json"). +func Spec(basePath string, b []byte, next http.Handler, opts ...SpecOption) http.Handler { if basePath == "" { basePath = "/" } - pth := path.Join(basePath, "swagger.json") + o := specOptionsWithDefaults(opts) + pth := path.Join(basePath, o.Path, o.Document) return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if r.URL.Path == pth { - rw.Header().Set("Content-Type", "application/json") + if path.Clean(r.URL.Path) == pth { + rw.Header().Set(contentTypeHeader, applicationJSON) rw.WriteHeader(http.StatusOK) - //#nosec _, _ = rw.Write(b) + return } - if next == nil { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(http.StatusNotFound) + if next != nil { + next.ServeHTTP(rw, r) + return } - next.ServeHTTP(rw, r) + + rw.Header().Set(contentTypeHeader, applicationJSON) + rw.WriteHeader(http.StatusNotFound) }) } + +// WithSpecPath sets the path to be joined to the base path of the Spec middleware. +// +// This is empty by default. +func WithSpecPath(pth string) SpecOption { + return func(o *specOptions) { + o.Path = pth + } +} + +// WithSpecDocument sets the name of the JSON document served as a spec. +// +// By default, this is "swagger.json" +func WithSpecDocument(doc string) SpecOption { + return func(o *specOptions) { + if doc == "" { + return + } + + o.Document = doc + } +} diff --git a/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go b/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go index 846e3cfbb4b8..ec3c10cbafaa 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go +++ b/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go @@ -8,40 +8,65 @@ import ( "path" ) -// SwaggerUIOpts configures the Swaggerui middlewares +// SwaggerUIOpts configures the SwaggerUI middleware type SwaggerUIOpts struct { - // BasePath for the UI path, defaults to: / + // BasePath for the API, defaults to: / BasePath string - // Path combines with BasePath for the full UI path, defaults to: docs + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". Path string - // SpecURL the url to find the spec for + + // SpecURL is the URL of the spec document. + // + // Defaults to: /swagger.json SpecURL string + + // Title for the documentation site, default to: API documentation + Title string + + // Template specifies a custom template to serve the UI + Template string + // OAuthCallbackURL the url called after OAuth2 login OAuthCallbackURL string // The three components needed to embed swagger-ui - SwaggerURL string + + // SwaggerURL points to the js that generates the SwaggerUI site. + // + // Defaults to: https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js + SwaggerURL string + SwaggerPresetURL string SwaggerStylesURL string Favicon32 string Favicon16 string - - // Title for the documentation site, default to: API documentation - Title string } // EnsureDefaults in case some options are missing func (r *SwaggerUIOpts) EnsureDefaults() { - if r.BasePath == "" { - r.BasePath = "/" - } - if r.Path == "" { - r.Path = defaultDocsPath + r.ensureDefaults() + + if r.Template == "" { + r.Template = swaggeruiTemplate } - if r.SpecURL == "" { - r.SpecURL = defaultDocsURL +} + +func (r *SwaggerUIOpts) EnsureDefaultsOauth2() { + r.ensureDefaults() + + if r.Template == "" { + r.Template = swaggerOAuthTemplate } +} + +func (r *SwaggerUIOpts) ensureDefaults() { + common := toCommonUIOptions(r) + common.EnsureDefaults() + fromCommonToAnyOptions(common, r) + + // swaggerui-specifics if r.OAuthCallbackURL == "" { r.OAuthCallbackURL = path.Join(r.BasePath, r.Path, "oauth2-callback") } @@ -60,40 +85,22 @@ func (r *SwaggerUIOpts) EnsureDefaults() { if r.Favicon32 == "" { r.Favicon32 = swaggerFavicon32Latest } - if r.Title == "" { - r.Title = defaultDocsTitle - } } // SwaggerUI creates a middleware to serve a documentation site for a swagger spec. +// // This allows for altering the spec before starting the http listener. func SwaggerUI(opts SwaggerUIOpts, next http.Handler) http.Handler { opts.EnsureDefaults() pth := path.Join(opts.BasePath, opts.Path) - tmpl := template.Must(template.New("swaggerui").Parse(swaggeruiTemplate)) - - buf := bytes.NewBuffer(nil) - _ = tmpl.Execute(buf, &opts) - b := buf.Bytes() - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if path.Join(r.URL.Path) == pth { - rw.Header().Set("Content-Type", "text/html; charset=utf-8") - rw.WriteHeader(http.StatusOK) - - _, _ = rw.Write(b) - return - } - - if next == nil { - rw.Header().Set("Content-Type", "text/plain") - rw.WriteHeader(http.StatusNotFound) - _, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth))) - return - } - next.ServeHTTP(rw, r) - }) + tmpl := template.Must(template.New("swaggerui").Parse(opts.Template)) + assets := bytes.NewBuffer(nil) + if err := tmpl.Execute(assets, opts); err != nil { + panic(fmt.Errorf("cannot execute template: %w", err)) + } + + return serveUI(pth, assets.Bytes(), next) } const ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go b/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go index 576f6003f7b9..e81212f71c80 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go +++ b/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go @@ -4,37 +4,20 @@ import ( "bytes" "fmt" "net/http" - "path" "text/template" ) func SwaggerUIOAuth2Callback(opts SwaggerUIOpts, next http.Handler) http.Handler { - opts.EnsureDefaults() + opts.EnsureDefaultsOauth2() pth := opts.OAuthCallbackURL - tmpl := template.Must(template.New("swaggeroauth").Parse(swaggerOAuthTemplate)) + tmpl := template.Must(template.New("swaggeroauth").Parse(opts.Template)) + assets := bytes.NewBuffer(nil) + if err := tmpl.Execute(assets, opts); err != nil { + panic(fmt.Errorf("cannot execute template: %w", err)) + } - buf := bytes.NewBuffer(nil) - _ = tmpl.Execute(buf, &opts) - b := buf.Bytes() - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if path.Join(r.URL.Path) == pth { - rw.Header().Set("Content-Type", "text/html; charset=utf-8") - rw.WriteHeader(http.StatusOK) - - _, _ = rw.Write(b) - return - } - - if next == nil { - rw.Header().Set("Content-Type", "text/plain") - rw.WriteHeader(http.StatusNotFound) - _, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth))) - return - } - next.ServeHTTP(rw, r) - }) + return serveUI(pth, assets.Bytes(), next) } const ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/ui_defaults.go b/vendor/github.com/go-openapi/runtime/middleware/ui_defaults.go deleted file mode 100644 index 25817d205169..000000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/ui_defaults.go +++ /dev/null @@ -1,8 +0,0 @@ -package middleware - -const ( - // constants that are common to all UI-serving middlewares - defaultDocsPath = "docs" - defaultDocsURL = "/swagger.json" - defaultDocsTitle = "API Documentation" -) diff --git a/vendor/github.com/go-openapi/runtime/middleware/ui_options.go b/vendor/github.com/go-openapi/runtime/middleware/ui_options.go new file mode 100644 index 000000000000..b86efa0089ee --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/middleware/ui_options.go @@ -0,0 +1,173 @@ +package middleware + +import ( + "bytes" + "encoding/gob" + "fmt" + "net/http" + "path" + "strings" +) + +const ( + // constants that are common to all UI-serving middlewares + defaultDocsPath = "docs" + defaultDocsURL = "/swagger.json" + defaultDocsTitle = "API Documentation" +) + +// uiOptions defines common options for UI serving middlewares. +type uiOptions struct { + // BasePath for the UI, defaults to: / + BasePath string + + // Path combines with BasePath to construct the path to the UI, defaults to: "docs". + Path string + + // SpecURL is the URL of the spec document. + // + // Defaults to: /swagger.json + SpecURL string + + // Title for the documentation site, default to: API documentation + Title string + + // Template specifies a custom template to serve the UI + Template string +} + +// toCommonUIOptions converts any UI option type to retain the common options. +// +// This uses gob encoding/decoding to convert common fields from one struct to another. +func toCommonUIOptions(opts interface{}) uiOptions { + var buf bytes.Buffer + enc := gob.NewEncoder(&buf) + dec := gob.NewDecoder(&buf) + var o uiOptions + err := enc.Encode(opts) + if err != nil { + panic(err) + } + + err = dec.Decode(&o) + if err != nil { + panic(err) + } + + return o +} + +func fromCommonToAnyOptions[T any](source uiOptions, target *T) { + var buf bytes.Buffer + enc := gob.NewEncoder(&buf) + dec := gob.NewDecoder(&buf) + err := enc.Encode(source) + if err != nil { + panic(err) + } + + err = dec.Decode(target) + if err != nil { + panic(err) + } +} + +// UIOption can be applied to UI serving middleware, such as Context.APIHandler or +// Context.APIHandlerSwaggerUI to alter the defaut behavior. +type UIOption func(*uiOptions) + +func uiOptionsWithDefaults(opts []UIOption) uiOptions { + var o uiOptions + for _, apply := range opts { + apply(&o) + } + + return o +} + +// WithUIBasePath sets the base path from where to serve the UI assets. +// +// By default, Context middleware sets this value to the API base path. +func WithUIBasePath(base string) UIOption { + return func(o *uiOptions) { + if !strings.HasPrefix(base, "/") { + base = "/" + base + } + o.BasePath = base + } +} + +// WithUIPath sets the path from where to serve the UI assets (i.e. /{basepath}/{path}. +func WithUIPath(pth string) UIOption { + return func(o *uiOptions) { + o.Path = pth + } +} + +// WithUISpecURL sets the path from where to serve swagger spec document. +// +// This may be specified as a full URL or a path. +// +// By default, this is "/swagger.json" +func WithUISpecURL(specURL string) UIOption { + return func(o *uiOptions) { + o.SpecURL = specURL + } +} + +// WithUITitle sets the title of the UI. +// +// By default, Context middleware sets this value to the title found in the API spec. +func WithUITitle(title string) UIOption { + return func(o *uiOptions) { + o.Title = title + } +} + +// WithTemplate allows to set a custom template for the UI. +// +// UI middleware will panic if the template does not parse or execute properly. +func WithTemplate(tpl string) UIOption { + return func(o *uiOptions) { + o.Template = tpl + } +} + +// EnsureDefaults in case some options are missing +func (r *uiOptions) EnsureDefaults() { + if r.BasePath == "" { + r.BasePath = "/" + } + if r.Path == "" { + r.Path = defaultDocsPath + } + if r.SpecURL == "" { + r.SpecURL = defaultDocsURL + } + if r.Title == "" { + r.Title = defaultDocsTitle + } +} + +// serveUI creates a middleware that serves a templated asset as text/html. +func serveUI(pth string, assets []byte, next http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if path.Clean(r.URL.Path) == pth { + rw.Header().Set(contentTypeHeader, "text/html; charset=utf-8") + rw.WriteHeader(http.StatusOK) + _, _ = rw.Write(assets) + + return + } + + if next != nil { + next.ServeHTTP(rw, r) + + return + } + + rw.Header().Set(contentTypeHeader, "text/plain") + rw.WriteHeader(http.StatusNotFound) + _, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth))) + }) +} diff --git a/vendor/github.com/go-openapi/runtime/middleware/validation.go b/vendor/github.com/go-openapi/runtime/middleware/validation.go index 1f0135b5788d..0a5356c6075e 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/validation.go +++ b/vendor/github.com/go-openapi/runtime/middleware/validation.go @@ -35,7 +35,6 @@ type validation struct { // ContentType validates the content type of a request func validateContentType(allowed []string, actual string) error { - debugLog("validating content type for %q against [%s]", actual, strings.Join(allowed, ", ")) if len(allowed) == 0 { return nil } @@ -57,13 +56,13 @@ func validateContentType(allowed []string, actual string) error { } func validateRequest(ctx *Context, request *http.Request, route *MatchedRoute) *validation { - debugLog("validating request %s %s", request.Method, request.URL.EscapedPath()) validate := &validation{ context: ctx, request: request, route: route, bound: make(map[string]interface{}), } + validate.debugLogf("validating request %s %s", request.Method, request.URL.EscapedPath()) validate.contentType() if len(validate.result) == 0 { @@ -76,8 +75,12 @@ func validateRequest(ctx *Context, request *http.Request, route *MatchedRoute) * return validate } +func (v *validation) debugLogf(format string, args ...any) { + v.context.debugLogf(format, args...) +} + func (v *validation) parameters() { - debugLog("validating request parameters for %s %s", v.request.Method, v.request.URL.EscapedPath()) + v.debugLogf("validating request parameters for %s %s", v.request.Method, v.request.URL.EscapedPath()) if result := v.route.Binder.Bind(v.request, v.route.Params, v.route.Consumer, v.bound); result != nil { if result.Error() == "validation failure list" { for _, e := range result.(*errors.Validation).Value.([]interface{}) { @@ -91,7 +94,7 @@ func (v *validation) parameters() { func (v *validation) contentType() { if len(v.result) == 0 && runtime.HasBody(v.request) { - debugLog("validating body content type for %s %s", v.request.Method, v.request.URL.EscapedPath()) + v.debugLogf("validating body content type for %s %s", v.request.Method, v.request.URL.EscapedPath()) ct, _, req, err := v.context.ContentType(v.request) if err != nil { v.result = append(v.result, err) @@ -100,6 +103,7 @@ func (v *validation) contentType() { } if len(v.result) == 0 { + v.debugLogf("validating content type for %q against [%s]", ct, strings.Join(v.route.Consumes, ", ")) if err := validateContentType(v.route.Consumes, ct); err != nil { v.result = append(v.result, err) } diff --git a/vendor/github.com/go-openapi/spec/README.md b/vendor/github.com/go-openapi/spec/README.md index 822172ff7965..7fd2810c6983 100644 --- a/vendor/github.com/go-openapi/spec/README.md +++ b/vendor/github.com/go-openapi/spec/README.md @@ -29,3 +29,26 @@ The object model for OpenAPI specification documents. > This [discussion thread](https://github.com/go-openapi/spec/issues/21) relates the full story. > > An early attempt to support Swagger 3 may be found at: https://github.com/go-openapi/spec3 + +* Does the unmarshaling support YAML? + +> Not directly. The exposed types know only how to unmarshal from JSON. +> +> In order to load a YAML document as a Swagger spec, you need to use the loaders provided by +> github.com/go-openapi/loads +> +> Take a look at the example there: https://pkg.go.dev/github.com/go-openapi/loads#example-Spec +> +> See also https://github.com/go-openapi/spec/issues/164 + +* How can I validate a spec? + +> Validation is provided by [the validate package](http://github.com/go-openapi/validate) + +* Why do we have an `ID` field for `Schema` which is not part of the swagger spec? + +> We found jsonschema compatibility more important: since `id` in jsonschema influences +> how `$ref` are resolved. +> This `id` does not conflict with any property named `id`. +> +> See also https://github.com/go-openapi/spec/issues/23 diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go index fae9c12439db..b81a5699a03e 100644 --- a/vendor/github.com/go-openapi/spec/expander.go +++ b/vendor/github.com/go-openapi/spec/expander.go @@ -57,7 +57,7 @@ func ExpandSpec(spec *Swagger, options *ExpandOptions) error { if !options.SkipSchemas { for key, definition := range spec.Definitions { parentRefs := make([]string, 0, 10) - parentRefs = append(parentRefs, fmt.Sprintf("#/definitions/%s", key)) + parentRefs = append(parentRefs, "#/definitions/"+key) def, err := expandSchema(definition, parentRefs, resolver, specBasePath) if resolver.shouldStopOnError(err) { @@ -213,7 +213,19 @@ func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader, ba } if target.Ref.String() != "" { - return expandSchemaRef(target, parentRefs, resolver, basePath) + if !resolver.options.SkipSchemas { + return expandSchemaRef(target, parentRefs, resolver, basePath) + } + + // when "expand" with SkipSchema, we just rebase the existing $ref without replacing + // the full schema. + rebasedRef, err := NewRef(normalizeURI(target.Ref.String(), basePath)) + if err != nil { + return nil, err + } + target.Ref = denormalizeRef(&rebasedRef, resolver.context.basePath, resolver.context.rootID) + + return &target, nil } for k := range target.Definitions { @@ -525,21 +537,25 @@ func getRefAndSchema(input interface{}) (*Ref, *Schema, error) { } func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePath string) error { - ref, _, err := getRefAndSchema(input) + ref, sch, err := getRefAndSchema(input) if err != nil { return err } - if ref == nil { + if ref == nil && sch == nil { // nothing to do return nil } parentRefs := make([]string, 0, 10) - if err = resolver.deref(input, parentRefs, basePath); resolver.shouldStopOnError(err) { - return err + if ref != nil { + // dereference this $ref + if err = resolver.deref(input, parentRefs, basePath); resolver.shouldStopOnError(err) { + return err + } + + ref, sch, _ = getRefAndSchema(input) } - ref, sch, _ := getRefAndSchema(input) if ref.String() != "" { transitiveResolver := resolver.transitiveResolver(basePath, *ref) basePath = resolver.updateBasePath(transitiveResolver, basePath) @@ -551,6 +567,7 @@ func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePa if ref != nil { *ref = Ref{} } + return nil } @@ -560,38 +577,29 @@ func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePa return ern } - switch { - case resolver.isCircular(&rebasedRef, basePath, parentRefs...): + if resolver.isCircular(&rebasedRef, basePath, parentRefs...) { // this is a circular $ref: stop expansion if !resolver.options.AbsoluteCircularRef { sch.Ref = denormalizeRef(&rebasedRef, resolver.context.basePath, resolver.context.rootID) } else { sch.Ref = rebasedRef } - case !resolver.options.SkipSchemas: - // schema expanded to a $ref in another root - sch.Ref = rebasedRef - debugLog("rebased to: %s", sch.Ref.String()) - default: - // skip schema expansion but rebase $ref to schema - sch.Ref = denormalizeRef(&rebasedRef, resolver.context.basePath, resolver.context.rootID) } } + // $ref expansion or rebasing is performed by expandSchema below if ref != nil { *ref = Ref{} } // expand schema - if !resolver.options.SkipSchemas { - s, err := expandSchema(*sch, parentRefs, resolver, basePath) - if resolver.shouldStopOnError(err) { - return err - } - if s == nil { - // guard for when continuing on error - return nil - } + // yes, we do it even if options.SkipSchema is true: we have to go down that rabbit hole and rebase nested $ref) + s, err := expandSchema(*sch, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return err + } + + if s != nil { // guard for when continuing on error *sch = *s } diff --git a/vendor/github.com/go-openapi/swag/.codecov.yml b/vendor/github.com/go-openapi/swag/.codecov.yml new file mode 100644 index 000000000000..3354f44b28e9 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.codecov.yml @@ -0,0 +1,4 @@ +ignore: + - jsonutils/fixtures_test + - jsonutils/adapters/ifaces/mocks + - jsonutils/adapters/testintegration/benchmarks diff --git a/vendor/github.com/go-openapi/swag/.golangci.yml b/vendor/github.com/go-openapi/swag/.golangci.yml index d2fafb8a2bb0..126264a6b898 100644 --- a/vendor/github.com/go-openapi/swag/.golangci.yml +++ b/vendor/github.com/go-openapi/swag/.golangci.yml @@ -1,56 +1,78 @@ -linters-settings: - gocyclo: - min-complexity: 45 - dupl: - threshold: 200 - goconst: - min-len: 2 - min-occurrences: 3 - +version: "2" linters: - enable-all: true + default: all disable: - - recvcheck - - unparam - - lll - - gochecknoinits - - gochecknoglobals + - cyclop + - depguard + - errchkjson + - errorlint + - exhaustruct + - forcetypeassert - funlen - - godox + - gochecknoglobals + - gochecknoinits - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage - - nlreturn - - errorlint - - nestif - godot - - gofumpt + - godox + - gomoddirectives + - gosmopolitan + - inamedparam + - intrange + - ireturn + - lll + - musttag + - modernize + - nestif + - nlreturn + - nonamedreturns + - noinlineerr - paralleltest - - tparallel + - recvcheck + - testpackage - thelper - - exhaustruct + - tagliatelle + - tparallel + - unparam - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - #- deadcode - #- interfacer - #- scopelint - #- varcheck - #- structcheck - #- golint - #- nosnakecase - #- maligned - #- goerr113 - #- ifshort - #- gomnd - #- exhaustivestruct + - whitespace + - wrapcheck + - wsl + - wsl_v5 + settings: + dupl: + threshold: 200 + goconst: + min-len: 2 + min-occurrences: 3 + gocyclo: + min-complexity: 45 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ +issues: + # Maximum issues count per one linter. + # Set to 0 to disable. + # Default: 50 + max-issues-per-linter: 0 + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 0 diff --git a/vendor/github.com/go-openapi/swag/.mockery.yml b/vendor/github.com/go-openapi/swag/.mockery.yml new file mode 100644 index 000000000000..8557cb58d331 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.mockery.yml @@ -0,0 +1,30 @@ +all: false +dir: '{{.InterfaceDir}}' +filename: mocks_test.go +force-file-write: true +formatter: goimports +include-auto-generated: false +log-level: info +structname: '{{.Mock}}{{.InterfaceName}}' +pkgname: '{{.SrcPackageName}}' +recursive: false +require-template-schema-exists: true +template: matryer +template-schema: '{{.Template}}.schema.json' +packages: + github.com/go-openapi/swag/jsonutils/adapters/ifaces: + config: + dir: jsonutils/adapters/ifaces/mocks + filename: mocks.go + pkgname: 'mocks' + force-file-write: true + all: true + github.com/go-openapi/swag/jsonutils/adapters/testintegration: + config: + inpackage: true + dir: jsonutils/adapters/testintegration + force-file-write: true + all: true + interfaces: + EJMarshaler: + EJUnmarshaler: diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md index a7292229980f..371fd55fdc36 100644 --- a/vendor/github.com/go-openapi/swag/README.md +++ b/vendor/github.com/go-openapi/swag/README.md @@ -1,23 +1,239 @@ # Swag [![Build Status](https://github.com/go-openapi/swag/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/swag/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) [![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/swag/master/LICENSE) +[![license](https://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) [![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/swag.svg)](https://pkg.go.dev/github.com/go-openapi/swag) [![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/swag)](https://goreportcard.com/report/github.com/go-openapi/swag) -Contains a bunch of helper functions for go-openapi and go-swagger projects. +Package `swag` contains a bunch of helper functions for go-openapi and go-swagger projects. You may also use it standalone for your projects. -* convert between value and pointers for builtin types -* convert from string to builtin types (wraps strconv) -* fast json concatenation -* search in path -* load from file or http -* name mangling +> **NOTE** +> `swag` is one of the foundational building blocks of the go-openapi initiative. +> Most repositories in `github.com/go-openapi/...` depend on it in some way. +> And so does our CLI tool `github.com/go-swagger/go-swagger`, +> as well as the code generated by this tool. +* [Contents](#contents) +* [Dependencies](#dependencies) +* [Release Notes](#release-notes) +* [Licensing](#licensing) +* [Note to contributors](#note-to-contributors) +* [TODOs, suggestions and plans](#todos-suggestions-and-plans) -This repo has only few dependencies outside of the standard library: +## Contents -* YAML utilities depend on `gopkg.in/yaml.v3` -* `github.com/mailru/easyjson v0.7.7` +`go-openapi/swag` exposes a collection of relatively independent modules. + +Moving forward, no additional feature will be added to the `swag` API directly at the root package level, +which remains there for backward-compatibility purposes. All exported top-level features are now deprecated. + +Child modules will continue to evolve and some new ones may be added in the future. + +| Module | Content | Main features | +|---------------|---------|---------------| +| `cmdutils` | utilities to work with CLIs || +| `conv` | type conversion utilities | convert between values and pointers for any types
convert from string to builtin types (wraps `strconv`)
require `./typeutils` (test dependency)
| +| `fileutils` | file utilities | | +| `jsonname` | JSON utilities | infer JSON names from `go` properties
| +| `jsonutils` | JSON utilities | fast json concatenation
read and write JSON from and to dynamic `go` data structures
~require `github.com/mailru/easyjson`~
| +| `loading` | file loading | load from file or http
require `./yamlutils`
| +| `mangling` | safe name generation | name mangling for `go`
| +| `netutils` | networking utilities | host, port from address
| +| `stringutils` | `string` utilities | search in slice (with case-insensitive)
split/join query parameters as arrays
| +| `typeutils` | `go` types utilities | check the zero value for any type
safe check for a nil value
| +| `yamlutils` | YAML utilities | converting YAML to JSON
loading YAML into a dynamic YAML document
maintaining the original order of keys in YAML objects
require `./jsonutils`
~require `github.com/mailru/easyjson`~
require `go.yaml.in/yaml/v3`
| + +--- + +## Dependencies + +The root module `github.com/go-openapi/swag` at the repo level maintains a few +dependencies outside of the standard library. + +* YAML utilities depend on `go.yaml.in/yaml/v3` +* JSON utilities depend on their registered adapter module: + * by default, only the standard library is used + * `github.com/mailru/easyjson` is now only a dependency for module + `github.com/go-openapi/swag/jsonutils/adapters/easyjson/json`, + for users willing to import that module. + * integration tests and benchmarks use all the dependencies are published as their own module +* other dependencies are test dependencies drawn from `github.com/stretchr/testify` + +## Release notes + +### v0.25.4 + +** mangling** + +Bug fix + +* [x] mangler may panic with pluralized overlapping initialisms + +Tests + +* [x] introduced fuzz tests + +### v0.25.3 + +** mangling** + +Bug fix + +* [x] mangler may panic with pluralized initialisms + +### v0.25.2 + +Minor changes due to internal maintenance that don't affect the behavior of the library. + +* [x] removed indirect test dependencies by switching all tests to `go-openapi/testify`, + a fork of `stretch/testify` with zero-dependencies. +* [x] improvements to CI to catch test reports. +* [x] modernized licensing annotations in source code, using the more compact SPDX annotations + rather than the full license terms. +* [x] simplified a bit JSON & YAML testing by using newly available assertions +* started the journey to an OpenSSF score card badge: + * [x] explicited permissions in CI workflows + * [x] published security policy + * pinned dependencies to github actions + * introduced fuzzing in tests + +### v0.25.1 + +* fixes a data race that could occur when using the standard library implementation of a JSON ordered map + +### v0.25.0 + +**New with this release**: + +* requires `go1.24`, as iterators are being introduced +* removes the dependency to `mailru/easyjson` by default (#68) + * functionality remains the same, but performance may somewhat degrade for applications + that relied on `easyjson` + * users of the JSON or YAML utilities who want to use `easyjson` as their preferred JSON serializer library + will be able to do so by registering this the corresponding JSON adapter at runtime. See below. + * ordered keys in JSON and YAML objects: this feature used to rely solely on `easyjson`. + With this release, an implementation relying on the standard `encoding/json` is provided. + * an independent [benchmark](./jsonutils/adapters/testintegration/benchmarks/README.md) to compare the different adapters +* improves the "float is integer" check (`conv.IsFloat64AJSONInteger`) (#59) +* removes the _direct_ dependency to `gopkg.in/yaml.v3` (indirect dependency is still incurred through `stretchr/testify`) (#127) +* exposed `conv.IsNil()` (previously kept private): a safe nil check (accounting for the "non-nil interface with nil value" nonsensical go trick) + +**What coming next?** + +Moving forward, we want to : +* provide an implementation of the JSON adapter based on `encoding/json/v2`, for `go1.25` builds. +* provide similar implementations for `goccy/go-json` and `jsoniterator/go`, and perhaps some other + similar libraries may be interesting too. + + +**How to explicitly register a dependency at runtime**? + +The following would maintain how JSON utilities proposed by `swag` used work, up to `v0.24.1`. + + ```go + import ( + "github.com/go-openapi/swag/jsonutils/adapters" + easyjson "github.com/go-openapi/swag/jsonutils/adapters/easyjson/json" + ) + + func init() { + easyjson.Register(adapters.Registry) + } + ``` + +Subsequent calls to `jsonutils.ReadJSON()` or `jsonutils.WriteJSON()` will switch to `easyjson` +whenever the passed data structures implement the `easyjson.Unmarshaler` or `easyjson.Marshaler` respectively, +or fallback to the standard library. + +For more details, you may also look at our +[integration tests](jsonutils/adapters/testintegration/integration_suite_test.go#29). + +### v0.24.0 + +With this release, we have largely modernized the API of `swag`: + +* The traditional `swag` API is still supported: code that imports `swag` will still + compile and work the same. +* A deprecation notice is published to encourage consumers of this library to adopt + the newer API +* **Deprecation notice** + * configuration through global variables is now deprecated, in favor of options passed as parameters + * all helper functions are moved to more specialized packages, which are exposed as + go modules. Importing such a module would reduce the footprint of dependencies. + * _all_ functions, variables, constants exposed by the deprecated API have now moved, so + that consumers of the new API no longer need to import github.com/go-openapi/swag, but + should import the desired sub-module(s). + +**New with this release**: + +* [x] type converters and pointer to value helpers now support generic types +* [x] name mangling now support pluralized initialisms (issue #46) + Strings like "contact IDs" are now recognized as such a plural form and mangled as a linter would expect. +* [x] performance: small improvements to reduce the overhead of convert/format wrappers (see issues #110, or PR #108) +* [x] performance: name mangling utilities run ~ 10% faster (PR #115) + +--- + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +## Note to contributors + +A mono-repo structure comes with some unavoidable extra pains... + +* Testing + +> The usual `go test ./...` command, run from the root of this repo won't work any longer to test all submodules. +> +> Each module constitutes an independant unit of test. So you have to run `go test` inside each module. +> Or you may take a look at how this is achieved by CI +> [here] https://github.com/go-openapi/swag/blob/master/.github/workflows/go-test.yml). +> +> There are also some alternative tricks using `go work`, for local development, if you feel comfortable with +> go workspaces. Perhaps some day, we'll have a `go work test` to run all tests without any hack. + +* Releasing + +> Each module follows its own independant module versioning. +> +> So you have tags like `mangling/v0.24.0`, `fileutils/v0.24.0` etc that are used by `go mod` and `go get` +> to refer to the tagged version of each module specifically. +> +> This means we may release patches etc to each module independently. +> +> We'd like to adopt the rule that modules in this repo would only differ by a patch version +> (e.g. `v0.24.5` vs `v0.24.3`), and we'll level all modules whenever a minor version is introduced. +> +> A script in `./hack` is provided to tag all modules with the same version in one go. + +* Continuous integration + +> At this moment, all tests in all modules are systematically run over the full test matrix (3 platform x 2 go releases). +> This generates quite a lot of jobs. +> +> We ought to reduce the number of jobs required to test a PR focused on only a few modules. + +## Todos, suggestions and plans + +All kinds of contributions are welcome. + +A few ideas: + +* [x] Complete the split of dependencies to isolate easyjson from the rest +* [x] Improve CI to reduce needed tests +* [x] Replace dependency to `gopkg.in/yaml.v3` (`yamlutil`) +* [ ] Improve mangling utilities (improve readability, support for capitalized words, + better word substitution for non-letter symbols...) +* [ ] Move back to this common shared pot a few of the technical features introduced by go-swagger independently + (e.g. mangle go package names, search package with go modules support, ...) +* [ ] Apply a similar mono-repo approach to go-openapi/strfmt which suffer from similar woes: bloated API, + imposed dependency to some database driver. +* [ ] Adapt `go-swagger` (incl. generated code) to the new `swag` API. +* [ ] Factorize some tests, as there is a lot of redundant testing code in `jsonutils` +* [ ] Benchmark & profiling: publish independently the tool built to analyze and chart benchmarks (e.g. similar to `benchvisual`) +* [ ] more thorough testing for nil / null case +* [ ] ci pipeline to manage releases +* [ ] cleaner mockery generation (doesn't work out of the box for all sub-modules) diff --git a/vendor/github.com/go-openapi/swag/SECURITY.md b/vendor/github.com/go-openapi/swag/SECURITY.md new file mode 100644 index 000000000000..72296a83135d --- /dev/null +++ b/vendor/github.com/go-openapi/swag/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.25.x | :white_check_mark: | + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +please report it privately to the maintainers. + +Please follow the instructions provided by github to +[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). + +TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". diff --git a/vendor/github.com/go-openapi/swag/cmdutils/LICENSE b/vendor/github.com/go-openapi/swag/cmdutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/cmdutils/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/go-openapi/swag/cmdutils/cmd_utils.go b/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go new file mode 100644 index 000000000000..6c7bbb26f03d --- /dev/null +++ b/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package cmdutils + +// CommandLineOptionsGroup represents a group of user-defined command line options. +// +// This is for instance used to configure command line arguments in API servers generated by go-swagger. +type CommandLineOptionsGroup struct { + ShortDescription string + LongDescription string + Options any +} diff --git a/vendor/github.com/go-openapi/swag/cmdutils/doc.go b/vendor/github.com/go-openapi/swag/cmdutils/doc.go new file mode 100644 index 000000000000..31f2c37538a0 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/cmdutils/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package cmdutils brings helpers for CLIs produced by go-openapi +package cmdutils diff --git a/vendor/github.com/go-openapi/swag/cmdutils_iface.go b/vendor/github.com/go-openapi/swag/cmdutils_iface.go new file mode 100644 index 000000000000..bd0c1fc12802 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/cmdutils_iface.go @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/cmdutils" + +// CommandLineOptionsGroup represents a group of user-defined command line options. +// +// Deprecated: use [cmdutils.CommandLineOptionsGroup] instead. +type CommandLineOptionsGroup = cmdutils.CommandLineOptionsGroup diff --git a/vendor/github.com/go-openapi/swag/conv/LICENSE b/vendor/github.com/go-openapi/swag/conv/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/conv/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/go-openapi/swag/conv/convert.go b/vendor/github.com/go-openapi/swag/conv/convert.go new file mode 100644 index 000000000000..f205c3913457 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/conv/convert.go @@ -0,0 +1,161 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +import ( + "math" + "strconv" + "strings" +) + +// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER +const ( + maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 + minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 + epsilon float64 = 1e-9 +) + +// IsFloat64AJSONInteger allows for integers [-2^53, 2^53-1] inclusive. +func IsFloat64AJSONInteger(f float64) bool { + if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { + return false + } + rounded := math.Round(f) + if f == rounded { + return true + } + if rounded == 0 { // f = 0.0 exited above + return false + } + + diff := math.Abs(f - rounded) + if diff == 0 { + return true + } + + // relative error Abs{f - Round(f)) / Round(f)} < ε ; Round(f) + return diff < epsilon*math.Abs(rounded) +} + +// ConvertFloat turns a string into a float numerical value. +func ConvertFloat[T Float](str string) (T, error) { + var v T + f, err := strconv.ParseFloat(str, bitsize(v)) + if err != nil { + return 0, err + } + + return T(f), nil +} + +// ConvertInteger turns a string into a signed integer. +func ConvertInteger[T Signed](str string) (T, error) { + var v T + f, err := strconv.ParseInt(str, 10, bitsize(v)) + if err != nil { + return 0, err + } + + return T(f), nil +} + +// ConvertUinteger turns a string into an unsigned integer. +func ConvertUinteger[T Unsigned](str string) (T, error) { + var v T + f, err := strconv.ParseUint(str, 10, bitsize(v)) + if err != nil { + return 0, err + } + + return T(f), nil +} + +// ConvertBool turns a string into a boolean. +// +// It supports a few more "true" strings than [strconv.ParseBool]: +// +// - it is not case sensitive ("trUe" or "FalsE" work) +// - "ok", "yes", "y", "on", "selected", "checked", "enabled" are all true +// - everything that is not true is false: there is never an actual error returned +func ConvertBool(str string) (bool, error) { + switch strings.ToLower(str) { + case "true", + "1", + "yes", + "ok", + "y", + "on", + "selected", + "checked", + "t", + "enabled": + return true, nil + default: + return false, nil + } +} + +// ConvertFloat32 turns a string into a float32. +func ConvertFloat32(str string) (float32, error) { return ConvertFloat[float32](str) } + +// ConvertFloat64 turns a string into a float64 +func ConvertFloat64(str string) (float64, error) { return ConvertFloat[float64](str) } + +// ConvertInt8 turns a string into an int8 +func ConvertInt8(str string) (int8, error) { return ConvertInteger[int8](str) } + +// ConvertInt16 turns a string into an int16 +func ConvertInt16(str string) (int16, error) { + i, err := strconv.ParseInt(str, 10, 16) + if err != nil { + return 0, err + } + return int16(i), nil +} + +// ConvertInt32 turns a string into an int32 +func ConvertInt32(str string) (int32, error) { + i, err := strconv.ParseInt(str, 10, 32) + if err != nil { + return 0, err + } + return int32(i), nil +} + +// ConvertInt64 turns a string into an int64 +func ConvertInt64(str string) (int64, error) { + return strconv.ParseInt(str, 10, 64) +} + +// ConvertUint8 turns a string into an uint8 +func ConvertUint8(str string) (uint8, error) { + i, err := strconv.ParseUint(str, 10, 8) + if err != nil { + return 0, err + } + return uint8(i), nil +} + +// ConvertUint16 turns a string into an uint16 +func ConvertUint16(str string) (uint16, error) { + i, err := strconv.ParseUint(str, 10, 16) + if err != nil { + return 0, err + } + return uint16(i), nil +} + +// ConvertUint32 turns a string into an uint32 +func ConvertUint32(str string) (uint32, error) { + i, err := strconv.ParseUint(str, 10, 32) + if err != nil { + return 0, err + } + return uint32(i), nil +} + +// ConvertUint64 turns a string into an uint64 +func ConvertUint64(str string) (uint64, error) { + return strconv.ParseUint(str, 10, 64) +} diff --git a/vendor/github.com/go-openapi/swag/conv/convert_types.go b/vendor/github.com/go-openapi/swag/conv/convert_types.go new file mode 100644 index 000000000000..cf4c6495ebc9 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/conv/convert_types.go @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +// Unlicensed credits (idea, concept) +// +// The idea to convert values to pointers and the other way around, was inspired, eons ago, by the aws go sdk. +// +// Nowadays, all sensible API sdk's expose a similar functionality. + +// Pointer returns a pointer to the value passed in. +func Pointer[T any](v T) *T { + return &v +} + +// Value returns a shallow copy of the value of the pointer passed in. +// +// If the pointer is nil, the returned value is the zero value. +func Value[T any](v *T) T { + if v != nil { + return *v + } + + var zero T + return zero +} + +// PointerSlice converts a slice of values into a slice of pointers. +func PointerSlice[T any](src []T) []*T { + dst := make([]*T, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// ValueSlice converts a slice of pointers into a slice of values. +// +// nil elements are zero values. +func ValueSlice[T any](src []*T) []T { + dst := make([]T, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// PointerMap converts a map of values into a map of pointers. +func PointerMap[K comparable, T any](src map[K]T) map[K]*T { + dst := make(map[K]*T) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// ValueMap converts a map of pointers into a map of values. +// +// nil elements are skipped. +func ValueMap[K comparable, T any](src map[K]*T) map[K]T { + dst := make(map[K]T) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} diff --git a/vendor/github.com/go-openapi/swag/conv/doc.go b/vendor/github.com/go-openapi/swag/conv/doc.go new file mode 100644 index 000000000000..1bd6ead6e2d1 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/conv/doc.go @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package conv exposes utilities to convert types. +// +// The Convert and Format families of functions are essentially a shorthand to [strconv] functions, +// using the decimal representation of numbers. +// +// Features: +// +// - from string representation to value ("Convert*") and reciprocally ("Format*") +// - from pointer to value ([Value]) and reciprocally ([Pointer]) +// - from slice of values to slice of pointers ([PointerSlice]) and reciprocally ([ValueSlice]) +// - from map of values to map of pointers ([PointerMap]) and reciprocally ([ValueMap]) +package conv diff --git a/vendor/github.com/go-openapi/swag/conv/format.go b/vendor/github.com/go-openapi/swag/conv/format.go new file mode 100644 index 000000000000..5b87b8e146bb --- /dev/null +++ b/vendor/github.com/go-openapi/swag/conv/format.go @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +import ( + "strconv" +) + +// FormatInteger turns an integer type into a string. +func FormatInteger[T Signed](value T) string { + return strconv.FormatInt(int64(value), 10) +} + +// FormatUinteger turns an unsigned integer type into a string. +func FormatUinteger[T Unsigned](value T) string { + return strconv.FormatUint(uint64(value), 10) +} + +// FormatFloat turns a floating point numerical value into a string. +func FormatFloat[T Float](value T) string { + return strconv.FormatFloat(float64(value), 'f', -1, bitsize(value)) +} + +// FormatBool turns a boolean into a string. +func FormatBool(value bool) string { + return strconv.FormatBool(value) +} diff --git a/vendor/github.com/go-openapi/swag/conv/sizeof.go b/vendor/github.com/go-openapi/swag/conv/sizeof.go new file mode 100644 index 000000000000..494346557381 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/conv/sizeof.go @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +import "unsafe" + +// bitsize returns the size in bits of a type. +// +// NOTE: [unsafe.SizeOf] simply returns the size in bytes of the value. +// For primitive types T, the generic stencil is precompiled and this value +// is resolved at compile time, resulting in an immediate call to [strconv.ParseFloat]. +// +// We may leave up to the go compiler to simplify this function into a +// constant value, which happens in practice at least for primitive types +// (e.g. numerical types). +func bitsize[T Numerical](value T) int { + const bitsPerByte = 8 + return int(unsafe.Sizeof(value)) * bitsPerByte +} diff --git a/vendor/github.com/go-openapi/swag/conv/type_constraints.go b/vendor/github.com/go-openapi/swag/conv/type_constraints.go new file mode 100644 index 000000000000..81135e827e52 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/conv/type_constraints.go @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package conv + +type ( + // these type constraints are redefined after golang.org/x/exp/constraints, + // because importing that package causes an undesired go upgrade. + + // Signed integer types, cf. [golang.org/x/exp/constraints.Signed] + Signed interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 + } + + // Unsigned integer types, cf. [golang.org/x/exp/constraints.Unsigned] + Unsigned interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr + } + + // Float numerical types, cf. [golang.org/x/exp/constraints.Float] + Float interface { + ~float32 | ~float64 + } + + // Numerical types + Numerical interface { + Signed | Unsigned | Float + } +) diff --git a/vendor/github.com/go-openapi/swag/conv_iface.go b/vendor/github.com/go-openapi/swag/conv_iface.go new file mode 100644 index 000000000000..eea7b2e56e33 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/conv_iface.go @@ -0,0 +1,486 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "time" + + "github.com/go-openapi/swag/conv" +) + +// IsFloat64AJSONInteger allows for integers [-2^53, 2^53-1] inclusive. +// +// Deprecated: use [conv.IsFloat64AJSONInteger] instead. +func IsFloat64AJSONInteger(f float64) bool { return conv.IsFloat64AJSONInteger(f) } + +// ConvertBool turns a string into a boolean. +// +// Deprecated: use [conv.ConvertBool] instead. +func ConvertBool(str string) (bool, error) { return conv.ConvertBool(str) } + +// ConvertFloat32 turns a string into a float32. +// +// Deprecated: use [conv.ConvertFloat32] instead. Alternatively, you may use the generic version [conv.ConvertFloat]. +func ConvertFloat32(str string) (float32, error) { return conv.ConvertFloat[float32](str) } + +// ConvertFloat64 turns a string into a float64. +// +// Deprecated: use [conv.ConvertFloat64] instead. Alternatively, you may use the generic version [conv.ConvertFloat]. +func ConvertFloat64(str string) (float64, error) { return conv.ConvertFloat[float64](str) } + +// ConvertInt8 turns a string into an int8. +// +// Deprecated: use [conv.ConvertInt8] instead. Alternatively, you may use the generic version [conv.ConvertInteger]. +func ConvertInt8(str string) (int8, error) { return conv.ConvertInteger[int8](str) } + +// ConvertInt16 turns a string into an int16. +// +// Deprecated: use [conv.ConvertInt16] instead. Alternatively, you may use the generic version [conv.ConvertInteger]. +func ConvertInt16(str string) (int16, error) { return conv.ConvertInteger[int16](str) } + +// ConvertInt32 turns a string into an int32. +// +// Deprecated: use [conv.ConvertInt32] instead. Alternatively, you may use the generic version [conv.ConvertInteger]. +func ConvertInt32(str string) (int32, error) { return conv.ConvertInteger[int32](str) } + +// ConvertInt64 turns a string into an int64. +// +// Deprecated: use [conv.ConvertInt64] instead. Alternatively, you may use the generic version [conv.ConvertInteger]. +func ConvertInt64(str string) (int64, error) { return conv.ConvertInteger[int64](str) } + +// ConvertUint8 turns a string into an uint8. +// +// Deprecated: use [conv.ConvertUint8] instead. Alternatively, you may use the generic version [conv.ConvertUinteger]. +func ConvertUint8(str string) (uint8, error) { return conv.ConvertUinteger[uint8](str) } + +// ConvertUint16 turns a string into an uint16. +// +// Deprecated: use [conv.ConvertUint16] instead. Alternatively, you may use the generic version [conv.ConvertUinteger]. +func ConvertUint16(str string) (uint16, error) { return conv.ConvertUinteger[uint16](str) } + +// ConvertUint32 turns a string into an uint32. +// +// Deprecated: use [conv.ConvertUint32] instead. Alternatively, you may use the generic version [conv.ConvertUinteger]. +func ConvertUint32(str string) (uint32, error) { return conv.ConvertUinteger[uint32](str) } + +// ConvertUint64 turns a string into an uint64. +// +// Deprecated: use [conv.ConvertUint64] instead. Alternatively, you may use the generic version [conv.ConvertUinteger]. +func ConvertUint64(str string) (uint64, error) { return conv.ConvertUinteger[uint64](str) } + +// FormatBool turns a boolean into a string. +// +// Deprecated: use [conv.FormatBool] instead. +func FormatBool(value bool) string { return conv.FormatBool(value) } + +// FormatFloat32 turns a float32 into a string. +// +// Deprecated: use [conv.FormatFloat] instead. +func FormatFloat32(value float32) string { return conv.FormatFloat(value) } + +// FormatFloat64 turns a float64 into a string. +// +// Deprecated: use [conv.FormatFloat] instead. +func FormatFloat64(value float64) string { return conv.FormatFloat(value) } + +// FormatInt8 turns an int8 into a string. +// +// Deprecated: use [conv.FormatInteger] instead. +func FormatInt8(value int8) string { return conv.FormatInteger(value) } + +// FormatInt16 turns an int16 into a string. +// +// Deprecated: use [conv.FormatInteger] instead. +func FormatInt16(value int16) string { return conv.FormatInteger(value) } + +// FormatInt32 turns an int32 into a string +// +// Deprecated: use [conv.FormatInteger] instead. +func FormatInt32(value int32) string { return conv.FormatInteger(value) } + +// FormatInt64 turns an int64 into a string. +// +// Deprecated: use [conv.FormatInteger] instead. +func FormatInt64(value int64) string { return conv.FormatInteger(value) } + +// FormatUint8 turns an uint8 into a string. +// +// Deprecated: use [conv.FormatUinteger] instead. +func FormatUint8(value uint8) string { return conv.FormatUinteger(value) } + +// FormatUint16 turns an uint16 into a string. +// +// Deprecated: use [conv.FormatUinteger] instead. +func FormatUint16(value uint16) string { return conv.FormatUinteger(value) } + +// FormatUint32 turns an uint32 into a string. +// +// Deprecated: use [conv.FormatUinteger] instead. +func FormatUint32(value uint32) string { return conv.FormatUinteger(value) } + +// FormatUint64 turns an uint64 into a string. +// +// Deprecated: use [conv.FormatUinteger] instead. +func FormatUint64(value uint64) string { return conv.FormatUinteger(value) } + +// String turn a pointer to of the string value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func String(v string) *string { return conv.Pointer(v) } + +// StringValue turn the value of the string pointer passed in or +// "" if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func StringValue(v *string) string { return conv.Value(v) } + +// StringSlice converts a slice of string values into a slice of string pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func StringSlice(src []string) []*string { return conv.PointerSlice(src) } + +// StringValueSlice converts a slice of string pointers into a slice of string values. +// +// Deprecated: use [conv.ValueSlice] instead. +func StringValueSlice(src []*string) []string { return conv.ValueSlice(src) } + +// StringMap converts a string map of string values into a string map of string pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func StringMap(src map[string]string) map[string]*string { return conv.PointerMap(src) } + +// StringValueMap converts a string map of string pointers into a string map of string values. +// +// Deprecated: use [conv.ValueMap] instead. +func StringValueMap(src map[string]*string) map[string]string { return conv.ValueMap(src) } + +// Bool turn a pointer to of the bool value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Bool(v bool) *bool { return conv.Pointer(v) } + +// BoolValue turn the value of the bool pointer passed in or false if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func BoolValue(v *bool) bool { return conv.Value(v) } + +// BoolSlice converts a slice of bool values into a slice of bool pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func BoolSlice(src []bool) []*bool { return conv.PointerSlice(src) } + +// BoolValueSlice converts a slice of bool pointers into a slice of bool values. +// +// Deprecated: use [conv.ValueSlice] instead. +func BoolValueSlice(src []*bool) []bool { return conv.ValueSlice(src) } + +// BoolMap converts a string map of bool values into a string map of bool pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func BoolMap(src map[string]bool) map[string]*bool { return conv.PointerMap(src) } + +// BoolValueMap converts a string map of bool pointers into a string map of bool values. +// +// Deprecated: use [conv.ValueMap] instead. +func BoolValueMap(src map[string]*bool) map[string]bool { return conv.ValueMap(src) } + +// Int turn a pointer to of the int value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Int(v int) *int { return conv.Pointer(v) } + +// IntValue turn the value of the int pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func IntValue(v *int) int { return conv.Value(v) } + +// IntSlice converts a slice of int values into a slice of int pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func IntSlice(src []int) []*int { return conv.PointerSlice(src) } + +// IntValueSlice converts a slice of int pointers into a slice of int values. +// +// Deprecated: use [conv.ValueSlice] instead. +func IntValueSlice(src []*int) []int { return conv.ValueSlice(src) } + +// IntMap converts a string map of int values into a string map of int pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func IntMap(src map[string]int) map[string]*int { return conv.PointerMap(src) } + +// IntValueMap converts a string map of int pointers into a string map of int values. +// +// Deprecated: use [conv.ValueMap] instead. +func IntValueMap(src map[string]*int) map[string]int { return conv.ValueMap(src) } + +// Int32 turn a pointer to of the int32 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Int32(v int32) *int32 { return conv.Pointer(v) } + +// Int32Value turn the value of the int32 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Int32Value(v *int32) int32 { return conv.Value(v) } + +// Int32Slice converts a slice of int32 values into a slice of int32 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Int32Slice(src []int32) []*int32 { return conv.PointerSlice(src) } + +// Int32ValueSlice converts a slice of int32 pointers into a slice of int32 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Int32ValueSlice(src []*int32) []int32 { return conv.ValueSlice(src) } + +// Int32Map converts a string map of int32 values into a string map of int32 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Int32Map(src map[string]int32) map[string]*int32 { return conv.PointerMap(src) } + +// Int32ValueMap converts a string map of int32 pointers into a string map of int32 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Int32ValueMap(src map[string]*int32) map[string]int32 { return conv.ValueMap(src) } + +// Int64 turn a pointer to of the int64 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Int64(v int64) *int64 { return conv.Pointer(v) } + +// Int64Value turn the value of the int64 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Int64Value(v *int64) int64 { return conv.Value(v) } + +// Int64Slice converts a slice of int64 values into a slice of int64 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Int64Slice(src []int64) []*int64 { return conv.PointerSlice(src) } + +// Int64ValueSlice converts a slice of int64 pointers into a slice of int64 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Int64ValueSlice(src []*int64) []int64 { return conv.ValueSlice(src) } + +// Int64Map converts a string map of int64 values into a string map of int64 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Int64Map(src map[string]int64) map[string]*int64 { return conv.PointerMap(src) } + +// Int64ValueMap converts a string map of int64 pointers into a string map of int64 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Int64ValueMap(src map[string]*int64) map[string]int64 { return conv.ValueMap(src) } + +// Uint16 turn a pointer to of the uint16 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Uint16(v uint16) *uint16 { return conv.Pointer(v) } + +// Uint16Value turn the value of the uint16 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Uint16Value(v *uint16) uint16 { return conv.Value(v) } + +// Uint16Slice converts a slice of uint16 values into a slice of uint16 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Uint16Slice(src []uint16) []*uint16 { return conv.PointerSlice(src) } + +// Uint16ValueSlice converts a slice of uint16 pointers into a slice of uint16 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Uint16ValueSlice(src []*uint16) []uint16 { return conv.ValueSlice(src) } + +// Uint16Map converts a string map of uint16 values into a string map of uint16 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Uint16Map(src map[string]uint16) map[string]*uint16 { return conv.PointerMap(src) } + +// Uint16ValueMap converts a string map of uint16 pointers into a string map of uint16 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { return conv.ValueMap(src) } + +// Uint turn a pointer to of the uint value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Uint(v uint) *uint { return conv.Pointer(v) } + +// UintValue turn the value of the uint pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func UintValue(v *uint) uint { return conv.Value(v) } + +// UintSlice converts a slice of uint values into a slice of uint pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func UintSlice(src []uint) []*uint { return conv.PointerSlice(src) } + +// UintValueSlice converts a slice of uint pointers into a slice of uint values. +// +// Deprecated: use [conv.ValueSlice] instead. +func UintValueSlice(src []*uint) []uint { return conv.ValueSlice(src) } + +// UintMap converts a string map of uint values into a string map of uint pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func UintMap(src map[string]uint) map[string]*uint { return conv.PointerMap(src) } + +// UintValueMap converts a string map of uint pointers into a string map of uint values. +// +// Deprecated: use [conv.ValueMap] instead. +func UintValueMap(src map[string]*uint) map[string]uint { return conv.ValueMap(src) } + +// Uint32 turn a pointer to of the uint32 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Uint32(v uint32) *uint32 { return conv.Pointer(v) } + +// Uint32Value turn the value of the uint32 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Uint32Value(v *uint32) uint32 { return conv.Value(v) } + +// Uint32Slice converts a slice of uint32 values into a slice of uint32 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Uint32Slice(src []uint32) []*uint32 { return conv.PointerSlice(src) } + +// Uint32ValueSlice converts a slice of uint32 pointers into a slice of uint32 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Uint32ValueSlice(src []*uint32) []uint32 { return conv.ValueSlice(src) } + +// Uint32Map converts a string map of uint32 values into a string map of uint32 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Uint32Map(src map[string]uint32) map[string]*uint32 { return conv.PointerMap(src) } + +// Uint32ValueMap converts a string map of uint32 pointers into a string map of uint32 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { return conv.ValueMap(src) } + +// Uint64 turn a pointer to of the uint64 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Uint64(v uint64) *uint64 { return conv.Pointer(v) } + +// Uint64Value turn the value of the uint64 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Uint64Value(v *uint64) uint64 { return conv.Value(v) } + +// Uint64Slice converts a slice of uint64 values into a slice of uint64 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Uint64Slice(src []uint64) []*uint64 { return conv.PointerSlice(src) } + +// Uint64ValueSlice converts a slice of uint64 pointers into a slice of uint64 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Uint64ValueSlice(src []*uint64) []uint64 { return conv.ValueSlice(src) } + +// Uint64Map converts a string map of uint64 values into a string map of uint64 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Uint64Map(src map[string]uint64) map[string]*uint64 { return conv.PointerMap(src) } + +// Uint64ValueMap converts a string map of uint64 pointers into a string map of uint64 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { return conv.ValueMap(src) } + +// Float32 turn a pointer to of the float32 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Float32(v float32) *float32 { return conv.Pointer(v) } + +// Float32Value turn the value of the float32 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Float32Value(v *float32) float32 { return conv.Value(v) } + +// Float32Slice converts a slice of float32 values into a slice of float32 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Float32Slice(src []float32) []*float32 { return conv.PointerSlice(src) } + +// Float32ValueSlice converts a slice of float32 pointers into a slice of float32 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Float32ValueSlice(src []*float32) []float32 { return conv.ValueSlice(src) } + +// Float32Map converts a string map of float32 values into a string map of float32 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Float32Map(src map[string]float32) map[string]*float32 { return conv.PointerMap(src) } + +// Float32ValueMap converts a string map of float32 pointers into a string map of float32 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Float32ValueMap(src map[string]*float32) map[string]float32 { return conv.ValueMap(src) } + +// Float64 turn a pointer to of the float64 value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Float64(v float64) *float64 { return conv.Pointer(v) } + +// Float64Value turn the value of the float64 pointer passed in or 0 if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func Float64Value(v *float64) float64 { return conv.Value(v) } + +// Float64Slice converts a slice of float64 values into a slice of float64 pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func Float64Slice(src []float64) []*float64 { return conv.PointerSlice(src) } + +// Float64ValueSlice converts a slice of float64 pointers into a slice of float64 values. +// +// Deprecated: use [conv.ValueSlice] instead. +func Float64ValueSlice(src []*float64) []float64 { return conv.ValueSlice(src) } + +// Float64Map converts a string map of float64 values into a string map of float64 pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func Float64Map(src map[string]float64) map[string]*float64 { return conv.PointerMap(src) } + +// Float64ValueMap converts a string map of float64 pointers into a string map of float64 values. +// +// Deprecated: use [conv.ValueMap] instead. +func Float64ValueMap(src map[string]*float64) map[string]float64 { return conv.ValueMap(src) } + +// Time turn a pointer to of the time.Time value passed in. +// +// Deprecated: use [conv.Pointer] instead. +func Time(v time.Time) *time.Time { return conv.Pointer(v) } + +// TimeValue turn the value of the time.Time pointer passed in or time.Time{} if the pointer is nil. +// +// Deprecated: use [conv.Value] instead. +func TimeValue(v *time.Time) time.Time { return conv.Value(v) } + +// TimeSlice converts a slice of time.Time values into a slice of time.Time pointers. +// +// Deprecated: use [conv.PointerSlice] instead. +func TimeSlice(src []time.Time) []*time.Time { return conv.PointerSlice(src) } + +// TimeValueSlice converts a slice of time.Time pointers into a slice of time.Time values +// +// Deprecated: use [conv.ValueSlice] instead. +func TimeValueSlice(src []*time.Time) []time.Time { return conv.ValueSlice(src) } + +// TimeMap converts a string map of time.Time values into a string map of time.Time pointers. +// +// Deprecated: use [conv.PointerMap] instead. +func TimeMap(src map[string]time.Time) map[string]*time.Time { return conv.PointerMap(src) } + +// TimeValueMap converts a string map of time.Time pointers into a string map of time.Time values. +// +// Deprecated: use [conv.ValueMap] instead. +func TimeValueMap(src map[string]*time.Time) map[string]time.Time { return conv.ValueMap(src) } diff --git a/vendor/github.com/go-openapi/swag/convert.go b/vendor/github.com/go-openapi/swag/convert.go deleted file mode 100644 index fc085aeb8ea5..000000000000 --- a/vendor/github.com/go-openapi/swag/convert.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "math" - "strconv" - "strings" -) - -// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER -const ( - maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 - minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 - epsilon float64 = 1e-9 -) - -// IsFloat64AJSONInteger allow for integers [-2^53, 2^53-1] inclusive -func IsFloat64AJSONInteger(f float64) bool { - if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { - return false - } - fa := math.Abs(f) - g := float64(uint64(f)) - ga := math.Abs(g) - - diff := math.Abs(f - g) - - // more info: https://floating-point-gui.de/errors/comparison/#look-out-for-edge-cases - switch { - case f == g: // best case - return true - case f == float64(int64(f)) || f == float64(uint64(f)): // optimistic case - return true - case f == 0 || g == 0 || diff < math.SmallestNonzeroFloat64: // very close to 0 values - return diff < (epsilon * math.SmallestNonzeroFloat64) - } - // check the relative error - return diff/math.Min(fa+ga, math.MaxFloat64) < epsilon -} - -var evaluatesAsTrue map[string]struct{} - -func init() { - evaluatesAsTrue = map[string]struct{}{ - "true": {}, - "1": {}, - "yes": {}, - "ok": {}, - "y": {}, - "on": {}, - "selected": {}, - "checked": {}, - "t": {}, - "enabled": {}, - } -} - -// ConvertBool turn a string into a boolean -func ConvertBool(str string) (bool, error) { - _, ok := evaluatesAsTrue[strings.ToLower(str)] - return ok, nil -} - -// ConvertFloat32 turn a string into a float32 -func ConvertFloat32(str string) (float32, error) { - f, err := strconv.ParseFloat(str, 32) - if err != nil { - return 0, err - } - return float32(f), nil -} - -// ConvertFloat64 turn a string into a float64 -func ConvertFloat64(str string) (float64, error) { - return strconv.ParseFloat(str, 64) -} - -// ConvertInt8 turn a string into an int8 -func ConvertInt8(str string) (int8, error) { - i, err := strconv.ParseInt(str, 10, 8) - if err != nil { - return 0, err - } - return int8(i), nil -} - -// ConvertInt16 turn a string into an int16 -func ConvertInt16(str string) (int16, error) { - i, err := strconv.ParseInt(str, 10, 16) - if err != nil { - return 0, err - } - return int16(i), nil -} - -// ConvertInt32 turn a string into an int32 -func ConvertInt32(str string) (int32, error) { - i, err := strconv.ParseInt(str, 10, 32) - if err != nil { - return 0, err - } - return int32(i), nil -} - -// ConvertInt64 turn a string into an int64 -func ConvertInt64(str string) (int64, error) { - return strconv.ParseInt(str, 10, 64) -} - -// ConvertUint8 turn a string into an uint8 -func ConvertUint8(str string) (uint8, error) { - i, err := strconv.ParseUint(str, 10, 8) - if err != nil { - return 0, err - } - return uint8(i), nil -} - -// ConvertUint16 turn a string into an uint16 -func ConvertUint16(str string) (uint16, error) { - i, err := strconv.ParseUint(str, 10, 16) - if err != nil { - return 0, err - } - return uint16(i), nil -} - -// ConvertUint32 turn a string into an uint32 -func ConvertUint32(str string) (uint32, error) { - i, err := strconv.ParseUint(str, 10, 32) - if err != nil { - return 0, err - } - return uint32(i), nil -} - -// ConvertUint64 turn a string into an uint64 -func ConvertUint64(str string) (uint64, error) { - return strconv.ParseUint(str, 10, 64) -} - -// FormatBool turns a boolean into a string -func FormatBool(value bool) string { - return strconv.FormatBool(value) -} - -// FormatFloat32 turns a float32 into a string -func FormatFloat32(value float32) string { - return strconv.FormatFloat(float64(value), 'f', -1, 32) -} - -// FormatFloat64 turns a float64 into a string -func FormatFloat64(value float64) string { - return strconv.FormatFloat(value, 'f', -1, 64) -} - -// FormatInt8 turns an int8 into a string -func FormatInt8(value int8) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt16 turns an int16 into a string -func FormatInt16(value int16) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt32 turns an int32 into a string -func FormatInt32(value int32) string { - return strconv.Itoa(int(value)) -} - -// FormatInt64 turns an int64 into a string -func FormatInt64(value int64) string { - return strconv.FormatInt(value, 10) -} - -// FormatUint8 turns an uint8 into a string -func FormatUint8(value uint8) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint16 turns an uint16 into a string -func FormatUint16(value uint16) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint32 turns an uint32 into a string -func FormatUint32(value uint32) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint64 turns an uint64 into a string -func FormatUint64(value uint64) string { - return strconv.FormatUint(value, 10) -} diff --git a/vendor/github.com/go-openapi/swag/convert_types.go b/vendor/github.com/go-openapi/swag/convert_types.go deleted file mode 100644 index c49cc473a8c2..000000000000 --- a/vendor/github.com/go-openapi/swag/convert_types.go +++ /dev/null @@ -1,730 +0,0 @@ -package swag - -import "time" - -// This file was taken from the aws go sdk - -// String returns a pointer to of the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to of the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to of the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int32 returns a pointer to of the int32 value passed in. -func Int32(v int32) *int32 { - return &v -} - -// Int32Value returns the value of the int32 pointer passed in or -// 0 if the pointer is nil. -func Int32Value(v *int32) int32 { - if v != nil { - return *v - } - return 0 -} - -// Int32Slice converts a slice of int32 values into a slice of -// int32 pointers -func Int32Slice(src []int32) []*int32 { - dst := make([]*int32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int32ValueSlice converts a slice of int32 pointers into a slice of -// int32 values -func Int32ValueSlice(src []*int32) []int32 { - dst := make([]int32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int32Map converts a string map of int32 values into a string -// map of int32 pointers -func Int32Map(src map[string]int32) map[string]*int32 { - dst := make(map[string]*int32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int32ValueMap converts a string map of int32 pointers into a string -// map of int32 values -func Int32ValueMap(src map[string]*int32) map[string]int32 { - dst := make(map[string]int32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to of the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint16 returns a pointer to of the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return &v -} - -// Uint16Value returns the value of the uint16 pointer passed in or -// 0 if the pointer is nil. -func Uint16Value(v *uint16) uint16 { - if v != nil { - return *v - } - - return 0 -} - -// Uint16Slice converts a slice of uint16 values into a slice of -// uint16 pointers -func Uint16Slice(src []uint16) []*uint16 { - dst := make([]*uint16, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - - return dst -} - -// Uint16ValueSlice converts a slice of uint16 pointers into a slice of -// uint16 values -func Uint16ValueSlice(src []*uint16) []uint16 { - dst := make([]uint16, len(src)) - - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - - return dst -} - -// Uint16Map converts a string map of uint16 values into a string -// map of uint16 pointers -func Uint16Map(src map[string]uint16) map[string]*uint16 { - dst := make(map[string]*uint16) - - for k, val := range src { - v := val - dst[k] = &v - } - - return dst -} - -// Uint16ValueMap converts a string map of uint16 pointers into a string -// map of uint16 values -func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { - dst := make(map[string]uint16) - - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - - return dst -} - -// Uint returns a pointer to of the uint value passed in. -func Uint(v uint) *uint { - return &v -} - -// UintValue returns the value of the uint pointer passed in or -// 0 if the pointer is nil. -func UintValue(v *uint) uint { - if v != nil { - return *v - } - return 0 -} - -// UintSlice converts a slice of uint values into a slice of -// uint pointers -func UintSlice(src []uint) []*uint { - dst := make([]*uint, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// UintValueSlice converts a slice of uint pointers into a slice of -// uint values -func UintValueSlice(src []*uint) []uint { - dst := make([]uint, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// UintMap converts a string map of uint values into a string -// map of uint pointers -func UintMap(src map[string]uint) map[string]*uint { - dst := make(map[string]*uint) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// UintValueMap converts a string map of uint pointers into a string -// map of uint values -func UintValueMap(src map[string]*uint) map[string]uint { - dst := make(map[string]uint) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint32 returns a pointer to of the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint32Value returns the value of the uint32 pointer passed in or -// 0 if the pointer is nil. -func Uint32Value(v *uint32) uint32 { - if v != nil { - return *v - } - return 0 -} - -// Uint32Slice converts a slice of uint32 values into a slice of -// uint32 pointers -func Uint32Slice(src []uint32) []*uint32 { - dst := make([]*uint32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint32ValueSlice converts a slice of uint32 pointers into a slice of -// uint32 values -func Uint32ValueSlice(src []*uint32) []uint32 { - dst := make([]uint32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint32Map converts a string map of uint32 values into a string -// map of uint32 pointers -func Uint32Map(src map[string]uint32) map[string]*uint32 { - dst := make(map[string]*uint32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint32ValueMap converts a string map of uint32 pointers into a string -// map of uint32 values -func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { - dst := make(map[string]uint32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint64 returns a pointer to of the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return &v -} - -// Uint64Value returns the value of the uint64 pointer passed in or -// 0 if the pointer is nil. -func Uint64Value(v *uint64) uint64 { - if v != nil { - return *v - } - return 0 -} - -// Uint64Slice converts a slice of uint64 values into a slice of -// uint64 pointers -func Uint64Slice(src []uint64) []*uint64 { - dst := make([]*uint64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint64ValueSlice converts a slice of uint64 pointers into a slice of -// uint64 values -func Uint64ValueSlice(src []*uint64) []uint64 { - dst := make([]uint64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint64Map converts a string map of uint64 values into a string -// map of uint64 pointers -func Uint64Map(src map[string]uint64) map[string]*uint64 { - dst := make(map[string]*uint64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint64ValueMap converts a string map of uint64 pointers into a string -// map of uint64 values -func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { - dst := make(map[string]uint64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float32 returns a pointer to of the float32 value passed in. -func Float32(v float32) *float32 { - return &v -} - -// Float32Value returns the value of the float32 pointer passed in or -// 0 if the pointer is nil. -func Float32Value(v *float32) float32 { - if v != nil { - return *v - } - - return 0 -} - -// Float32Slice converts a slice of float32 values into a slice of -// float32 pointers -func Float32Slice(src []float32) []*float32 { - dst := make([]*float32, len(src)) - - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - - return dst -} - -// Float32ValueSlice converts a slice of float32 pointers into a slice of -// float32 values -func Float32ValueSlice(src []*float32) []float32 { - dst := make([]float32, len(src)) - - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - - return dst -} - -// Float32Map converts a string map of float32 values into a string -// map of float32 pointers -func Float32Map(src map[string]float32) map[string]*float32 { - dst := make(map[string]*float32) - - for k, val := range src { - v := val - dst[k] = &v - } - - return dst -} - -// Float32ValueMap converts a string map of float32 pointers into a string -// map of float32 values -func Float32ValueMap(src map[string]*float32) map[string]float32 { - dst := make(map[string]float32) - - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - - return dst -} - -// Float64 returns a pointer to of the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to of the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/vendor/github.com/go-openapi/swag/doc.go b/vendor/github.com/go-openapi/swag/doc.go index 55094cb74c4d..b54b57478af6 100644 --- a/vendor/github.com/go-openapi/swag/doc.go +++ b/vendor/github.com/go-openapi/swag/doc.go @@ -1,31 +1,47 @@ -// Copyright 2015 go-swagger maintainers +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package swag contains a bunch of helper functions for go-openapi and go-swagger projects. // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at +// You may also use it standalone for your projects. // -// http://www.apache.org/licenses/LICENSE-2.0 +// NOTE: all features that used to be exposed as package-level members (constants, variables, +// functions and types) are now deprecated and are superseded by equivalent features in +// more specialized sub-packages. +// Moving forward, no additional feature will be added to the [swag] API directly at the root package level, +// which remains there for backward-compatibility purposes. // -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag contains a bunch of helper functions for go-openapi and go-swagger projects. - -You may also use it standalone for your projects. - - - convert between value and pointers for builtin types - - convert from string to builtin types (wraps strconv) - - fast json concatenation - - search in path - - load from file or http - - name mangling - -This repo has only few dependencies outside of the standard library: - - - YAML utilities depend on gopkg.in/yaml.v2 -*/ +// Child modules will continue to evolve or some new ones may be added in the future. +// +// # Modules +// +// - [cmdutils] utilities to work with CLIs +// +// - [conv] type conversion utilities +// +// - [fileutils] file utilities +// +// - [jsonname] JSON utilities +// +// - [jsonutils] JSON utilities +// +// - [loading] file loading +// +// - [mangling] safe name generation +// +// - [netutils] networking utilities +// +// - [stringutils] `string` utilities +// +// - [typeutils] `go` types utilities +// +// - [yamlutils] YAML utilities +// +// # Dependencies +// +// This repo has a few dependencies outside of the standard library: +// +// - YAML utilities depend on [go.yaml.in/yaml/v3] package swag + +//go:generate mockery diff --git a/vendor/github.com/go-openapi/swag/errors.go b/vendor/github.com/go-openapi/swag/errors.go deleted file mode 100644 index 6c67fbf92e35..000000000000 --- a/vendor/github.com/go-openapi/swag/errors.go +++ /dev/null @@ -1,15 +0,0 @@ -package swag - -type swagError string - -const ( - // ErrYAML is an error raised by YAML utilities - ErrYAML swagError = "yaml error" - - // ErrLoader is an error raised by the file loader utility - ErrLoader swagError = "loader error" -) - -func (e swagError) Error() string { - return string(e) -} diff --git a/vendor/github.com/go-openapi/swag/file.go b/vendor/github.com/go-openapi/swag/file.go deleted file mode 100644 index 16accc55f82e..000000000000 --- a/vendor/github.com/go-openapi/swag/file.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import "mime/multipart" - -// File represents an uploaded file. -type File struct { - Data multipart.File - Header *multipart.FileHeader -} - -// Read bytes from the file -func (f *File) Read(p []byte) (n int, err error) { - return f.Data.Read(p) -} - -// Close the file -func (f *File) Close() error { - return f.Data.Close() -} diff --git a/vendor/github.com/go-openapi/swag/fileutils/LICENSE b/vendor/github.com/go-openapi/swag/fileutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/fileutils/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/go-openapi/swag/fileutils/doc.go b/vendor/github.com/go-openapi/swag/fileutils/doc.go new file mode 100644 index 000000000000..859a200d8413 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/fileutils/doc.go @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package fileutils exposes utilities to deal with files and paths. +// +// Currently, there is: +// - [File] to represent an abstraction of an uploaded file. +// For instance, this is used by [github.com/go-openapi/runtime.File]. +// - path search utilities (e.g. finding packages in the GO search path) +package fileutils diff --git a/vendor/github.com/go-openapi/swag/fileutils/file.go b/vendor/github.com/go-openapi/swag/fileutils/file.go new file mode 100644 index 000000000000..5ad4cfaeafa4 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/fileutils/file.go @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package fileutils + +import "mime/multipart" + +// File represents an uploaded file. +type File struct { + Data multipart.File + Header *multipart.FileHeader +} + +// Read bytes from the file +func (f *File) Read(p []byte) (n int, err error) { + return f.Data.Read(p) +} + +// Close the file +func (f *File) Close() error { + return f.Data.Close() +} diff --git a/vendor/github.com/go-openapi/swag/path.go b/vendor/github.com/go-openapi/swag/fileutils/path.go similarity index 58% rename from vendor/github.com/go-openapi/swag/path.go rename to vendor/github.com/go-openapi/swag/fileutils/path.go index 941bd0176b05..dd09f690bf81 100644 --- a/vendor/github.com/go-openapi/swag/path.go +++ b/vendor/github.com/go-openapi/swag/fileutils/path.go @@ -1,18 +1,7 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 -package swag +package fileutils import ( "os" @@ -21,10 +10,8 @@ import ( "strings" ) -const ( - // GOPATHKey represents the env key for gopath - GOPATHKey = "GOPATH" -) +// GOPATHKey represents the env key for gopath +const GOPATHKey = "GOPATH" // FindInSearchPath finds a package in a provided lists of paths func FindInSearchPath(searchPath, pkg string) string { @@ -40,11 +27,17 @@ func FindInSearchPath(searchPath, pkg string) string { } // FindInGoSearchPath finds a package in the $GOPATH:$GOROOT +// +// Deprecated: this function is no longer relevant with modern go. +// It uses [runtime.GOROOT] under the hood, which is deprecated as of go1.24. func FindInGoSearchPath(pkg string) string { return FindInSearchPath(FullGoSearchPath(), pkg) } // FullGoSearchPath gets the search paths for finding packages +// +// Deprecated: this function is no longer relevant with modern go. +// It uses [runtime.GOROOT] under the hood, which is deprecated as of go1.24. func FullGoSearchPath() string { allPaths := os.Getenv(GOPATHKey) if allPaths == "" { diff --git a/vendor/github.com/go-openapi/swag/fileutils_iface.go b/vendor/github.com/go-openapi/swag/fileutils_iface.go new file mode 100644 index 000000000000..f3e79a0e4bce --- /dev/null +++ b/vendor/github.com/go-openapi/swag/fileutils_iface.go @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/fileutils" + +// GOPATHKey represents the env key for gopath +// +// Deprecated: use [fileutils.GOPATHKey] instead. +const GOPATHKey = fileutils.GOPATHKey + +// File represents an uploaded file. +// +// Deprecated: use [fileutils.File] instead. +type File = fileutils.File + +// FindInSearchPath finds a package in a provided lists of paths. +// +// Deprecated: use [fileutils.FindInSearchPath] instead. +func FindInSearchPath(searchPath, pkg string) string { + return fileutils.FindInSearchPath(searchPath, pkg) +} + +// FindInGoSearchPath finds a package in the $GOPATH:$GOROOT +// +// Deprecated: use [fileutils.FindInGoSearchPath] instead. +func FindInGoSearchPath(pkg string) string { return fileutils.FindInGoSearchPath(pkg) } + +// FullGoSearchPath gets the search paths for finding packages +// +// Deprecated: use [fileutils.FullGoSearchPath] instead. +func FullGoSearchPath() string { return fileutils.FullGoSearchPath() } diff --git a/vendor/github.com/go-openapi/swag/go.work b/vendor/github.com/go-openapi/swag/go.work new file mode 100644 index 000000000000..1e537f0749b0 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/go.work @@ -0,0 +1,20 @@ +use ( + . + ./cmdutils + ./conv + ./fileutils + ./jsonname + ./jsonutils + ./jsonutils/adapters/easyjson + ./jsonutils/adapters/testintegration + ./jsonutils/adapters/testintegration/benchmarks + ./jsonutils/fixtures_test + ./loading + ./mangling + ./netutils + ./stringutils + ./typeutils + ./yamlutils +) + +go 1.24.0 diff --git a/vendor/github.com/go-openapi/swag/go.work.sum b/vendor/github.com/go-openapi/swag/go.work.sum new file mode 100644 index 000000000000..c1308cafa672 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/go.work.sum @@ -0,0 +1,7 @@ +github.com/go-openapi/testify/v2 v2.0.1/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= +golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= +golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= +golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= diff --git a/vendor/github.com/go-openapi/swag/initialism_index.go b/vendor/github.com/go-openapi/swag/initialism_index.go deleted file mode 100644 index 20a359bb60a2..000000000000 --- a/vendor/github.com/go-openapi/swag/initialism_index.go +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "sort" - "strings" - "sync" -) - -var ( - // commonInitialisms are common acronyms that are kept as whole uppercased words. - commonInitialisms *indexOfInitialisms - - // initialisms is a slice of sorted initialisms - initialisms []string - - // a copy of initialisms pre-baked as []rune - initialismsRunes [][]rune - initialismsUpperCased [][]rune - - isInitialism func(string) bool - - maxAllocMatches int -) - -func init() { - // Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769 - configuredInitialisms := map[string]bool{ - "ACL": true, - "API": true, - "ASCII": true, - "CPU": true, - "CSS": true, - "DNS": true, - "EOF": true, - "GUID": true, - "HTML": true, - "HTTPS": true, - "HTTP": true, - "ID": true, - "IP": true, - "IPv4": true, - "IPv6": true, - "JSON": true, - "LHS": true, - "OAI": true, - "QPS": true, - "RAM": true, - "RHS": true, - "RPC": true, - "SLA": true, - "SMTP": true, - "SQL": true, - "SSH": true, - "TCP": true, - "TLS": true, - "TTL": true, - "UDP": true, - "UI": true, - "UID": true, - "UUID": true, - "URI": true, - "URL": true, - "UTF8": true, - "VM": true, - "XML": true, - "XMPP": true, - "XSRF": true, - "XSS": true, - } - - // a thread-safe index of initialisms - commonInitialisms = newIndexOfInitialisms().load(configuredInitialisms) - initialisms = commonInitialisms.sorted() - initialismsRunes = asRunes(initialisms) - initialismsUpperCased = asUpperCased(initialisms) - maxAllocMatches = maxAllocHeuristic(initialismsRunes) - - // a test function - isInitialism = commonInitialisms.isInitialism -} - -func asRunes(in []string) [][]rune { - out := make([][]rune, len(in)) - for i, initialism := range in { - out[i] = []rune(initialism) - } - - return out -} - -func asUpperCased(in []string) [][]rune { - out := make([][]rune, len(in)) - - for i, initialism := range in { - out[i] = []rune(upper(trim(initialism))) - } - - return out -} - -func maxAllocHeuristic(in [][]rune) int { - heuristic := make(map[rune]int) - for _, initialism := range in { - heuristic[initialism[0]]++ - } - - var maxAlloc int - for _, val := range heuristic { - if val > maxAlloc { - maxAlloc = val - } - } - - return maxAlloc -} - -// AddInitialisms add additional initialisms -func AddInitialisms(words ...string) { - for _, word := range words { - // commonInitialisms[upper(word)] = true - commonInitialisms.add(upper(word)) - } - // sort again - initialisms = commonInitialisms.sorted() - initialismsRunes = asRunes(initialisms) - initialismsUpperCased = asUpperCased(initialisms) -} - -// indexOfInitialisms is a thread-safe implementation of the sorted index of initialisms. -// Since go1.9, this may be implemented with sync.Map. -type indexOfInitialisms struct { - sortMutex *sync.Mutex - index *sync.Map -} - -func newIndexOfInitialisms() *indexOfInitialisms { - return &indexOfInitialisms{ - sortMutex: new(sync.Mutex), - index: new(sync.Map), - } -} - -func (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms { - m.sortMutex.Lock() - defer m.sortMutex.Unlock() - for k, v := range initial { - m.index.Store(k, v) - } - return m -} - -func (m *indexOfInitialisms) isInitialism(key string) bool { - _, ok := m.index.Load(key) - return ok -} - -func (m *indexOfInitialisms) add(key string) *indexOfInitialisms { - m.index.Store(key, true) - return m -} - -func (m *indexOfInitialisms) sorted() (result []string) { - m.sortMutex.Lock() - defer m.sortMutex.Unlock() - m.index.Range(func(key, _ interface{}) bool { - k := key.(string) - result = append(result, k) - return true - }) - sort.Sort(sort.Reverse(byInitialism(result))) - return -} - -type byInitialism []string - -func (s byInitialism) Len() int { - return len(s) -} -func (s byInitialism) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s byInitialism) Less(i, j int) bool { - if len(s[i]) != len(s[j]) { - return len(s[i]) < len(s[j]) - } - - return strings.Compare(s[i], s[j]) > 0 -} diff --git a/vendor/github.com/go-openapi/swag/json.go b/vendor/github.com/go-openapi/swag/json.go deleted file mode 100644 index c7caa9908fea..000000000000 --- a/vendor/github.com/go-openapi/swag/json.go +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "bytes" - "encoding/json" - "log" - "reflect" - "strings" - "sync" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" -) - -// nullJSON represents a JSON object with null type -var nullJSON = []byte("null") - -// DefaultJSONNameProvider the default cache for types -var DefaultJSONNameProvider = NewNameProvider() - -const comma = byte(',') - -var closers map[byte]byte - -func init() { - closers = map[byte]byte{ - '{': '}', - '[': ']', - } -} - -type ejMarshaler interface { - MarshalEasyJSON(w *jwriter.Writer) -} - -type ejUnmarshaler interface { - UnmarshalEasyJSON(w *jlexer.Lexer) -} - -// WriteJSON writes json data, prefers finding an appropriate interface to short-circuit the marshaler -// so it takes the fastest option available. -func WriteJSON(data interface{}) ([]byte, error) { - if d, ok := data.(ejMarshaler); ok { - jw := new(jwriter.Writer) - d.MarshalEasyJSON(jw) - return jw.BuildBytes() - } - if d, ok := data.(json.Marshaler); ok { - return d.MarshalJSON() - } - return json.Marshal(data) -} - -// ReadJSON reads json data, prefers finding an appropriate interface to short-circuit the unmarshaler -// so it takes the fastest option available -func ReadJSON(data []byte, value interface{}) error { - trimmedData := bytes.Trim(data, "\x00") - if d, ok := value.(ejUnmarshaler); ok { - jl := &jlexer.Lexer{Data: trimmedData} - d.UnmarshalEasyJSON(jl) - return jl.Error() - } - if d, ok := value.(json.Unmarshaler); ok { - return d.UnmarshalJSON(trimmedData) - } - return json.Unmarshal(trimmedData, value) -} - -// DynamicJSONToStruct converts an untyped json structure into a struct -func DynamicJSONToStruct(data interface{}, target interface{}) error { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := WriteJSON(data) - if err != nil { - return err - } - return ReadJSON(b, target) -} - -// ConcatJSON concatenates multiple json objects efficiently -func ConcatJSON(blobs ...[]byte) []byte { - if len(blobs) == 0 { - return nil - } - - last := len(blobs) - 1 - for blobs[last] == nil || bytes.Equal(blobs[last], nullJSON) { - // strips trailing null objects - last-- - if last < 0 { - // there was nothing but "null"s or nil... - return nil - } - } - if last == 0 { - return blobs[0] - } - - var opening, closing byte - var idx, a int - buf := bytes.NewBuffer(nil) - - for i, b := range blobs[:last+1] { - if b == nil || bytes.Equal(b, nullJSON) { - // a null object is in the list: skip it - continue - } - if len(b) > 0 && opening == 0 { // is this an array or an object? - opening, closing = b[0], closers[b[0]] - } - - if opening != '{' && opening != '[' { - continue // don't know how to concatenate non container objects - } - - const minLengthIfNotEmpty = 3 - if len(b) < minLengthIfNotEmpty { // yep empty but also the last one, so closing this thing - if i == last && a > 0 { - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - continue - } - - idx = 0 - if a > 0 { // we need to join with a comma for everything beyond the first non-empty item - if err := buf.WriteByte(comma); err != nil { - log.Println(err) - } - idx = 1 // this is not the first or the last so we want to drop the leading bracket - } - - if i != last { // not the last one, strip brackets - if _, err := buf.Write(b[idx : len(b)-1]); err != nil { - log.Println(err) - } - } else { // last one, strip only the leading bracket - if _, err := buf.Write(b[idx:]); err != nil { - log.Println(err) - } - } - a++ - } - // somehow it ended up being empty, so provide a default value - if buf.Len() == 0 { - if err := buf.WriteByte(opening); err != nil { - log.Println(err) - } - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - return buf.Bytes() -} - -// ToDynamicJSON turns an object into a properly JSON typed structure -func ToDynamicJSON(data interface{}) interface{} { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - var res interface{} - if err := json.Unmarshal(b, &res); err != nil { - log.Println(err) - } - return res -} - -// FromDynamicJSON turns an object into a properly JSON typed structure -func FromDynamicJSON(data, target interface{}) error { - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - return json.Unmarshal(b, target) -} - -// NameProvider represents an object capable of translating from go property names -// to json property names -// This type is thread-safe. -type NameProvider struct { - lock *sync.Mutex - index map[reflect.Type]nameIndex -} - -type nameIndex struct { - jsonNames map[string]string - goNames map[string]string -} - -// NewNameProvider creates a new name provider -func NewNameProvider() *NameProvider { - return &NameProvider{ - lock: &sync.Mutex{}, - index: make(map[reflect.Type]nameIndex), - } -} - -func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { - for i := 0; i < tpe.NumField(); i++ { - targetDes := tpe.Field(i) - - if targetDes.PkgPath != "" { // unexported - continue - } - - if targetDes.Anonymous { // walk embedded structures tree down first - buildnameIndex(targetDes.Type, idx, reverseIdx) - continue - } - - if tag := targetDes.Tag.Get("json"); tag != "" { - - parts := strings.Split(tag, ",") - if len(parts) == 0 { - continue - } - - nm := parts[0] - if nm == "-" { - continue - } - if nm == "" { // empty string means we want to use the Go name - nm = targetDes.Name - } - - idx[nm] = targetDes.Name - reverseIdx[targetDes.Name] = nm - } - } -} - -func newNameIndex(tpe reflect.Type) nameIndex { - var idx = make(map[string]string, tpe.NumField()) - var reverseIdx = make(map[string]string, tpe.NumField()) - - buildnameIndex(tpe, idx, reverseIdx) - return nameIndex{jsonNames: idx, goNames: reverseIdx} -} - -// GetJSONNames gets all the json property names for a type -func (n *NameProvider) GetJSONNames(subject interface{}) []string { - n.lock.Lock() - defer n.lock.Unlock() - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - - res := make([]string, 0, len(names.jsonNames)) - for k := range names.jsonNames { - res = append(res, k) - } - return res -} - -// GetJSONName gets the json name for a go property name -func (n *NameProvider) GetJSONName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetJSONNameForType(tpe, name) -} - -// GetJSONNameForType gets the json name for a go property name on a given type -func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.goNames[name] - return nme, ok -} - -func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { - names := newNameIndex(tpe) - n.index[tpe] = names - return names -} - -// GetGoName gets the go name for a json property name -func (n *NameProvider) GetGoName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetGoNameForType(tpe, name) -} - -// GetGoNameForType gets the go name for a given type for a json property name -func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.jsonNames[name] - return nme, ok -} diff --git a/vendor/github.com/go-openapi/swag/jsonname/LICENSE b/vendor/github.com/go-openapi/swag/jsonname/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonname/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/go-openapi/swag/jsonname/doc.go b/vendor/github.com/go-openapi/swag/jsonname/doc.go new file mode 100644 index 000000000000..79232eaca476 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonname/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package jsonname is a provider of json property names from go properties. +package jsonname diff --git a/vendor/github.com/go-openapi/swag/jsonname/name_provider.go b/vendor/github.com/go-openapi/swag/jsonname/name_provider.go new file mode 100644 index 000000000000..8eaf1bece8d6 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonname/name_provider.go @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonname + +import ( + "reflect" + "strings" + "sync" +) + +// DefaultJSONNameProvider is the default cache for types. +var DefaultJSONNameProvider = NewNameProvider() + +// NameProvider represents an object capable of translating from go property names +// to json property names. +// +// This type is thread-safe. +// +// See [github.com/go-openapi/jsonpointer.Pointer] for an example. +type NameProvider struct { + lock *sync.Mutex + index map[reflect.Type]nameIndex +} + +type nameIndex struct { + jsonNames map[string]string + goNames map[string]string +} + +// NewNameProvider creates a new name provider +func NewNameProvider() *NameProvider { + return &NameProvider{ + lock: &sync.Mutex{}, + index: make(map[reflect.Type]nameIndex), + } +} + +func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { + for i := 0; i < tpe.NumField(); i++ { + targetDes := tpe.Field(i) + + if targetDes.PkgPath != "" { // unexported + continue + } + + if targetDes.Anonymous { // walk embedded structures tree down first + buildnameIndex(targetDes.Type, idx, reverseIdx) + continue + } + + if tag := targetDes.Tag.Get("json"); tag != "" { + + parts := strings.Split(tag, ",") + if len(parts) == 0 { + continue + } + + nm := parts[0] + if nm == "-" { + continue + } + if nm == "" { // empty string means we want to use the Go name + nm = targetDes.Name + } + + idx[nm] = targetDes.Name + reverseIdx[targetDes.Name] = nm + } + } +} + +func newNameIndex(tpe reflect.Type) nameIndex { + var idx = make(map[string]string, tpe.NumField()) + var reverseIdx = make(map[string]string, tpe.NumField()) + + buildnameIndex(tpe, idx, reverseIdx) + return nameIndex{jsonNames: idx, goNames: reverseIdx} +} + +// GetJSONNames gets all the json property names for a type +func (n *NameProvider) GetJSONNames(subject any) []string { + n.lock.Lock() + defer n.lock.Unlock() + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + + res := make([]string, 0, len(names.jsonNames)) + for k := range names.jsonNames { + res = append(res, k) + } + return res +} + +// GetJSONName gets the json name for a go property name +func (n *NameProvider) GetJSONName(subject any, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetJSONNameForType(tpe, name) +} + +// GetJSONNameForType gets the json name for a go property name on a given type +func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.goNames[name] + return nme, ok +} + +// GetGoName gets the go name for a json property name +func (n *NameProvider) GetGoName(subject any, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetGoNameForType(tpe, name) +} + +// GetGoNameForType gets the go name for a given type for a json property name +func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.jsonNames[name] + return nme, ok +} + +func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { + names := newNameIndex(tpe) + n.index[tpe] = names + return names +} diff --git a/vendor/github.com/go-openapi/swag/jsonname_iface.go b/vendor/github.com/go-openapi/swag/jsonname_iface.go new file mode 100644 index 000000000000..303a007f6f4c --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonname_iface.go @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "github.com/go-openapi/swag/jsonname" +) + +// DefaultJSONNameProvider is the default cache for types +// +// Deprecated: use [jsonname.DefaultJSONNameProvider] instead. +var DefaultJSONNameProvider = jsonname.DefaultJSONNameProvider + +// NameProvider represents an object capable of translating from go property names +// to json property names. +// +// Deprecated: use [jsonname.NameProvider] instead. +type NameProvider = jsonname.NameProvider + +// NewNameProvider creates a new name provider +// +// Deprecated: use [jsonname.NewNameProvider] instead. +func NewNameProvider() *NameProvider { return jsonname.NewNameProvider() } diff --git a/vendor/github.com/go-openapi/swag/jsonutils/LICENSE b/vendor/github.com/go-openapi/swag/jsonutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/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/go-openapi/swag/jsonutils/README.md b/vendor/github.com/go-openapi/swag/jsonutils/README.md new file mode 100644 index 000000000000..d745cdb466e2 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/README.md @@ -0,0 +1,108 @@ + # jsonutils + +`jsonutils` exposes a few tools to work with JSON: + +- a fast, simple `Concat` to concatenate (not merge) JSON objects and arrays +- `FromDynamicJSON` to convert a data structure into a "dynamic JSON" data structure +- `ReadJSON` and `WriteJSON` behave like `json.Unmarshal` and `json.Marshal`, + with the ability to use another underlying serialization library through an `Adapter` + configured at runtime +- a `JSONMapSlice` structure that may be used to store JSON objects with the order of keys maintained + +## Dynamic JSON + +We call "dynamic JSON" the go data structure that results from unmarshaling JSON like this: + +```go + var value any + jsonBytes := `{"a": 1, ... }` + _ = json.Unmarshal(jsonBytes, &value) +``` + +In this configuration, the standard library mappings are as follows: + +| JSON | go | +|-----------|------------------| +| `number` | `float64` | +| `string` | `string` | +| `boolean` | `bool` | +| `null` | `nil` | +| `object` | `map[string]any` | +| `array` | `[]any` | + +## Map slices + +When using `JSONMapSlice`, the ordering of keys is ensured by replacing +mappings to `map[string]any` by a `JSONMapSlice` which is an (ordered) +slice of `JSONMapItem`s. + +Notice that a similar feature is available for YAML (see [`yamlutils`](../yamlutils)), +with a `YAMLMapSlice` type based on the `JSONMapSlice`. + +`JSONMapSlice` is similar to an ordered map, but the keys are not retrieved +in constant time. + +Another difference with the the above standard mappings is that numbers don't always map +to a `float64`: if the value is a JSON integer, it unmarshals to `int64`. + +See also [some examples](https://pkg.go.dev/github.com/go-openapi/swag/jsonutils#pkg-examples) + +## Adapters + +`ReadJSON`, `WriteJSON` and `FromDynamicJSON` (which is a combination of the latter two) +are wrappers on top of `json.Unmarshal` and `json.Marshal`. + +By default, the adapter merely wraps the standard library. + +The adapter may be used to register other JSON serialization libraries, +possibly several ones at the same time. + +If the value passed is identified as an "ordered map" (i.e. implements `ifaces.Ordered` +or `ifaces.SetOrdered`, the adapter favors the "ordered" JSON behavior and tries to +find a registered implementation that support ordered keys in objects. + +Our standard library implementation supports this. + +As of `v0.25.0`, we support through such an adapter the popular `mailru/easyjson` +library, which kicks in when the passed values support the `easyjson.Unmarshaler` +or `easyjson.Marshaler` interfaces. + +In the future, we plan to add more similar libraries that compete on the go JSON +serializers scene. + +## Registering an adapter + +In package `github.com/go-openapi/swag/easyjson/adapters`, several adapters are available. + +Each adapter is an independent go module. Hence you'll pick its dependencies only if you import it. + +At this moment we provide: +* `stdlib`: JSON adapter based on the standard library +* `easyjson`: JSON adapter based on the `github.com/mailru/easyjson` + +The adapters provide the basic `Marshal` and `Unmarshal` capabilities, plus an implementation +of the `MapSlice` pattern. + +You may also build your own adapter based on your specific use-case. An adapter is not required to implement +all capabilities. + +Every adapter comes with a `Register` function, possibly with some options, to register the adapter +to a global registry. + +For example, to enable `easyjson` to be used in `ReadJSON` and `WriteJSON`, you would write something like: + +```go + import ( + "github.com/go-openapi/swag/jsonutils/adapters" + easyjson "github.com/go-openapi/swag/jsonutils/adapters/easyjson/json" + ) + + func init() { + easyjson.Register(adapters.Registry) + } +``` + +You may register several adapters. In this case, capability matching is evaluated from the last registered +adapters (LIFO). + +## [Benchmarks](./adapters/testintegration/benchmarks/README.md) diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go new file mode 100644 index 000000000000..76d3898fca5e --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go @@ -0,0 +1,8 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package adapters exposes a registry of adapters to multiple +// JSON serialization libraries. +// +// All interfaces are defined in package [ifaces.Adapter]. +package adapters diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go new file mode 100644 index 000000000000..1fd43a1fad51 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package ifaces exposes all interfaces to work with adapters. +package ifaces diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go new file mode 100644 index 000000000000..7805e5e5e398 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package ifaces + +import ( + _ "encoding/json" // for documentation purpose + "iter" +) + +// Ordered knows how to iterate over the (key,value) pairs of a JSON object. +type Ordered interface { + OrderedItems() iter.Seq2[string, any] +} + +// SetOrdered knows how to append or update the keys of a JSON object, +// given an iterator over (key,value) pairs. +// +// If the provided iterator is nil then the receiver should be set to nil. +type SetOrdered interface { + SetOrderedItems(iter.Seq2[string, any]) +} + +// OrderedMap represent a JSON object (i.e. like a map[string,any]), +// and knows how to serialize and deserialize JSON with the order of keys maintained. +type OrderedMap interface { + Ordered + SetOrdered + + OrderedMarshalJSON() ([]byte, error) + OrderedUnmarshalJSON([]byte) error +} + +// MarshalAdapter behaves likes the standard library [json.Marshal]. +type MarshalAdapter interface { + Poolable + + Marshal(any) ([]byte, error) +} + +// OrderedMarshalAdapter behaves likes the standard library [json.Marshal], preserving the order of keys in objects. +type OrderedMarshalAdapter interface { + Poolable + + OrderedMarshal(Ordered) ([]byte, error) +} + +// UnmarshalAdapter behaves likes the standard library [json.Unmarshal]. +type UnmarshalAdapter interface { + Poolable + + Unmarshal([]byte, any) error +} + +// OrderedUnmarshalAdapter behaves likes the standard library [json.Unmarshal], preserving the order of keys in objects. +type OrderedUnmarshalAdapter interface { + Poolable + + OrderedUnmarshal([]byte, SetOrdered) error +} + +// Adapter exposes an interface like the standard [json] library. +type Adapter interface { + MarshalAdapter + UnmarshalAdapter + + OrderedAdapter +} + +// OrderedAdapter exposes interfaces to process JSON and keep the order of object keys. +type OrderedAdapter interface { + OrderedMarshalAdapter + OrderedUnmarshalAdapter + NewOrderedMap(capacity int) OrderedMap +} + +type Poolable interface { + // Self-redeem: for [Adapter] s that are allocated from a pool. + // The [Adapter] must not be used after calling [Redeem]. + Redeem() + + // Reset the state of the [Adapter], if any. + Reset() +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go new file mode 100644 index 000000000000..2d6c69f4e602 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package ifaces + +import ( + "strings" +) + +// Capability indicates what a JSON adapter is capable of. +type Capability uint8 + +const ( + CapabilityMarshalJSON Capability = 1 << iota + CapabilityUnmarshalJSON + CapabilityOrderedMarshalJSON + CapabilityOrderedUnmarshalJSON + CapabilityOrderedMap +) + +func (c Capability) String() string { + switch c { + case CapabilityMarshalJSON: + return "MarshalJSON" + case CapabilityUnmarshalJSON: + return "UnmarshalJSON" + case CapabilityOrderedMarshalJSON: + return "OrderedMarshalJSON" + case CapabilityOrderedUnmarshalJSON: + return "OrderedUnmarshalJSON" + case CapabilityOrderedMap: + return "OrderedMap" + default: + return "" + } +} + +// Capabilities holds several unitary capability flags +type Capabilities uint8 + +// Has some capability flag enabled. +func (c Capabilities) Has(capability Capability) bool { + return Capability(c)&capability > 0 +} + +func (c Capabilities) String() string { + var w strings.Builder + + first := true + for _, capability := range []Capability{ + CapabilityMarshalJSON, + CapabilityUnmarshalJSON, + CapabilityOrderedMarshalJSON, + CapabilityOrderedUnmarshalJSON, + CapabilityOrderedMap, + } { + if c.Has(capability) { + if !first { + w.WriteByte('|') + } else { + first = false + } + w.WriteString(capability.String()) + } + } + + return w.String() +} + +const ( + AllCapabilities Capabilities = Capabilities(uint8(CapabilityMarshalJSON) | + uint8(CapabilityUnmarshalJSON) | + uint8(CapabilityOrderedMarshalJSON) | + uint8(CapabilityOrderedUnmarshalJSON) | + uint8(CapabilityOrderedMap)) + + AllUnorderedCapabilities Capabilities = Capabilities(uint8(CapabilityMarshalJSON) | uint8(CapabilityUnmarshalJSON)) +) + +// RegistryEntry describes how any given adapter registers its capabilities to the [Registrar]. +type RegistryEntry struct { + Who string + What Capabilities + Constructor func() Adapter + Support func(what Capability, value any) bool +} + +// Registrar is a type that knows how to keep registration calls from adapters. +type Registrar interface { + RegisterFor(RegistryEntry) +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go new file mode 100644 index 000000000000..3062acaff261 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package adapters + +import ( + "fmt" + "reflect" + "slices" + "sync" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" + stdlib "github.com/go-openapi/swag/jsonutils/adapters/stdlib/json" +) + +// Registry holds the global registry for registered adapters. +var Registry = NewRegistrar() + +var ( + defaultRegistered = stdlib.Register + + _ ifaces.Registrar = &Registrar{} +) + +type registryError string + +func (e registryError) Error() string { + return string(e) +} + +// ErrRegistry indicates an error returned by the [Registrar]. +var ErrRegistry registryError = "JSON adapters registry error" + +type registry []*ifaces.RegistryEntry + +// Registrar holds registered [ifaces.Adapters] for different serialization capabilities. +// +// Internally, it maintains a cache for data types that favor a given adapter. +type Registrar struct { + marshalerRegistry registry + unmarshalerRegistry registry + orderedMarshalerRegistry registry + orderedUnmarshalerRegistry registry + orderedMapRegistry registry + + gmx sync.RWMutex + + // cache indexed by value type, so we don't have to lookup + marshalerCache map[reflect.Type]*ifaces.RegistryEntry + unmarshalerCache map[reflect.Type]*ifaces.RegistryEntry + orderedMarshalerCache map[reflect.Type]*ifaces.RegistryEntry + orderedUnmarshalerCache map[reflect.Type]*ifaces.RegistryEntry + orderedMapCache map[reflect.Type]*ifaces.RegistryEntry +} + +func NewRegistrar() *Registrar { + r := &Registrar{} + + r.marshalerRegistry = make(registry, 0, 1) + r.unmarshalerRegistry = make(registry, 0, 1) + r.orderedMarshalerRegistry = make(registry, 0, 1) + r.orderedUnmarshalerRegistry = make(registry, 0, 1) + r.orderedMapRegistry = make(registry, 0, 1) + + r.marshalerCache = make(map[reflect.Type]*ifaces.RegistryEntry) + r.unmarshalerCache = make(map[reflect.Type]*ifaces.RegistryEntry) + r.orderedMarshalerCache = make(map[reflect.Type]*ifaces.RegistryEntry) + r.orderedUnmarshalerCache = make(map[reflect.Type]*ifaces.RegistryEntry) + r.orderedMapCache = make(map[reflect.Type]*ifaces.RegistryEntry) + + defaultRegistered(r) + + return r +} + +// ClearCache resets the internal type cache. +func (r *Registrar) ClearCache() { + r.gmx.Lock() + r.clearCache() + r.gmx.Unlock() +} + +// Reset the [Registrar] to its defaults. +func (r *Registrar) Reset() { + r.gmx.Lock() + r.clearCache() + r.marshalerRegistry = r.marshalerRegistry[:0] + r.unmarshalerRegistry = r.unmarshalerRegistry[:0] + r.orderedMarshalerRegistry = r.orderedMarshalerRegistry[:0] + r.orderedUnmarshalerRegistry = r.orderedUnmarshalerRegistry[:0] + r.orderedMapRegistry = r.orderedMapRegistry[:0] + r.gmx.Unlock() + + defaultRegistered(r) +} + +// RegisterFor registers an adapter for some JSON capabilities. +func (r *Registrar) RegisterFor(entry ifaces.RegistryEntry) { + r.gmx.Lock() + if entry.What.Has(ifaces.CapabilityMarshalJSON) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityMarshalJSON) + r.marshalerRegistry = slices.Insert(r.marshalerRegistry, 0, &e) + } + if entry.What.Has(ifaces.CapabilityUnmarshalJSON) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityUnmarshalJSON) + r.unmarshalerRegistry = slices.Insert(r.unmarshalerRegistry, 0, &e) + } + if entry.What.Has(ifaces.CapabilityOrderedMarshalJSON) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityOrderedMarshalJSON) + r.orderedMarshalerRegistry = slices.Insert(r.orderedMarshalerRegistry, 0, &e) + } + if entry.What.Has(ifaces.CapabilityOrderedUnmarshalJSON) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityOrderedUnmarshalJSON) + r.orderedUnmarshalerRegistry = slices.Insert(r.orderedUnmarshalerRegistry, 0, &e) + } + if entry.What.Has(ifaces.CapabilityOrderedMap) { + e := entry + e.What &= ifaces.Capabilities(ifaces.CapabilityOrderedMap) + r.orderedMapRegistry = slices.Insert(r.orderedMapRegistry, 0, &e) + } + r.gmx.Unlock() +} + +// AdapterFor returns an [ifaces.Adapter] that supports this capability for this type of value. +// +// The [ifaces.Adapter] may be redeemed to its pool using its Redeem() method, for adapters that support global +// pooling. When this is not the case, the redeem function is just a no-operation. +func (r *Registrar) AdapterFor(capability ifaces.Capability, value any) ifaces.Adapter { + entry := r.findFirstFor(capability, value) + if entry == nil { + return nil + } + + return entry.Constructor() +} + +func (r *Registrar) clearCache() { + clear(r.marshalerCache) + clear(r.unmarshalerCache) + clear(r.orderedMarshalerCache) + clear(r.orderedUnmarshalerCache) + clear(r.orderedMapCache) +} + +func (r *Registrar) findFirstFor(capability ifaces.Capability, value any) *ifaces.RegistryEntry { + switch capability { + case ifaces.CapabilityMarshalJSON: + return r.findFirstInRegistryFor(r.marshalerRegistry, r.marshalerCache, capability, value) + case ifaces.CapabilityUnmarshalJSON: + return r.findFirstInRegistryFor(r.unmarshalerRegistry, r.unmarshalerCache, capability, value) + case ifaces.CapabilityOrderedMarshalJSON: + return r.findFirstInRegistryFor(r.orderedMarshalerRegistry, r.orderedMarshalerCache, capability, value) + case ifaces.CapabilityOrderedUnmarshalJSON: + return r.findFirstInRegistryFor(r.orderedUnmarshalerRegistry, r.orderedUnmarshalerCache, capability, value) + case ifaces.CapabilityOrderedMap: + return r.findFirstInRegistryFor(r.orderedMapRegistry, r.orderedMapCache, capability, value) + default: + panic(fmt.Errorf("unsupported capability %d: %w", capability, ErrRegistry)) + } +} + +func (r *Registrar) findFirstInRegistryFor(reg registry, cache map[reflect.Type]*ifaces.RegistryEntry, capability ifaces.Capability, value any) *ifaces.RegistryEntry { + r.gmx.RLock() + if len(reg) > 1 { + if entry, ok := cache[reflect.TypeOf(value)]; ok { + // cache hit + r.gmx.RUnlock() + return entry + } + } + + for _, entry := range reg { + if !entry.Support(capability, value) { + continue + } + + r.gmx.RUnlock() + + // update the internal cache + r.gmx.Lock() + cache[reflect.TypeOf(value)] = entry + r.gmx.Unlock() + + return entry + } + + // no adapter found + r.gmx.RUnlock() + + return nil +} + +// MarshalAdapterFor returns the first adapter that knows how to Marshal this type of value. +func MarshalAdapterFor(value any) ifaces.MarshalAdapter { + return Registry.AdapterFor(ifaces.CapabilityMarshalJSON, value) +} + +// OrderedMarshalAdapterFor returns the first adapter that knows how to OrderedMarshal this type of value. +func OrderedMarshalAdapterFor(value ifaces.Ordered) ifaces.OrderedMarshalAdapter { + return Registry.AdapterFor(ifaces.CapabilityOrderedMarshalJSON, value) +} + +// UnmarshalAdapterFor returns the first adapter that knows how to Unmarshal this type of value. +func UnmarshalAdapterFor(value any) ifaces.UnmarshalAdapter { + return Registry.AdapterFor(ifaces.CapabilityUnmarshalJSON, value) +} + +// OrderedUnmarshalAdapterFor provides the first adapter that knows how to OrderedUnmarshal this type of value. +func OrderedUnmarshalAdapterFor(value ifaces.SetOrdered) ifaces.OrderedUnmarshalAdapter { + return Registry.AdapterFor(ifaces.CapabilityOrderedUnmarshalJSON, value) +} + +// NewOrderedMap provides the "ordered map" implementation provided by the registry. +func NewOrderedMap(capacity int) ifaces.OrderedMap { + var v any + adapter := Registry.AdapterFor(ifaces.CapabilityOrderedUnmarshalJSON, v) + if adapter == nil { + return nil + } + + defer adapter.Redeem() + return adapter.NewOrderedMap(capacity) +} + +func noopRedeemer() {} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go new file mode 100644 index 000000000000..0213ff5c29f1 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + stdjson "encoding/json" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" + "github.com/go-openapi/swag/typeutils" +) + +const sensibleBufferSize = 8192 + +type jsonError string + +func (e jsonError) Error() string { + return string(e) +} + +// ErrStdlib indicates that an error comes from the stdlib JSON adapter +var ErrStdlib jsonError = "error from the JSON adapter stdlib" + +var _ ifaces.Adapter = &Adapter{} + +type Adapter struct { +} + +// NewAdapter yields an [ifaces.Adapter] using the standard library. +func NewAdapter() *Adapter { + return &Adapter{} +} + +func (a *Adapter) Marshal(value any) ([]byte, error) { + return stdjson.Marshal(value) +} + +func (a *Adapter) Unmarshal(data []byte, value any) error { + return stdjson.Unmarshal(data, value) +} + +func (a *Adapter) OrderedMarshal(value ifaces.Ordered) ([]byte, error) { + w := poolOfWriters.Borrow() + defer func() { + poolOfWriters.Redeem(w) + }() + + if typeutils.IsNil(value) { + w.RawString("null") + + return w.BuildBytes() + } + + w.RawByte('{') + first := true + for k, v := range value.OrderedItems() { + if first { + first = false + } else { + w.RawByte(',') + } + + w.String(k) + w.RawByte(':') + + switch val := v.(type) { + case ifaces.Ordered: + w.Raw(a.OrderedMarshal(val)) + default: + w.Raw(stdjson.Marshal(v)) + } + } + + w.RawByte('}') + + return w.BuildBytes() +} + +func (a *Adapter) OrderedUnmarshal(data []byte, value ifaces.SetOrdered) error { + var m MapSlice + if err := m.OrderedUnmarshalJSON(data); err != nil { + return err + } + + if typeutils.IsNil(m) { + // force input value to nil + value.SetOrderedItems(nil) + + return nil + } + + value.SetOrderedItems(m.OrderedItems()) + + return nil +} + +func (a *Adapter) NewOrderedMap(capacity int) ifaces.OrderedMap { + m := make(MapSlice, 0, capacity) + + return &m +} + +// Redeem the [Adapter] when it comes from a pool. +// +// The adapter becomes immediately unusable once redeemed. +func (a *Adapter) Redeem() { + if a == nil { + return + } + + RedeemAdapter(a) +} + +func (a *Adapter) Reset() { +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go new file mode 100644 index 000000000000..5ea1b4404252 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package json implements an [ifaces.Adapter] using the standard library. +package json diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go new file mode 100644 index 000000000000..b5aa1c7972e7 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go @@ -0,0 +1,320 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + stdjson "encoding/json" + "errors" + "fmt" + "io" + "math" + "strconv" + + "github.com/go-openapi/swag/conv" +) + +type token struct { + stdjson.Token +} + +func (t token) String() string { + if t == invalidToken { + return "invalid token" + } + if t == eofToken { + return "EOF" + } + + return fmt.Sprintf("%v", t.Token) +} + +func (t token) Kind() tokenKind { + switch t.Token.(type) { + case nil: + return tokenNull + case stdjson.Delim: + return tokenDelim + case bool: + return tokenBool + case float64: + return tokenFloat + case stdjson.Number: + return tokenNumber + case string: + return tokenString + default: + return tokenUndef + } +} + +func (t token) Delim() byte { + r, ok := t.Token.(stdjson.Delim) + if !ok { + return 0 + } + + return byte(r) +} + +type tokenKind uint8 + +const ( + tokenUndef tokenKind = iota + tokenString + tokenNumber + tokenFloat + tokenBool + tokenNull + tokenDelim +) + +var ( + invalidToken = token{ + Token: stdjson.Token(struct{}{}), + } + + eofToken = token{ + Token: stdjson.Token(&struct{}{}), + } + + undefToken = token{ + Token: stdjson.Token(uint8(0)), + } +) + +// jlexer apes easyjson's jlexer, but uses the standard library decoder under the hood. +type jlexer struct { + buf *bytesReader + dec *stdjson.Decoder + err error + // current token + next token + // started bool +} + +type bytesReader struct { + buf []byte + offset int +} + +func (b *bytesReader) Reset() { + b.buf = nil + b.offset = 0 +} + +func (b *bytesReader) Read(p []byte) (int, error) { + if b.offset >= len(b.buf) { + return 0, io.EOF + } + + n := len(p) + buf := b.buf[b.offset:] + m := len(buf) + + if n >= m { + copy(p, buf) + b.offset += m + + return m, nil + } + + copy(p, buf[:n]) + b.offset += n + + return n, nil +} + +var _ io.Reader = &bytesReader{} + +func newLexer(data []byte) *jlexer { + l := &jlexer{ + // current: undefToken, + next: undefToken, + } + l.buf = &bytesReader{ + buf: data, + } + l.dec = stdjson.NewDecoder(l.buf) // unfortunately, cannot pool this + + return l +} + +func (l *jlexer) Reset() { + l.err = nil + l.next = undefToken + // leave l.dec and l.buf alone, since they are replaced at every Borrow +} + +func (l *jlexer) Error() error { + return l.err +} + +func (l *jlexer) SetErr(err error) { + l.err = err +} + +func (l *jlexer) Ok() bool { + return l.err == nil +} + +// NextToken consumes a token +func (l *jlexer) NextToken() token { + if !l.Ok() { + return invalidToken + } + + if l.next != undefToken { + next := l.next + l.next = undefToken + + return next + } + + return l.fetchToken() +} + +// PeekToken returns the next token without consuming it +func (l *jlexer) PeekToken() token { + if l.next == undefToken { + l.next = l.fetchToken() + } + + return l.next +} + +func (l *jlexer) Skip() { + _ = l.NextToken() +} + +func (l *jlexer) IsDelim(c byte) bool { + if !l.Ok() { + return false + } + + next := l.PeekToken() + if next.Kind() != tokenDelim { + return false + } + + if next.Delim() != c { + return false + } + + return true +} + +func (l *jlexer) IsNull() bool { + if !l.Ok() { + return false + } + + next := l.PeekToken() + + return next.Kind() == tokenNull +} + +func (l *jlexer) Delim(c byte) { + if !l.Ok() { + return + } + + tok := l.NextToken() + if tok.Kind() != tokenDelim { + l.err = fmt.Errorf("expected a delimiter token but got '%v': %w", tok, ErrStdlib) + + return + } + + if tok.Delim() != c { + l.err = fmt.Errorf("expected delimiter '%q' but got '%q': %w", c, tok.Delim(), ErrStdlib) + } +} + +func (l *jlexer) Null() { + if !l.Ok() { + return + } + + tok := l.NextToken() + if tok.Kind() != tokenNull { + l.err = fmt.Errorf("expected a null token but got '%v': %w", tok, ErrStdlib) + } +} + +func (l *jlexer) Number() any { + if !l.Ok() { + return 0 + } + + tok := l.NextToken() + + switch tok.Kind() { //nolint:exhaustive + case tokenNumber: + n := tok.Token.(stdjson.Number).String() + f, _ := strconv.ParseFloat(n, 64) + if conv.IsFloat64AJSONInteger(f) { + return int64(math.Trunc(f)) + } + + return f + + case tokenFloat: + f := tok.Token.(float64) + if conv.IsFloat64AJSONInteger(f) { + return int64(math.Trunc(f)) + } + + return f + + default: + l.err = fmt.Errorf("expected a number token but got '%v': %w", tok, ErrStdlib) + + return 0 + } +} + +func (l *jlexer) Bool() bool { + if !l.Ok() { + return false + } + + tok := l.NextToken() + if tok.Kind() != tokenBool { + l.err = fmt.Errorf("expected a bool token but got '%v': %w", tok, ErrStdlib) + + return false + } + + return tok.Token.(bool) +} + +func (l *jlexer) String() string { + if !l.Ok() { + return "" + } + + tok := l.NextToken() + if tok.Kind() != tokenString { + l.err = fmt.Errorf("expected a string token but got '%v': %w", tok, ErrStdlib) + + return "" + } + + return tok.Token.(string) +} + +// Commas and colons are elided. +func (l *jlexer) fetchToken() token { + jtok, err := l.dec.Token() + if err != nil { + if errors.Is(err, io.EOF) { + return eofToken + } + + l.err = errors.Join(err, ErrStdlib) + return invalidToken + } + + return token{Token: jtok} +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go new file mode 100644 index 000000000000..54deef406f33 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go @@ -0,0 +1,266 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + stdjson "encoding/json" + "fmt" + "iter" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" +) + +var _ ifaces.OrderedMap = &MapSlice{} + +// MapSlice represents a JSON object, with the order of keys maintained. +type MapSlice []MapItem + +func (s MapSlice) OrderedItems() iter.Seq2[string, any] { + return func(yield func(string, any) bool) { + for _, item := range s { + if !yield(item.Key, item.Value) { + return + } + } + } +} + +func (s *MapSlice) SetOrderedItems(items iter.Seq2[string, any]) { + if items == nil { + *s = nil + + return + } + + m := *s + if len(m) > 0 { + // update mode + idx := make(map[string]int, len(m)) + + for i, item := range m { + idx[item.Key] = i + } + + for k, v := range items { + idx, ok := idx[k] + if ok { + m[idx].Value = v + + continue + } + m = append(m, MapItem{Key: k, Value: v}) + } + + *s = m + + return + } + + for k, v := range items { + m = append(m, MapItem{Key: k, Value: v}) + } + + *s = m +} + +// MarshalJSON renders a [MapSlice] as JSON bytes, preserving the order of keys. +func (s MapSlice) MarshalJSON() ([]byte, error) { + return s.OrderedMarshalJSON() +} + +func (s MapSlice) OrderedMarshalJSON() ([]byte, error) { + w := poolOfWriters.Borrow() + defer func() { + poolOfWriters.Redeem(w) + }() + + s.marshalObject(w) + + return w.BuildBytes() // this clones data, so it's okay to redeem the writer and its buffer +} + +// UnmarshalJSON builds a [MapSlice] from JSON bytes, preserving the order of keys. +// +// Inner objects are unmarshaled as [MapSlice] slices and not map[string]any. +func (s *MapSlice) UnmarshalJSON(data []byte) error { + return s.OrderedUnmarshalJSON(data) +} + +func (s *MapSlice) OrderedUnmarshalJSON(data []byte) error { + l := poolOfLexers.Borrow(data) + defer func() { + poolOfLexers.Redeem(l) + }() + + s.unmarshalObject(l) + + return l.Error() +} + +func (s MapSlice) marshalObject(w *jwriter) { + if s == nil { + w.RawString("null") + + return + } + + w.RawByte('{') + + if len(s) == 0 { + w.RawByte('}') + + return + } + + s[0].marshalJSON(w) + + for i := 1; i < len(s); i++ { + w.RawByte(',') + s[i].marshalJSON(w) + } + + w.RawByte('}') +} + +func (s *MapSlice) unmarshalObject(in *jlexer) { + if in.IsNull() { + in.Skip() + + return + } + + in.Delim('{') // consume token + if !in.Ok() { + return + } + + result := make(MapSlice, 0) + + for in.Ok() && !in.IsDelim('}') { + var mi MapItem + + mi.unmarshalKeyValue(in) + result = append(result, mi) + } + + in.Delim('}') + + if !in.Ok() { + return + } + + *s = result +} + +// MapItem represents the value of a key in a JSON object held by [MapSlice]. +// +// Notice that [MapItem] should not be marshaled to or unmarshaled from JSON directly, +// use this type as part of a [MapSlice] when dealing with JSON bytes. +type MapItem struct { + Key string + Value any +} + +func (s MapItem) marshalJSON(w *jwriter) { + w.String(s.Key) + w.RawByte(':') + w.Raw(stdjson.Marshal(s.Value)) +} + +func (s *MapItem) unmarshalKeyValue(in *jlexer) { + key := in.String() // consume string + value := s.asInterface(in) // consume any value, including termination tokens '}' or ']' + + if !in.Ok() { + return + } + + s.Key = key + s.Value = value +} + +func (s *MapItem) unmarshalArray(in *jlexer) []any { + if in.IsNull() { + in.Skip() + + return nil + } + + in.Delim('[') // consume token + if !in.Ok() { + return nil + } + + ret := make([]any, 0) + + for in.Ok() && !in.IsDelim(']') { + ret = append(ret, s.asInterface(in)) + } + + in.Delim(']') + if !in.Ok() { + return nil + } + + return ret +} + +// asInterface is very much like [jlexer.Lexer.Interface], but unmarshals an object +// into a [MapSlice], not a map[string]any. +// +// We have to force parsing errors somehow, since [jlexer.Lexer] doesn't let us +// set a parsing error directly. +func (s *MapItem) asInterface(in *jlexer) any { + if !in.Ok() { + return nil + } + + tok := in.PeekToken() // look-ahead what the next token looks like + kind := tok.Kind() + + switch kind { + case tokenString: + return in.String() // consume string + + case tokenNumber, tokenFloat: + return in.Number() + + case tokenBool: + return in.Bool() + + case tokenNull: + in.Null() + + return nil + + case tokenDelim: + switch tok.Delim() { + case '{': // not consumed yet + ret := make(MapSlice, 0) + ret.unmarshalObject(in) // consumes the terminating '}' + + if in.Ok() { + return ret + } + + // lexer is in an error state: will exhaust + return nil + + case '[': // not consumed yet + return s.unmarshalArray(in) // consumes the terminating ']' + default: + in.SetErr(fmt.Errorf("unexpected delimiter: %v: %w", tok, ErrStdlib)) // force error + return nil + } + + case tokenUndef: + fallthrough + default: + if in.Ok() { + in.SetErr(fmt.Errorf("unexpected token: %v: %w", tok, ErrStdlib)) // force error + } + + return nil + } +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go new file mode 100644 index 000000000000..709b97c3046b --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + "encoding/json" + "sync" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" +) + +type adaptersPool struct { + sync.Pool +} + +func (p *adaptersPool) Borrow() *Adapter { + return p.Get().(*Adapter) +} + +func (p *adaptersPool) BorrowIface() ifaces.Adapter { + return p.Get().(*Adapter) +} + +func (p *adaptersPool) Redeem(a *Adapter) { + p.Put(a) +} + +type writersPool struct { + sync.Pool +} + +func (p *writersPool) Borrow() *jwriter { + ptr := p.Get() + + jw := ptr.(*jwriter) + jw.Reset() + + return jw +} + +func (p *writersPool) Redeem(w *jwriter) { + p.Put(w) +} + +type lexersPool struct { + sync.Pool +} + +func (p *lexersPool) Borrow(data []byte) *jlexer { + ptr := p.Get() + + l := ptr.(*jlexer) + l.buf = poolOfReaders.Borrow(data) + l.dec = json.NewDecoder(l.buf) // cannot pool, not exposed by the encoding/json API + l.Reset() + + return l +} + +func (p *lexersPool) Redeem(l *jlexer) { + l.dec = nil + discard := l.buf + l.buf = nil + poolOfReaders.Redeem(discard) + p.Put(l) +} + +type readersPool struct { + sync.Pool +} + +func (p *readersPool) Borrow(data []byte) *bytesReader { + ptr := p.Get() + + b := ptr.(*bytesReader) + b.Reset() + b.buf = data + + return b +} + +func (p *readersPool) Redeem(b *bytesReader) { + p.Put(b) +} + +var ( + poolOfAdapters = &adaptersPool{ + Pool: sync.Pool{ + New: func() any { + return NewAdapter() + }, + }, + } + + poolOfWriters = &writersPool{ + Pool: sync.Pool{ + New: func() any { + return newJWriter() + }, + }, + } + + poolOfLexers = &lexersPool{ + Pool: sync.Pool{ + New: func() any { + return newLexer(nil) + }, + }, + } + + poolOfReaders = &readersPool{ + Pool: sync.Pool{ + New: func() any { + return &bytesReader{} + }, + }, + } +) + +// BorrowAdapter borrows an [Adapter] from the pool, recycling already allocated instances. +func BorrowAdapter() *Adapter { + return poolOfAdapters.Borrow() +} + +// BorrowAdapterIface borrows a stdlib [Adapter] and converts it directly +// to [ifaces.Adapter]. This is useful to avoid further allocations when +// translating the concrete type into an interface. +func BorrowAdapterIface() ifaces.Adapter { + return poolOfAdapters.BorrowIface() +} + +// RedeemAdapter redeems an [Adapter] to the pool, so it may be recycled. +func RedeemAdapter(a *Adapter) { + poolOfAdapters.Redeem(a) +} + +func RedeemAdapterIface(a ifaces.Adapter) { + concrete, ok := a.(*Adapter) + if ok { + poolOfAdapters.Redeem(concrete) + } +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go new file mode 100644 index 000000000000..fc8818694eae --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + "fmt" + "reflect" + + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" +) + +func Register(dispatcher ifaces.Registrar) { + t := reflect.TypeOf(Adapter{}) + dispatcher.RegisterFor( + ifaces.RegistryEntry{ + Who: fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()), + What: ifaces.AllCapabilities, + Constructor: BorrowAdapterIface, + Support: support, + }) +} + +func support(_ ifaces.Capability, _ any) bool { + return true +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go new file mode 100644 index 000000000000..dc2325c1a30f --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + "bytes" + "encoding/json" + "strings" +) + +type jwriter struct { + buf *bytes.Buffer + err error +} + +func newJWriter() *jwriter { + buf := make([]byte, 0, sensibleBufferSize) + + return &jwriter{buf: bytes.NewBuffer(buf)} +} + +func (w *jwriter) Reset() { + w.buf.Reset() + w.err = nil +} + +func (w *jwriter) RawString(s string) { + if w.err != nil { + return + } + w.buf.WriteString(s) +} + +func (w *jwriter) Raw(b []byte, err error) { + if w.err != nil { + return + } + if err != nil { + w.err = err + return + } + + _, _ = w.buf.Write(b) +} + +func (w *jwriter) RawByte(c byte) { + if w.err != nil { + return + } + w.buf.WriteByte(c) +} + +var quoteReplacer = strings.NewReplacer(`"`, `\"`, `\`, `\\`) + +func (w *jwriter) String(s string) { + if w.err != nil { + return + } + // escape quotes and \ + s = quoteReplacer.Replace(s) + + _ = w.buf.WriteByte('"') + json.HTMLEscape(w.buf, []byte(s)) + _ = w.buf.WriteByte('"') +} + +// BuildBytes returns a clone of the internal buffer. +func (w *jwriter) BuildBytes() ([]byte, error) { + if w.err != nil { + return nil, w.err + } + + return bytes.Clone(w.buf.Bytes()), nil +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/concat.go b/vendor/github.com/go-openapi/swag/jsonutils/concat.go new file mode 100644 index 000000000000..2068503af05b --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/concat.go @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonutils + +import ( + "bytes" +) + +// nullJSON represents a JSON object with null type +var nullJSON = []byte("null") + +const comma = byte(',') + +var closers map[byte]byte + +func init() { + closers = map[byte]byte{ + '{': '}', + '[': ']', + } +} + +// ConcatJSON concatenates multiple json objects or arrays efficiently. +// +// Note that [ConcatJSON] performs a very simple (and fast) concatenation +// operation: it does not attempt to merge objects. +func ConcatJSON(blobs ...[]byte) []byte { + if len(blobs) == 0 { + return nil + } + + last := len(blobs) - 1 + for blobs[last] == nil || bytes.Equal(blobs[last], nullJSON) { + // strips trailing null objects + last-- + if last < 0 { + // there was nothing but "null"s or nil... + return nil + } + } + if last == 0 { + return blobs[0] + } + + var opening, closing byte + var idx, a int + buf := bytes.NewBuffer(nil) + + for i, b := range blobs[:last+1] { + if b == nil || bytes.Equal(b, nullJSON) { + // a null object is in the list: skip it + continue + } + if len(b) > 0 && opening == 0 { // is this an array or an object? + opening, closing = b[0], closers[b[0]] + } + + if opening != '{' && opening != '[' { + continue // don't know how to concatenate non container objects + } + + const minLengthIfNotEmpty = 3 + if len(b) < minLengthIfNotEmpty { // yep empty but also the last one, so closing this thing + if i == last && a > 0 { + _ = buf.WriteByte(closing) // never returns err != nil + } + continue + } + + idx = 0 + if a > 0 { // we need to join with a comma for everything beyond the first non-empty item + _ = buf.WriteByte(comma) // never returns err != nil + idx = 1 // this is not the first or the last so we want to drop the leading bracket + } + + if i != last { // not the last one, strip brackets + _, _ = buf.Write(b[idx : len(b)-1]) // never returns err != nil + } else { // last one, strip only the leading bracket + _, _ = buf.Write(b[idx:]) + } + a++ + } + + // somehow it ended up being empty, so provide a default value + if buf.Len() == 0 && (opening == '{' || opening == '[') { + _ = buf.WriteByte(opening) // never returns err != nil + _ = buf.WriteByte(closing) + } + + return buf.Bytes() +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/doc.go b/vendor/github.com/go-openapi/swag/jsonutils/doc.go new file mode 100644 index 000000000000..3926cc58d1bc --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/doc.go @@ -0,0 +1,7 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package jsonutils provides helpers to work with JSON. +// +// These utilities work with dynamic go structures to and from JSON. +package jsonutils diff --git a/vendor/github.com/go-openapi/swag/jsonutils/json.go b/vendor/github.com/go-openapi/swag/jsonutils/json.go new file mode 100644 index 000000000000..40753ce03fde --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/json.go @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonutils + +import ( + "bytes" + "encoding/json" + + "github.com/go-openapi/swag/jsonutils/adapters" + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" +) + +// WriteJSON marshals a data structure as JSON. +// +// The difference with [json.Marshal] is that it may check among several alternatives +// to do so. +// +// See [adapters.Registrar] for more details about how to configure +// multiple serialization alternatives. +// +// NOTE: to allow types that are [easyjson.Marshaler] s to use that route to process JSON, +// you now need to register the adapter for easyjson at runtime. +func WriteJSON(value any) ([]byte, error) { + if orderedMap, isOrdered := value.(ifaces.Ordered); isOrdered { + orderedMarshaler := adapters.OrderedMarshalAdapterFor(orderedMap) + + if orderedMarshaler != nil { + defer orderedMarshaler.Redeem() + + return orderedMarshaler.OrderedMarshal(orderedMap) + } + + // no support found in registered adapters, fallback to the default (unordered) case + } + + marshaler := adapters.MarshalAdapterFor(value) + if marshaler != nil { + defer marshaler.Redeem() + + return marshaler.Marshal(value) + } + + // no support found in registered adapters, fallback to the default standard library. + // + // This only happens when tinkering with the global registry of adapters, since the default handles all the above cases. + return json.Marshal(value) // Codecov ignore // this is a safeguard not easily simulated in tests +} + +// ReadJSON unmarshals JSON data into a data structure. +// +// The difference with [json.Unmarshal] is that it may check among several alternatives +// to do so. +// +// See [adapters.Registrar] for more details about how to configure +// multiple serialization alternatives. +// +// NOTE: value must be a pointer. +// +// If the provided value implements [ifaces.SetOrdered], it is a considered an "ordered map" and [ReadJSON] +// will favor an adapter that supports the [ifaces.OrderedUnmarshal] feature, or fallback to +// an unordered behavior if none is found. +// +// NOTE: to allow types that are [easyjson.Unmarshaler] s to use that route to process JSON, +// you now need to register the adapter for easyjson at runtime. +func ReadJSON(data []byte, value any) error { + trimmedData := bytes.Trim(data, "\x00") + + if orderedMap, isOrdered := value.(ifaces.SetOrdered); isOrdered { + // if the value is an ordered map, favors support for OrderedUnmarshal. + + orderedUnmarshaler := adapters.OrderedUnmarshalAdapterFor(orderedMap) + + if orderedUnmarshaler != nil { + defer orderedUnmarshaler.Redeem() + + return orderedUnmarshaler.OrderedUnmarshal(trimmedData, orderedMap) + } + + // no support found in registered adapters, fallback to the default (unordered) case + } + + unmarshaler := adapters.UnmarshalAdapterFor(value) + if unmarshaler != nil { + defer unmarshaler.Redeem() + + return unmarshaler.Unmarshal(trimmedData, value) + } + + // no support found in registered adapters, fallback to the default standard library. + // + // This only happens when tinkering with the global registry of adapters, since the default handles all the above cases. + return json.Unmarshal(trimmedData, value) // Codecov ignore // this is a safeguard not easily simulated in tests +} + +// FromDynamicJSON turns a go value into a properly JSON typed structure. +// +// "Dynamic JSON" refers to what you get when unmarshaling JSON into an untyped any, +// i.e. objects are represented by map[string]any, arrays by []any, and +// all numbers are represented as float64. +// +// NOTE: target must be a pointer. +// +// # Maintaining the order of keys in objects +// +// If source and target implement [ifaces.Ordered] and [ifaces.SetOrdered] respectively, +// they are considered "ordered maps" and the order of keys is maintained in the +// "jsonification" process. In that case, map[string]any values are replaced by (ordered) [JSONMapSlice] ones. +func FromDynamicJSON(source, target any) error { + b, err := WriteJSON(source) + if err != nil { + return err + } + + return ReadJSON(b, target) +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go b/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go new file mode 100644 index 000000000000..38dd3e244426 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonutils + +import ( + "iter" + + "github.com/go-openapi/swag/jsonutils/adapters" + "github.com/go-openapi/swag/typeutils" +) + +// JSONMapSlice represents a JSON object, with the order of keys maintained. +// +// It behaves like an ordered map, but keys can't be accessed in constant time. +type JSONMapSlice []JSONMapItem + +// OrderedItems iterates over all (key,value) pairs with the order of keys maintained. +// +// This implements the [ifaces.Ordered] interface, so that [ifaces.Adapter] s know how to marshal +// keys in the desired order. +func (s JSONMapSlice) OrderedItems() iter.Seq2[string, any] { + return func(yield func(string, any) bool) { + for _, item := range s { + if !yield(item.Key, item.Value) { + return + } + } + } +} + +// SetOrderedItems sets keys in the [JSONMapSlice] objects, as presented by +// the provided iterator. +// +// As a special case, if items is nil, this sets to receiver to a nil slice. +// +// This implements the [ifaces.SetOrdered] interface, so that [ifaces.Adapter] s know how to unmarshal +// keys in the desired order. +func (s *JSONMapSlice) SetOrderedItems(items iter.Seq2[string, any]) { + if items == nil { + // force receiver to be a nil slice + *s = nil + + return + } + + m := *s + if len(m) > 0 { + // update mode: short-circuited when unmarshaling fresh data structures + idx := make(map[string]int, len(m)) + + for i, item := range m { + idx[item.Key] = i + } + + for k, v := range items { + idx, ok := idx[k] + if ok { + m[idx].Value = v + + continue + } + + m = append(m, JSONMapItem{Key: k, Value: v}) + } + + *s = m + + return + } + + for k, v := range items { + m = append(m, JSONMapItem{Key: k, Value: v}) + } + + *s = m +} + +// MarshalJSON renders a [JSONMapSlice] as JSON bytes, preserving the order of keys. +// +// It will pick the JSON library currently configured by the [adapters.Registry] (defaults to the standard library). +func (s JSONMapSlice) MarshalJSON() ([]byte, error) { + orderedMarshaler := adapters.OrderedMarshalAdapterFor(s) + defer orderedMarshaler.Redeem() + + return orderedMarshaler.OrderedMarshal(s) +} + +// UnmarshalJSON builds a [JSONMapSlice] from JSON bytes, preserving the order of keys. +// +// Inner objects are unmarshaled as ordered [JSONMapSlice] slices and not map[string]any. +// +// It will pick the JSON library currently configured by the [adapters.Registry] (defaults to the standard library). +func (s *JSONMapSlice) UnmarshalJSON(data []byte) error { + if typeutils.IsNil(*s) { + // allow to unmarshal with a simple var declaration (nil slice) + *s = JSONMapSlice{} + } + + orderedUnmarshaler := adapters.OrderedUnmarshalAdapterFor(s) + defer orderedUnmarshaler.Redeem() + + return orderedUnmarshaler.OrderedUnmarshal(data, s) +} + +// JSONMapItem represents the value of a key in a JSON object held by [JSONMapSlice]. +// +// Notice that JSONMapItem should not be marshaled to or unmarshaled from JSON directly. +// +// Use this type as part of a [JSONMapSlice] when dealing with JSON bytes. +type JSONMapItem struct { + Key string + Value any +} diff --git a/vendor/github.com/go-openapi/swag/jsonutils_iface.go b/vendor/github.com/go-openapi/swag/jsonutils_iface.go new file mode 100644 index 000000000000..7bd4105fa51a --- /dev/null +++ b/vendor/github.com/go-openapi/swag/jsonutils_iface.go @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "log" + + "github.com/go-openapi/swag/jsonutils" +) + +// JSONMapSlice represents a JSON object, with the order of keys maintained +// +// Deprecated: use [jsonutils.JSONMapSlice] instead, or [yamlutils.YAMLMapSlice] if you marshal YAML. +type JSONMapSlice = jsonutils.JSONMapSlice + +// JSONMapItem represents a JSON object, with the order of keys maintained +// +// Deprecated: use [jsonutils.JSONMapItem] instead. +type JSONMapItem = jsonutils.JSONMapItem + +// WriteJSON writes json data. +// +// Deprecated: use [jsonutils.WriteJSON] instead. +func WriteJSON(data any) ([]byte, error) { return jsonutils.WriteJSON(data) } + +// ReadJSON reads json data. +// +// Deprecated: use [jsonutils.ReadJSON] instead. +func ReadJSON(data []byte, value any) error { return jsonutils.ReadJSON(data, value) } + +// DynamicJSONToStruct converts an untyped JSON structure into a target data type. +// +// Deprecated: use [jsonutils.FromDynamicJSON] instead. +func DynamicJSONToStruct(data any, target any) error { + return jsonutils.FromDynamicJSON(data, target) +} + +// ConcatJSON concatenates multiple JSON objects efficiently. +// +// Deprecated: use [jsonutils.ConcatJSON] instead. +func ConcatJSON(blobs ...[]byte) []byte { return jsonutils.ConcatJSON(blobs...) } + +// ToDynamicJSON turns a go value into a properly JSON untyped structure. +// +// It is the same as [FromDynamicJSON], but doesn't check for errors. +// +// Deprecated: this function is a misnomer and is unsafe. Use [jsonutils.FromDynamicJSON] instead. +func ToDynamicJSON(value any) any { + var res any + if err := FromDynamicJSON(value, &res); err != nil { + log.Println(err) + } + + return res +} + +// FromDynamicJSON turns a go value into a properly JSON typed structure. +// +// "Dynamic JSON" refers to what you get when unmarshaling JSON into an untyped any, +// i.e. objects are represented by map[string]any, arrays by []any, and all +// scalar values are any. +// +// Deprecated: use [jsonutils.FromDynamicJSON] instead. +func FromDynamicJSON(data, target any) error { return jsonutils.FromDynamicJSON(data, target) } diff --git a/vendor/github.com/go-openapi/swag/loading/LICENSE b/vendor/github.com/go-openapi/swag/loading/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading/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/go-openapi/swag/loading/doc.go b/vendor/github.com/go-openapi/swag/loading/doc.go new file mode 100644 index 000000000000..8cf7bcb8b9d4 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package loading provides tools to load a file from http or from a local file system. +package loading diff --git a/vendor/github.com/go-openapi/swag/loading/errors.go b/vendor/github.com/go-openapi/swag/loading/errors.go new file mode 100644 index 000000000000..b3964289c742 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading/errors.go @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +type loadingError string + +const ( + // ErrLoader is an error raised by the file loader utility + ErrLoader loadingError = "loader error" +) + +func (e loadingError) Error() string { + return string(e) +} diff --git a/vendor/github.com/go-openapi/swag/loading/json.go b/vendor/github.com/go-openapi/swag/loading/json.go new file mode 100644 index 000000000000..59db12f5cfdb --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading/json.go @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +import ( + "encoding/json" + "errors" + "path/filepath" +) + +// JSONMatcher matches json for a file loader. +func JSONMatcher(path string) bool { + ext := filepath.Ext(path) + return ext == ".json" || ext == ".jsn" || ext == ".jso" +} + +// JSONDoc loads a json document from either a file or a remote url. +func JSONDoc(path string, opts ...Option) (json.RawMessage, error) { + data, err := LoadFromFileOrHTTP(path, opts...) + if err != nil { + return nil, errors.Join(err, ErrLoader) + } + return json.RawMessage(data), nil +} diff --git a/api/vendor/github.com/go-openapi/swag/loading.go b/vendor/github.com/go-openapi/swag/loading/loading.go similarity index 61% rename from api/vendor/github.com/go-openapi/swag/loading.go rename to vendor/github.com/go-openapi/swag/loading/loading.go index 658a24b789b5..269fb74d1675 100644 --- a/api/vendor/github.com/go-openapi/swag/loading.go +++ b/vendor/github.com/go-openapi/swag/loading/loading.go @@ -1,54 +1,26 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 -package swag +package loading import ( + "context" + "embed" "fmt" "io" "log" "net/http" "net/url" - "os" "path" "path/filepath" "runtime" "strings" - "time" ) -// LoadHTTPTimeout the default timeout for load requests -var LoadHTTPTimeout = 30 * time.Second - -// LoadHTTPBasicAuthUsername the username to use when load requests require basic auth -var LoadHTTPBasicAuthUsername = "" - -// LoadHTTPBasicAuthPassword the password to use when load requests require basic auth -var LoadHTTPBasicAuthPassword = "" - -// LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests -var LoadHTTPCustomHeaders = map[string]string{} - // LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in -func LoadFromFileOrHTTP(pth string) ([]byte, error) { - return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(pth) -} - -// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in -// timeout arg allows for per request overriding of the request timeout -func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration) ([]byte, error) { - return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(timeout))(pth) +func LoadFromFileOrHTTP(pth string, opts ...Option) ([]byte, error) { + o := optionsWithDefaults(opts) + return LoadStrategy(pth, o.ReadFileFunc(), loadHTTPBytes(opts...), opts...)(pth) } // LoadStrategy returns a loader function for a given path or URI. @@ -81,10 +53,12 @@ func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration) ([]byte, e // - `file://host/folder/file` becomes an UNC path like `\\host\folder\file` (no port specification is supported) // - `file:///c:/folder/file` becomes `C:\folder\file` // - `file://c:/folder/file` is tolerated (without leading `/`) and becomes `c:\folder\file` -func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) { +func LoadStrategy(pth string, local, remote func(string) ([]byte, error), opts ...Option) func(string) ([]byte, error) { if strings.HasPrefix(pth, "http") { return remote } + o := optionsWithDefaults(opts) + _, isEmbedFS := o.fs.(embed.FS) return func(p string) ([]byte, error) { upth, err := url.PathUnescape(p) @@ -92,19 +66,19 @@ func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(s return nil, err } - if !strings.HasPrefix(p, `file://`) { + cpth, hasPrefix := strings.CutPrefix(upth, "file://") + if !hasPrefix || isEmbedFS || runtime.GOOS != "windows" { + // crude processing: trim the file:// prefix. This leaves full URIs with a host with a (mostly) unexpected result // regular file path provided: just normalize slashes - return local(filepath.FromSlash(upth)) - } - - if runtime.GOOS != "windows" { - // crude processing: this leaves full URIs with a host with a (mostly) unexpected result - upth = strings.TrimPrefix(upth, `file://`) + if isEmbedFS { + // on windows, we need to slash the path if FS is an embed FS. + return local(strings.TrimLeft(filepath.ToSlash(cpth), "./")) // remove invalid leading characters for embed FS + } - return local(filepath.FromSlash(upth)) + return local(filepath.FromSlash(cpth)) } - // windows-only pre-processing of file://... URIs + // windows-only pre-processing of file://... URIs, excluding embed.FS // support for canonical file URIs on windows. u, err := url.Parse(filepath.ToSlash(upth)) @@ -139,19 +113,29 @@ func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(s } } -func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { +func loadHTTPBytes(opts ...Option) func(path string) ([]byte, error) { + o := optionsWithDefaults(opts) + return func(path string) ([]byte, error) { - client := &http.Client{Timeout: timeout} - req, err := http.NewRequest(http.MethodGet, path, nil) //nolint:noctx + client := o.client + timeoutCtx := context.Background() + var cancel func() + + if o.httpTimeout > 0 { + timeoutCtx, cancel = context.WithTimeout(timeoutCtx, o.httpTimeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(timeoutCtx, http.MethodGet, path, nil) if err != nil { return nil, err } - if LoadHTTPBasicAuthUsername != "" && LoadHTTPBasicAuthPassword != "" { - req.SetBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword) + if o.basicAuthUsername != "" && o.basicAuthPassword != "" { + req.SetBasicAuth(o.basicAuthUsername, o.basicAuthPassword) } - for key, val := range LoadHTTPCustomHeaders { + for key, val := range o.customHeaders { req.Header.Set(key, val) } diff --git a/vendor/github.com/go-openapi/swag/loading/options.go b/vendor/github.com/go-openapi/swag/loading/options.go new file mode 100644 index 000000000000..6674ac69e628 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading/options.go @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +import ( + "io/fs" + "net/http" + "os" + "time" +) + +type ( + // Option provides options for loading a file over HTTP or from a file. + Option func(*options) + + httpOptions struct { + httpTimeout time.Duration + basicAuthUsername string + basicAuthPassword string + customHeaders map[string]string + client *http.Client + } + + fileOptions struct { + fs fs.ReadFileFS + } + + options struct { + httpOptions + fileOptions + } +) + +func (fo fileOptions) ReadFileFunc() func(string) ([]byte, error) { + if fo.fs == nil { + return os.ReadFile + } + + return fo.fs.ReadFile +} + +// WithTimeout sets a timeout for the remote file loader. +// +// The default timeout is 30s. +func WithTimeout(timeout time.Duration) Option { + return func(o *options) { + o.httpTimeout = timeout + } +} + +// WithBasicAuth sets a basic authentication scheme for the remote file loader. +func WithBasicAuth(username, password string) Option { + return func(o *options) { + o.basicAuthUsername = username + o.basicAuthPassword = password + } +} + +// WithCustomHeaders sets custom headers for the remote file loader. +func WithCustomHeaders(headers map[string]string) Option { + return func(o *options) { + if o.customHeaders == nil { + o.customHeaders = make(map[string]string, len(headers)) + } + + for header, value := range headers { + o.customHeaders[header] = value + } + } +} + +// WithHTTPClient overrides the default HTTP client used to fetch a remote file. +// +// By default, [http.DefaultClient] is used. +func WithHTTPClient(client *http.Client) Option { + return func(o *options) { + o.client = client + } +} + +// WithFS sets a file system for the local file loader. +// +// If the provided file system is a [fs.ReadFileFS], the ReadFile function is used. +// Otherwise, ReadFile is wrapped using [fs.ReadFile]. +// +// By default, the file system is the one provided by the os package. +// +// For example, this may be set to consume from an embedded file system, or a rooted FS. +func WithFS(filesystem fs.FS) Option { + return func(o *options) { + if rfs, ok := filesystem.(fs.ReadFileFS); ok { + o.fs = rfs + + return + } + o.fs = readFileFS{FS: filesystem} + } +} + +type readFileFS struct { + fs.FS +} + +func (r readFileFS) ReadFile(name string) ([]byte, error) { + return fs.ReadFile(r.FS, name) +} + +func optionsWithDefaults(opts []Option) options { + const defaultTimeout = 30 * time.Second + + o := options{ + // package level defaults + httpOptions: httpOptions{ + httpTimeout: defaultTimeout, + client: http.DefaultClient, + }, + } + + for _, apply := range opts { + apply(&o) + } + + return o +} diff --git a/vendor/github.com/go-openapi/swag/loading/yaml.go b/vendor/github.com/go-openapi/swag/loading/yaml.go new file mode 100644 index 000000000000..3ebb53668c47 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading/yaml.go @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +import ( + "encoding/json" + "path/filepath" + + "github.com/go-openapi/swag/yamlutils" +) + +// YAMLMatcher matches yaml for a file loader. +func YAMLMatcher(path string) bool { + ext := filepath.Ext(path) + return ext == ".yaml" || ext == ".yml" +} + +// YAMLDoc loads a yaml document from either http or a file and converts it to json. +func YAMLDoc(path string, opts ...Option) (json.RawMessage, error) { + yamlDoc, err := YAMLData(path, opts...) + if err != nil { + return nil, err + } + + return yamlutils.YAMLToJSON(yamlDoc) +} + +// YAMLData loads a yaml document from either http or a file. +func YAMLData(path string, opts ...Option) (any, error) { + data, err := LoadFromFileOrHTTP(path, opts...) + if err != nil { + return nil, err + } + + return yamlutils.BytesToYAMLDoc(data) +} diff --git a/vendor/github.com/go-openapi/swag/loading_iface.go b/vendor/github.com/go-openapi/swag/loading_iface.go new file mode 100644 index 000000000000..27ec3fb8c37a --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading_iface.go @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "encoding/json" + "time" + + "github.com/go-openapi/swag/loading" +) + +var ( + // Package-level defaults for the file loading utilities (deprecated). + + // LoadHTTPTimeout the default timeout for load requests. + // + // Deprecated: use [loading.WithTimeout] instead. + LoadHTTPTimeout = 30 * time.Second + + // LoadHTTPBasicAuthUsername the username to use when load requests require basic auth. + // + // Deprecated: use [loading.WithBasicAuth] instead. + LoadHTTPBasicAuthUsername = "" + + // LoadHTTPBasicAuthPassword the password to use when load requests require basic auth. + // + // Deprecated: use [loading.WithBasicAuth] instead. + LoadHTTPBasicAuthPassword = "" + + // LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests. + // + // Deprecated: use [loading.WithCustomHeaders] instead. + LoadHTTPCustomHeaders = map[string]string{} +) + +// LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the provided path. +// +// Deprecated: use [loading.LoadFromFileOrHTTP] instead. +func LoadFromFileOrHTTP(pth string, opts ...loading.Option) ([]byte, error) { + return loading.LoadFromFileOrHTTP(pth, loadingOptionsWithDefaults(opts)...) +} + +// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in +// timeout arg allows for per request overriding of the request timeout. +// +// Deprecated: use [loading.LoadFileOrHTTP] with the [loading.WithTimeout] option instead. +func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration, opts ...loading.Option) ([]byte, error) { + opts = append(opts, loading.WithTimeout(timeout)) + + return LoadFromFileOrHTTP(pth, opts...) +} + +// LoadStrategy returns a loader function for a given path or URL. +// +// Deprecated: use [loading.LoadStrategy] instead. +func LoadStrategy(pth string, local, remote func(string) ([]byte, error), opts ...loading.Option) func(string) ([]byte, error) { + return loading.LoadStrategy(pth, local, remote, loadingOptionsWithDefaults(opts)...) +} + +// YAMLMatcher matches yaml for a file loader. +// +// Deprecated: use [loading.YAMLMatcher] instead. +func YAMLMatcher(path string) bool { return loading.YAMLMatcher(path) } + +// YAMLDoc loads a yaml document from either http or a file and converts it to json. +// +// Deprecated: use [loading.YAMLDoc] instead. +func YAMLDoc(path string) (json.RawMessage, error) { + return loading.YAMLDoc(path) +} + +// YAMLData loads a yaml document from either http or a file. +// +// Deprecated: use [loading.YAMLData] instead. +func YAMLData(path string) (any, error) { + return loading.YAMLData(path) +} + +// loadingOptionsWithDefaults bridges deprecated default settings that use package-level variables, +// with the recommended use of loading.Option. +func loadingOptionsWithDefaults(opts []loading.Option) []loading.Option { + o := []loading.Option{ + loading.WithTimeout(LoadHTTPTimeout), + loading.WithBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword), + loading.WithCustomHeaders(LoadHTTPCustomHeaders), + } + o = append(o, opts...) + + return o +} diff --git a/api/vendor/github.com/go-openapi/swag/BENCHMARK.md b/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md similarity index 53% rename from api/vendor/github.com/go-openapi/swag/BENCHMARK.md rename to vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md index e7f28ed6b789..6674c63b7294 100644 --- a/api/vendor/github.com/go-openapi/swag/BENCHMARK.md +++ b/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md @@ -1,12 +1,10 @@ -# Benchmarks - -## Name mangling utilities +# Benchmarking name mangling utilities ```bash go test -bench XXX -run XXX -benchtime 30s ``` -### Benchmarks at b3e7a5386f996177e4808f11acb2aa93a0f660df +## Benchmarks at b3e7a5386f996177e4808f11acb2aa93a0f660df ``` goos: linux @@ -21,7 +19,7 @@ BenchmarkToXXXName/ToHumanNameLower-4 895334 40354 ns/op 10472 B/op BenchmarkToXXXName/ToHumanNameTitle-4 882441 40678 ns/op 10566 B/op 749 allocs/op ``` -### Benchmarks after PR #79 +## Benchmarks after PR #79 ~ x10 performance improvement and ~ /100 memory allocations. @@ -50,3 +48,43 @@ BenchmarkToXXXName/ToCommandName-16 32256634 1137 ns/op 147 B/op BenchmarkToXXXName/ToHumanNameLower-16 18599661 1946 ns/op 92 B/op 6 allocs/op BenchmarkToXXXName/ToHumanNameTitle-16 17581353 2054 ns/op 105 B/op 6 allocs/op ``` + +## Benchmarks at d7d2d1b895f5b6747afaff312dd2a402e69e818b + +go1.24 + +``` +goos: linux +goarch: amd64 +pkg: github.com/go-openapi/swag +cpu: AMD Ryzen 7 5800X 8-Core Processor +BenchmarkToXXXName/ToGoName-16 19757858 1881 ns/op 42 B/op 5 allocs/op +BenchmarkToXXXName/ToVarName-16 17494111 2094 ns/op 74 B/op 7 allocs/op +BenchmarkToXXXName/ToFileName-16 28161226 1492 ns/op 158 B/op 7 allocs/op +BenchmarkToXXXName/ToCommandName-16 23787333 1489 ns/op 158 B/op 7 allocs/op +BenchmarkToXXXName/ToHumanNameLower-16 17537257 2030 ns/op 103 B/op 6 allocs/op +BenchmarkToXXXName/ToHumanNameTitle-16 16977453 2156 ns/op 105 B/op 6 allocs/op +``` + +## Benchmarks after PR #106 + +Moving the scope of everything down to a struct allowed to reduce a bit garbage and pooling. + +On top of that, ToGoName (and thus ToVarName) have been subject to a minor optimization, removing a few allocations. + +Overall timings improve by ~ -10%. + +go1.24 + +``` +goos: linux +goarch: amd64 +pkg: github.com/go-openapi/swag/mangling +cpu: AMD Ryzen 7 5800X 8-Core Processor +BenchmarkToXXXName/ToGoName-16 22496130 1618 ns/op 31 B/op 3 allocs/op +BenchmarkToXXXName/ToVarName-16 22538068 1618 ns/op 33 B/op 3 allocs/op +BenchmarkToXXXName/ToFileName-16 27722977 1236 ns/op 105 B/op 6 allocs/op +BenchmarkToXXXName/ToCommandName-16 27967395 1258 ns/op 105 B/op 6 allocs/op +BenchmarkToXXXName/ToHumanNameLower-16 18587901 1917 ns/op 103 B/op 6 allocs/op +BenchmarkToXXXName/ToHumanNameTitle-16 17193208 2019 ns/op 108 B/op 7 allocs/op +``` diff --git a/vendor/github.com/go-openapi/swag/mangling/LICENSE b/vendor/github.com/go-openapi/swag/mangling/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/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/go-openapi/swag/mangling/doc.go b/vendor/github.com/go-openapi/swag/mangling/doc.go new file mode 100644 index 000000000000..ce0d8904857a --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/doc.go @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package mangling provides name mangling capabilities. +// +// Name mangling is an important stage when generating code: +// it helps construct safe program identifiers that abide by the language rules +// and play along with linters. +// +// Examples: +// +// Suppose we get an object name taken from an API spec: "json_object", +// +// We may generate a legit go type name using [NameMangler.ToGoName]: "JsonObject". +// +// We may then locate this type in a source file named using [NameMangler.ToFileName]: "json_object.go". +// +// The methods exposed by the NameMangler are used to generate code in many different contexts, such as: +// +// - generating exported or unexported go identifiers from a JSON schema or an API spec +// - generating file names +// - generating human-readable comments for types and variables +// - generating JSON-like API identifiers from go code +// - ... +package mangling diff --git a/vendor/github.com/go-openapi/swag/mangling/initialism_index.go b/vendor/github.com/go-openapi/swag/mangling/initialism_index.go new file mode 100644 index 000000000000..e5b70c149388 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/initialism_index.go @@ -0,0 +1,270 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "sort" + "strings" + "unicode" + "unicode/utf8" +) + +// DefaultInitialisms returns all the initialisms configured by default for this package. +// +// # Motivation +// +// Common initialisms are acronyms for which the ordinary camel-casing rules are altered and +// for which we retain the original case. +// +// This is largely specific to the go naming conventions enforced by golint (now revive). +// +// # Example +// +// In go, "id" is a good-looking identifier, but "Id" is not and "ID" is preferred +// (notice that this stems only from conventions: the go compiler accepts all of these). +// +// Similarly, we may use "http", but not "Http". In this case, "HTTP" is preferred. +// +// # Reference and customization +// +// The default list of these casing-style exceptions is taken from the [github.com/mgechev/revive] linter for go: +// https://github.com/mgechev/revive/blob/master/lint/name.go#L93 +// +// There are a few additions to the original list, such as IPv4, IPv6 and OAI ("OpenAPI"). +// +// For these additions, "IPv4" would be preferred to "Ipv4" or "IPV4", and "OAI" to "Oai" +// +// You may redefine this list entirely using the mangler option [WithInitialisms], or simply add extra definitions +// using [WithAdditionalInitialisms]. +// +// # Mixed-case and plurals +// +// Notice that initialisms are not necessarily fully upper-cased: a mixed-case initialism indicates the preferred casing. +// +// Obviously, lower-case only initialisms do not make a lot of sense: if lower-case only initialisms are added, +// they will be considered fully capitalized. +// +// Plural forms use mixed case like "IDs". And so do values like "IPv4" or "IPv6". +// +// The [NameMangler] automatically detects simple plurals for words such as "IDs" or "APIs", +// so you don't need to configure these variants. +// +// At this moment, it doesn't support pluralization of terms that ends with an 's' (or 'S'), since there is +// no clear consensus on whether a word like DNS should be pluralized as DNSes or remain invariant. +// The [NameMangler] consider those invariant. Therefore DNSs or DNSes are not recognized as plurals for DNS. +// +// Besids, we don't want to support pluralization of terms which would otherwise conflict with another one, +// like "HTTPs" vs "HTTPS". All these should be considered invariant. Hence: "Https" matches "HTTPS" and +// "HTTPSS" is "HTTPS" followed by "S". +func DefaultInitialisms() []string { + return []string{ + "ACL", + "API", + "ASCII", + "CPU", + "CSS", + "DNS", + "EOF", + "GUID", + "HTML", + "HTTPS", + "HTTP", + "ID", + "IP", + "IPv4", // prefer the mixed case outcome IPv4 over the capitalized IPV4 + "IPv6", // prefer the mixed case outcome IPv6 over the capitalized IPV6 + "JSON", + "LHS", + "OAI", + "QPS", + "RAM", + "RHS", + "RPC", + "SLA", + "SMTP", + "SQL", + "SSH", + "TCP", + "TLS", + "TTL", + "UDP", + "UI", + "UID", + "UUID", + "URI", + "URL", + "UTF8", + "VM", + "XML", + "XMPP", + "XSRF", + "XSS", + } +} + +type indexOfInitialisms struct { + initialismsCache + + index map[string]struct{} +} + +func newIndexOfInitialisms() *indexOfInitialisms { + return &indexOfInitialisms{ + index: make(map[string]struct{}), + } +} + +func (m *indexOfInitialisms) add(words ...string) *indexOfInitialisms { + for _, word := range words { + // sanitization of injected words: trimmed from blanks, and must start with a letter + trimmed := strings.TrimSpace(word) + + firstRune, _ := utf8.DecodeRuneInString(trimmed) + if !unicode.IsLetter(firstRune) { + continue + } + + // Initialisms are case-sensitive. This means that we support mixed-case words. + // However, if specified as a lower-case string, the initialism should be fully capitalized. + if trimmed == strings.ToLower(trimmed) { + m.index[strings.ToUpper(trimmed)] = struct{}{} + + continue + } + + m.index[trimmed] = struct{}{} + } + return m +} + +func (m *indexOfInitialisms) sorted() []string { + result := make([]string, 0, len(m.index)) + for k := range m.index { + result = append(result, k) + } + sort.Sort(sort.Reverse(byInitialism(result))) + return result +} + +func (m *indexOfInitialisms) buildCache() { + m.build(m.sorted(), m.pluralForm) +} + +// initialismsCache caches all needed pre-computed and converted initialism entries, +// in the desired resolution order. +type initialismsCache struct { + initialisms []string + initialismsRunes [][]rune + initialismsUpperCased [][]rune // initialisms cached in their trimmed, upper-cased version + initialismsPluralForm []pluralForm +} + +func (c *initialismsCache) build(in []string, pluralfunc func(string) pluralForm) { + c.initialisms = in + c.initialismsRunes = asRunes(c.initialisms) + c.initialismsUpperCased = asUpperCased(c.initialisms) + c.initialismsPluralForm = asPluralForms(c.initialisms, pluralfunc) +} + +// pluralForm denotes the kind of pluralization to be used for initialisms. +// +// At this moment, initialisms are either invariant or follow a simple plural form with an +// extra (lower case) "s". +type pluralForm uint8 + +const ( + notPlural pluralForm = iota + invariantPlural + simplePlural +) + +func (f pluralForm) String() string { + switch f { + case notPlural: + return "notPlural" + case invariantPlural: + return "invariantPlural" + case simplePlural: + return "simplePlural" + default: + return "" + } +} + +// pluralForm indicates how we want to pluralize a given initialism. +// +// Besides configured invariant forms (like HTTP and HTTPS), +// an initialism is normally pluralized by adding a single 's', like in IDs. +// +// Initialisms ending with an 'S' or an 's' are configured as invariant (we don't +// support plural forms like CSSes or DNSes, however the mechanism could be extended to +// do just that). +func (m *indexOfInitialisms) pluralForm(key string) pluralForm { + if _, ok := m.index[key]; !ok { + return notPlural + } + + if strings.HasSuffix(strings.ToUpper(key), "S") { + return invariantPlural + } + + if _, ok := m.index[key+"s"]; ok { + return invariantPlural + } + + if _, ok := m.index[key+"S"]; ok { + return invariantPlural + } + + return simplePlural +} + +type byInitialism []string + +func (s byInitialism) Len() int { + return len(s) +} +func (s byInitialism) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} + +// Less specifies the order in which initialisms are prioritized: +// 1. match longest first +// 2. when equal length, match in reverse lexicographical order, lower case match comes first +func (s byInitialism) Less(i, j int) bool { + if len(s[i]) != len(s[j]) { + return len(s[i]) < len(s[j]) + } + + return s[i] < s[j] +} + +func asRunes(in []string) [][]rune { + out := make([][]rune, len(in)) + for i, initialism := range in { + out[i] = []rune(initialism) + } + + return out +} + +func asUpperCased(in []string) [][]rune { + out := make([][]rune, len(in)) + + for i, initialism := range in { + out[i] = []rune(upper(trim(initialism))) + } + + return out +} + +// asPluralForms bakes an index of pluralization support. +func asPluralForms(in []string, pluralFunc func(string) pluralForm) []pluralForm { + out := make([]pluralForm, len(in)) + for i, initialism := range in { + out[i] = pluralFunc(initialism) + } + + return out +} diff --git a/vendor/github.com/go-openapi/swag/mangling/name_lexem.go b/vendor/github.com/go-openapi/swag/mangling/name_lexem.go new file mode 100644 index 000000000000..bc837e3b9f5d --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/name_lexem.go @@ -0,0 +1,186 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "bytes" + "strings" + "unicode" + "unicode/utf8" +) + +type ( + lexemKind uint8 + + nameLexem struct { + original string + matchedInitialism string + kind lexemKind + } +) + +const ( + lexemKindCasualName lexemKind = iota + lexemKindInitialismName +) + +func newInitialismNameLexem(original, matchedInitialism string) nameLexem { + return nameLexem{ + kind: lexemKindInitialismName, + original: original, + matchedInitialism: matchedInitialism, + } +} + +func newCasualNameLexem(original string) nameLexem { + return nameLexem{ + kind: lexemKindCasualName, + original: trim(original), // TODO: save on calls to trim + } +} + +// WriteTitleized writes the titleized lexeme to a bytes.Buffer. +// +// If the first letter cannot be capitalized, it doesn't write anything and return false, +// so the caller may attempt some workaround strategy. +func (l nameLexem) WriteTitleized(w *bytes.Buffer, alwaysUpper bool) bool { + if l.kind == lexemKindInitialismName { + w.WriteString(l.matchedInitialism) + + return true + } + + if len(l.original) == 0 { + return true + } + + if len(l.original) == 1 { + // identifier is too short: casing will depend on the context + firstByte := l.original[0] + switch { + case 'A' <= firstByte && firstByte <= 'Z': + // safe + w.WriteByte(firstByte) + + return true + case alwaysUpper && 'a' <= firstByte && firstByte <= 'z': + w.WriteByte(firstByte - 'a' + 'A') + + return true + default: + + // not a letter: skip and let the caller decide + return false + } + } + + if firstByte := l.original[0]; firstByte < utf8.RuneSelf { + // ASCII + switch { + case 'A' <= firstByte && firstByte <= 'Z': + // already an upper case letter + w.WriteString(l.original) + + return true + case 'a' <= firstByte && firstByte <= 'z': + w.WriteByte(firstByte - 'a' + 'A') + w.WriteString(l.original[1:]) + + return true + default: + // not a good candidate: doesn't start with a letter + return false + } + } + + // unicode + firstRune, idx := utf8.DecodeRuneInString(l.original) + if !unicode.IsLetter(firstRune) || !unicode.IsUpper(unicode.ToUpper(firstRune)) { + // not a good candidate: doesn't start with a letter + // or a rune for which case doesn't make sense (e.g. East-Asian runes etc) + return false + } + + rest := l.original[idx:] + w.WriteRune(unicode.ToUpper(firstRune)) + w.WriteString(strings.ToLower(rest)) + + return true +} + +// WriteLower is like write titleized but it writes a lower-case version of the lexeme. +// +// Similarly, there is no writing if the casing of the first rune doesn't make sense. +func (l nameLexem) WriteLower(w *bytes.Buffer, alwaysLower bool) bool { + if l.kind == lexemKindInitialismName { + w.WriteString(lower(l.matchedInitialism)) + + return true + } + + if len(l.original) == 0 { + return true + } + + if len(l.original) == 1 { + // identifier is too short: casing will depend on the context + firstByte := l.original[0] + switch { + case 'a' <= firstByte && firstByte <= 'z': + // safe + w.WriteByte(firstByte) + + return true + case alwaysLower && 'A' <= firstByte && firstByte <= 'Z': + w.WriteByte(firstByte - 'A' + 'a') + + return true + default: + + // not a letter: skip and let the caller decide + return false + } + } + + if firstByte := l.original[0]; firstByte < utf8.RuneSelf { + // ASCII + switch { + case 'a' <= firstByte && firstByte <= 'z': + // already a lower case letter + w.WriteString(l.original) + + return true + case 'A' <= firstByte && firstByte <= 'Z': + w.WriteByte(firstByte - 'A' + 'a') + w.WriteString(l.original[1:]) + + return true + default: + // not a good candidate: doesn't start with a letter + return false + } + } + + // unicode + firstRune, idx := utf8.DecodeRuneInString(l.original) + if !unicode.IsLetter(firstRune) || !unicode.IsLower(unicode.ToLower(firstRune)) { + // not a good candidate: doesn't start with a letter + // or a rune for which case doesn't make sense (e.g. East-Asian runes etc) + return false + } + + rest := l.original[idx:] + w.WriteRune(unicode.ToLower(firstRune)) + w.WriteString(rest) + + return true +} + +func (l nameLexem) GetOriginal() string { + return l.original +} + +func (l nameLexem) IsInitialism() bool { + return l.kind == lexemKindInitialismName +} diff --git a/vendor/github.com/go-openapi/swag/mangling/name_mangler.go b/vendor/github.com/go-openapi/swag/mangling/name_mangler.go new file mode 100644 index 000000000000..da685681d08c --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/name_mangler.go @@ -0,0 +1,370 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "strings" + "unicode" +) + +// NameMangler knows how to transform sentences or words into +// identifiers that are a better fit in contexts such as: +// +// - unexported or exported go variable identifiers +// - file names +// - camel cased identifiers +// - ... +// +// The [NameMangler] is safe for concurrent use, save for its [NameMangler.AddInitialisms] method, +// which is not. +// +// # Known limitations +// +// At this moment, the [NameMangler] doesn't play well with "all caps" text: +// +// unless every single upper-cased word is declared as an initialism, capitalized words would generally +// not be transformed with the expected result, e.g. +// +// ToFileName("THIS_IS_ALL_CAPS") +// +// yields the weird outcome +// +// "t_h_i_s_i_s_a_l_l_c_a_p_s" +type NameMangler struct { + options + + index *indexOfInitialisms + + splitter splitter + splitterWithPostSplit splitter + + _ struct{} +} + +// NewNameMangler builds a name mangler ready to convert strings. +// +// The default name mangler is configured with default common initialisms and all default options. +func NewNameMangler(opts ...Option) NameMangler { + m := NameMangler{ + options: optionsWithDefaults(opts), + index: newIndexOfInitialisms(), + } + m.addInitialisms(m.commonInitialisms...) + + // a splitter that returns matches lexemes as ready-to-assemble strings: + // details of the lexemes are redeemed. + m.splitter = newSplitter( + withInitialismsCache(&m.index.initialismsCache), + withReplaceFunc(m.replaceFunc), + ) + + // a splitter that returns matches lexemes ready for post-processing + m.splitterWithPostSplit = newSplitter( + withInitialismsCache(&m.index.initialismsCache), + withReplaceFunc(m.replaceFunc), + withPostSplitInitialismCheck, + ) + + return m +} + +// AddInitialisms declares extra initialisms to the mangler. +// +// It declares extra words as "initialisms" (i.e. words that won't be camel cased or titled cased), +// on top of the existing list of common initialisms (such as ID, HTTP...). +// +// Added words must start with a (unicode) letter. If some don't, they are ignored. +// Added words are either fully capitalized or mixed-cased. Lower-case only words are considered capitalized. +// +// It is typically used just after initializing the [NameMangler]. +// +// When all initialisms are known at the time the mangler is initialized, it is preferable to +// use [NewNameMangler] with the option [WithAdditionalInitialisms]. +// +// Adding initialisms mutates the mangler and should not be carried out concurrently with other calls to the mangler. +func (m *NameMangler) AddInitialisms(words ...string) { + m.addInitialisms(words...) +} + +// Initialisms renders the list of initialisms supported by this mangler. +func (m *NameMangler) Initialisms() []string { + return m.index.initialisms +} + +// Camelize a single word. +// +// Example: +// +// - "HELLO" and "hello" become "Hello". +func (m NameMangler) Camelize(word string) string { + ru := []rune(word) + + switch len(ru) { + case 0: + return "" + case 1: + return string(unicode.ToUpper(ru[0])) + default: + camelized := poolOfBuffers.BorrowBuffer(len(word)) + camelized.Grow(len(word)) + defer func() { + poolOfBuffers.RedeemBuffer(camelized) + }() + + camelized.WriteRune(unicode.ToUpper(ru[0])) + for _, ru := range ru[1:] { + camelized.WriteRune(unicode.ToLower(ru)) + } + + return camelized.String() + } +} + +// ToFileName generates a suitable snake-case file name from a sentence. +// +// It lower-cases everything with underscore (_) as a word separator. +// +// Examples: +// +// - "Hello, Swagger" becomes "hello_swagger" +// - "HelloSwagger" becomes "hello_swagger" +func (m NameMangler) ToFileName(name string) string { + inptr := m.split(name) + in := *inptr + out := make([]string, 0, len(in)) + + for _, w := range in { + out = append(out, lower(w)) + } + poolOfStrings.RedeemStrings(inptr) + + return strings.Join(out, "_") +} + +// ToCommandName generates a suitable CLI command name from a sentence. +// +// It lower-cases everything with dash (-) as a word separator. +// +// Examples: +// +// - "Hello, Swagger" becomes "hello-swagger" +// - "HelloSwagger" becomes "hello-swagger" +func (m NameMangler) ToCommandName(name string) string { + inptr := m.split(name) + in := *inptr + out := make([]string, 0, len(in)) + + for _, w := range in { + out = append(out, lower(w)) + } + poolOfStrings.RedeemStrings(inptr) + + return strings.Join(out, "-") +} + +// ToHumanNameLower represents a code name as a human-readable series of words. +// +// It lower-cases everything with blank space as a word separator. +// +// NOTE: parts recognized as initialisms just keep their original casing. +// +// Examples: +// +// - "Hello, Swagger" becomes "hello swagger" +// - "HelloSwagger" or "Hello-Swagger" become "hello swagger" +func (m NameMangler) ToHumanNameLower(name string) string { + s := m.splitterWithPostSplit + in := s.split(name) + out := make([]string, 0, len(*in)) + + for _, w := range *in { + if !w.IsInitialism() { + out = append(out, lower(w.GetOriginal())) + } else { + out = append(out, trim(w.GetOriginal())) + } + } + + poolOfLexems.RedeemLexems(in) + + return strings.Join(out, " ") +} + +// ToHumanNameTitle represents a code name as a human-readable series of titleized words. +// +// It titleizes every word with blank space as a word separator. +// +// Examples: +// +// - "hello, Swagger" becomes "Hello Swagger" +// - "helloSwagger" becomes "Hello Swagger" +func (m NameMangler) ToHumanNameTitle(name string) string { + s := m.splitterWithPostSplit + in := s.split(name) + + out := make([]string, 0, len(*in)) + for _, w := range *in { + original := trim(w.GetOriginal()) + if !w.IsInitialism() { + out = append(out, m.Camelize(original)) + } else { + out = append(out, original) + } + } + poolOfLexems.RedeemLexems(in) + + return strings.Join(out, " ") +} + +// ToJSONName generates a camelized single-word version of a sentence. +// +// The output assembles every camelized word, but for the first word, which +// is lower-cased. +// +// Example: +// +// - "Hello_swagger" becomes "helloSwagger" +func (m NameMangler) ToJSONName(name string) string { + inptr := m.split(name) + in := *inptr + out := make([]string, 0, len(in)) + + for i, w := range in { + if i == 0 { + out = append(out, lower(w)) + continue + } + out = append(out, m.Camelize(trim(w))) + } + + poolOfStrings.RedeemStrings(inptr) + + return strings.Join(out, "") +} + +// ToVarName generates a legit unexported go variable name from a sentence. +// +// The generated name plays well with linters (see also [NameMangler.ToGoName]). +// +// Examples: +// +// - "Hello_swagger" becomes "helloSwagger" +// - "Http_server" becomes "httpServer" +// +// This name applies the same rules as [NameMangler.ToGoName] (legit exported variable), save the +// capitalization of the initial rune. +// +// Special case: when the initial part is a recognized as an initialism (like in the example above), +// the full part is lower-cased. +func (m NameMangler) ToVarName(name string) string { + return m.goIdentifier(name, false) +} + +// ToGoName generates a legit exported go variable name from a sentence. +// +// The generated name plays well with most linters. +// +// ToGoName abides by the go "exported" symbol rule starting with an upper-case letter. +// +// Examples: +// +// - "hello_swagger" becomes "HelloSwagger" +// - "Http_server" becomes "HTTPServer" +// +// # Edge cases +// +// Whenever the first rune is not eligible to upper case, a special prefix is prepended to the resulting name. +// By default this is simply "X" and you may customize this behavior using the [WithGoNamePrefixFunc] option. +// +// This happens when the first rune is not a letter, e.g. a digit, or a symbol that has no word transliteration +// (see also [WithReplaceFunc] about symbol transliterations), +// as well as for most East Asian or Devanagari runes, for which there is no such concept as upper-case. +// +// # Linting +// +// [revive], the successor of golint is the reference linter. +// +// This means that [NameMangler.ToGoName] supports the initialisms that revive checks (see also [DefaultInitialisms]). +// +// At this moment, there is no attempt to transliterate unicode into ascii, meaning that some linters +// (e.g. asciicheck, gosmopolitan) may croak on go identifiers generated from unicode input. +// +// [revive]: https://github.com/mgechev/revive +func (m NameMangler) ToGoName(name string) string { + return m.goIdentifier(name, true) +} + +func (m NameMangler) goIdentifier(name string, exported bool) string { + s := m.splitterWithPostSplit + lexems := s.split(name) + defer func() { + poolOfLexems.RedeemLexems(lexems) + }() + lexemes := *lexems + + if len(lexemes) == 0 { + return "" + } + + result := poolOfBuffers.BorrowBuffer(len(name)) + defer func() { + poolOfBuffers.RedeemBuffer(result) + }() + + firstPart := lexemes[0] + if !exported { + if ok := firstPart.WriteLower(result, true); !ok { + // NOTE: an initialism as the first part is lower-cased: no longer generates stuff like hTTPxyz. + // + // same prefixing rule applied to unexported variable as to an exported one, so that we have consistent + // names, whether the generated identifier is exported or not. + result.WriteString(strings.ToLower(m.prefixFunc()(name))) + result.WriteString(lexemes[0].GetOriginal()) + } + } else { + if ok := firstPart.WriteTitleized(result, true); !ok { + // "repairs" a lexeme that doesn't start with a letter to become + // the start a legit go name. The current strategy is very crude and simply adds a fixed prefix, + // e.g. "X". + // For instance "1_sesame_street" would be split into lexemes ["1", "sesame", "street"] and + // the first one ("1") would result in something like "X1" (with the default prefix function). + // + // NOTE: no longer forcing the first part to be fully upper-cased + result.WriteString(m.prefixFunc()(name)) + result.WriteString(lexemes[0].GetOriginal()) + } + } + + for _, lexem := range lexemes[1:] { + // NOTE: no longer forcing initialism parts to be fully upper-cased: + // * pluralized initialism preserve their trailing "s" + // * mixed-cased initialisms, such as IPv4, are preserved + if ok := lexem.WriteTitleized(result, false); !ok { + // it's not titleized: perhaps it's too short, perhaps the first rune is not a letter. + // write anyway + result.WriteString(lexem.GetOriginal()) + } + } + + return result.String() +} + +func (m *NameMangler) addInitialisms(words ...string) { + m.index.add(words...) + m.index.buildCache() +} + +// split calls the inner splitter. +func (m NameMangler) split(str string) *[]string { + s := m.splitter + lexems := s.split(str) + result := poolOfStrings.BorrowStrings() + + for _, lexem := range *lexems { + *result = append(*result, lexem.GetOriginal()) + } + poolOfLexems.RedeemLexems(lexems) + + return result +} diff --git a/vendor/github.com/go-openapi/swag/mangling/options.go b/vendor/github.com/go-openapi/swag/mangling/options.go new file mode 100644 index 000000000000..3c92b2f18bf1 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/options.go @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +type ( + // PrefixFunc defines a safeguard rule (that may depend on the input string), to prefix + // a generated go name (in [NameMangler.ToGoName] and [NameMangler.ToVarName]). + // + // See [NameMangler.ToGoName] for more about which edge cases the prefix function covers. + PrefixFunc func(string) string + + // ReplaceFunc is a transliteration function to replace special runes by a word. + ReplaceFunc func(r rune) (string, bool) + + // Option to configure a [NameMangler]. + Option func(*options) + + options struct { + commonInitialisms []string + + goNamePrefixFunc PrefixFunc + goNamePrefixFuncPtr *PrefixFunc + replaceFunc func(r rune) (string, bool) + } +) + +func (o *options) prefixFunc() PrefixFunc { + if o.goNamePrefixFuncPtr != nil && *o.goNamePrefixFuncPtr != nil { + return *o.goNamePrefixFuncPtr + } + + return o.goNamePrefixFunc +} + +// WithGoNamePrefixFunc overrides the default prefix rule to safeguard generated go names. +// +// Example: +// +// This helps convert "123" into "{prefix}123" (a very crude strategy indeed, but it works). +// +// See [github.com/go-swagger/go-swagger/generator.DefaultFuncMap] for an example. +// +// The prefix function is assumed to return a string that starts with an upper case letter. +// +// The default is to prefix with "X". +// +// See [NameMangler.ToGoName] for more about which edge cases the prefix function covers. +func WithGoNamePrefixFunc(fn PrefixFunc) Option { + return func(o *options) { + o.goNamePrefixFunc = fn + } +} + +// WithGoNamePrefixFuncPtr is like [WithGoNamePrefixFunc] but it specifies a pointer to a function. +// +// [WithGoNamePrefixFunc] should be preferred in most situations. This option should only serve the +// purpose of handling special situations where the prefix function is not an internal variable +// (e.g. an exported package global). +// +// [WithGoNamePrefixFuncPtr] supersedes [WithGoNamePrefixFunc] if it also specified. +// +// If the provided pointer is nil or points to a nil value, this option has no effect. +// +// The caller should ensure that no undesirable concurrent changes are applied to the function pointed to. +func WithGoNamePrefixFuncPtr(ptr *PrefixFunc) Option { + return func(o *options) { + o.goNamePrefixFuncPtr = ptr + } +} + +// WithInitialisms declares the initialisms this mangler supports. +// +// This supersedes any pre-loaded defaults (see [DefaultInitialisms] for more about what initialisms are). +// +// It declares words to be recognized as "initialisms" (i.e. words that won't be camel cased or titled cased). +// +// Words must start with a (unicode) letter. If some don't, they are ignored. +// Words are either fully capitalized or mixed-cased. Lower-case only words are considered capitalized. +func WithInitialisms(words ...string) Option { + return func(o *options) { + o.commonInitialisms = words + } +} + +// WithAdditionalInitialisms adds new initialisms to the currently supported list (see [DefaultInitialisms]). +// +// The same sanitization rules apply as those described for [WithInitialisms]. +func WithAdditionalInitialisms(words ...string) Option { + return func(o *options) { + o.commonInitialisms = append(o.commonInitialisms, words...) + } +} + +// WithReplaceFunc specifies a custom transliteration function instead of the default. +// +// The default translates the following characters into words as follows: +// +// - '@' -> 'At' +// - '&' -> 'And' +// - '|' -> 'Pipe' +// - '$' -> 'Dollar' +// - '!' -> 'Bang' +// +// Notice that the outcome of a transliteration should always be titleized. +func WithReplaceFunc(fn ReplaceFunc) Option { + return func(o *options) { + o.replaceFunc = fn + } +} + +func defaultPrefixFunc(_ string) string { + return "X" +} + +// defaultReplaceTable finds a word representation for special characters. +func defaultReplaceTable(r rune) (string, bool) { + switch r { + case '@': + return "At ", true + case '&': + return "And ", true + case '|': + return "Pipe ", true + case '$': + return "Dollar ", true + case '!': + return "Bang ", true + case '-': + return "", true + case '_': + return "", true + default: + return "", false + } +} + +func optionsWithDefaults(opts []Option) options { + o := options{ + commonInitialisms: DefaultInitialisms(), + goNamePrefixFunc: defaultPrefixFunc, + replaceFunc: defaultReplaceTable, + } + + for _, apply := range opts { + apply(&o) + } + + return o +} diff --git a/vendor/github.com/go-openapi/swag/mangling/pools.go b/vendor/github.com/go-openapi/swag/mangling/pools.go new file mode 100644 index 000000000000..f8104351445d --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/pools.go @@ -0,0 +1,123 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "bytes" + "sync" +) + +const maxAllocMatches = 8 + +type ( + // memory pools of temporary objects. + // + // These are used to recycle temporarily allocated objects + // and relieve the GC from undue pressure. + + matchesPool struct { + *sync.Pool + } + + buffersPool struct { + *sync.Pool + } + + lexemsPool struct { + *sync.Pool + } + + stringsPool struct { + *sync.Pool + } +) + +var ( + // poolOfMatches holds temporary slices for recycling during the initialism match process + poolOfMatches = matchesPool{ + Pool: &sync.Pool{ + New: func() any { + s := make(initialismMatches, 0, maxAllocMatches) + + return &s + }, + }, + } + + poolOfBuffers = buffersPool{ + Pool: &sync.Pool{ + New: func() any { + return new(bytes.Buffer) + }, + }, + } + + poolOfLexems = lexemsPool{ + Pool: &sync.Pool{ + New: func() any { + s := make([]nameLexem, 0, maxAllocMatches) + + return &s + }, + }, + } + + poolOfStrings = stringsPool{ + Pool: &sync.Pool{ + New: func() any { + s := make([]string, 0, maxAllocMatches) + + return &s + }, + }, + } +) + +func (p matchesPool) BorrowMatches() *initialismMatches { + s := p.Get().(*initialismMatches) + *s = (*s)[:0] // reset slice, keep allocated capacity + + return s +} + +func (p buffersPool) BorrowBuffer(size int) *bytes.Buffer { + s := p.Get().(*bytes.Buffer) + s.Reset() + + if s.Cap() < size { + s.Grow(size) + } + + return s +} + +func (p lexemsPool) BorrowLexems() *[]nameLexem { + s := p.Get().(*[]nameLexem) + *s = (*s)[:0] // reset slice, keep allocated capacity + + return s +} + +func (p stringsPool) BorrowStrings() *[]string { + s := p.Get().(*[]string) + *s = (*s)[:0] // reset slice, keep allocated capacity + + return s +} + +func (p matchesPool) RedeemMatches(s *initialismMatches) { + p.Put(s) +} + +func (p buffersPool) RedeemBuffer(s *bytes.Buffer) { + p.Put(s) +} + +func (p lexemsPool) RedeemLexems(s *[]nameLexem) { + p.Put(s) +} + +func (p stringsPool) RedeemStrings(s *[]string) { + p.Put(s) +} diff --git a/vendor/github.com/go-openapi/swag/mangling/split.go b/vendor/github.com/go-openapi/swag/mangling/split.go new file mode 100644 index 000000000000..ed12ea256746 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/split.go @@ -0,0 +1,341 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "fmt" + "unicode" +) + +type splitterOption func(*splitter) + +// withPostSplitInitialismCheck allows to catch initialisms after main split process +func withPostSplitInitialismCheck(s *splitter) { + s.postSplitInitialismCheck = true +} + +func withReplaceFunc(fn ReplaceFunc) func(*splitter) { + return func(s *splitter) { + s.replaceFunc = fn + } +} + +func withInitialismsCache(c *initialismsCache) splitterOption { + return func(s *splitter) { + s.initialismsCache = c + } +} + +type ( + initialismMatch struct { + body []rune + start, end int + complete bool + hasPlural pluralForm + } + initialismMatches []initialismMatch +) + +// String representation of a match, e.g. for debugging. +func (m initialismMatch) String() string { + return fmt.Sprintf("{body: %s (%d), start: %d, end; %d, complete: %t, hasPlural: %v}", + string(m.body), len(m.body), m.start, m.end, m.complete, m.hasPlural, + ) +} + +func (m initialismMatch) isZero() bool { + return m.start == 0 && m.end == 0 +} + +type splitter struct { + *initialismsCache + + postSplitInitialismCheck bool + replaceFunc ReplaceFunc +} + +func newSplitter(options ...splitterOption) splitter { + var s splitter + + for _, option := range options { + option(&s) + } + + if s.replaceFunc == nil { + s.replaceFunc = defaultReplaceTable + } + + return s +} + +func (s splitter) split(name string) *[]nameLexem { + nameRunes := []rune(name) + matches := s.gatherInitialismMatches(nameRunes) + if matches == nil { + return poolOfLexems.BorrowLexems() + } + + return s.mapMatchesToNameLexems(nameRunes, matches) +} + +func (s splitter) gatherInitialismMatches(nameRunes []rune) *initialismMatches { + matches := poolOfMatches.BorrowMatches() + const minLenInitialism = 1 + if len(nameRunes) < minLenInitialism+1 { + // can't match initialism with 0 or 1 rune + return matches + } + + // first iteration + s.findMatches(matches, nameRunes, nameRunes[0], 0) + + for i, currentRune := range nameRunes[1:] { + currentRunePosition := i + 1 + // recycle allocations as we loop over runes + // with such recycling, only 2 slices should be allocated per call + // instead of o(n). + // + // BorrowMatches always yields slices with zero length (with some capacity) + newMatches := poolOfMatches.BorrowMatches() + + // check current initialism matches + for _, match := range *matches { + if keepCompleteMatch := match.complete; keepCompleteMatch { + // the match is already complete: keep it then move on to the next match + *newMatches = append(*newMatches, match) + continue + } + + if currentRunePosition-match.start == len(match.body) { + // unmatched: skip + continue + } + + // 1. by construction of the matches, we can't have currentRunePosition - match.start < 0 + // because matches have been computed with their start <= currentRunePosition in the previous + // iterations. + // 2. by construction of the matches, we can't have currentRunePosition - match.start >= len(match.body) + + currentMatchRune := match.body[currentRunePosition-match.start] + if currentMatchRune != currentRune { + // failed match, discard it then move on to the next match + continue + } + + // try to complete the current match + if currentRunePosition-match.start == len(match.body)-1 { + // we are close: the next step is to check the symbol ahead + // if it is a lowercase letter, then it is not the end of match + // but the beginning of the next word. + // + // NOTE(fredbi): this heuristic sometimes leads to counterintuitive splits and + // perhaps (not sure yet) we should check against case _alternance_. + // + // Example: + // + // In the current version, in the sentence "IDS initialism", "ID" is recognized as an initialism, + // leading to a split like "id_s_initialism" (or IDSInitialism), + // whereas in the sentence "IDx initialism", it is not and produces something like + // "i_d_x_initialism" (or IDxInitialism). The generated file name is not great. + // + // Both go identifiers are tolerated by linters. + // + // Notice that the slightly different input "IDs initialism" is correctly detected + // as a pluralized initialism and produces something like "ids_initialism" (or IDsInitialism). + + if currentRunePosition < len(nameRunes)-1 { // when before the last rune + nextRune := nameRunes[currentRunePosition+1] + + // recognize a plural form for this initialism (only simple english pluralization is supported). + if nextRune == 's' && match.hasPlural == simplePlural { + // detected a pluralized initialism + match.body = append(match.body, nextRune) + lookAhead := currentRunePosition + 1 + if lookAhead < len(nameRunes)-1 { + nextRune = nameRunes[lookAhead+1] + if newWord := unicode.IsLower(nextRune); newWord { + // it is the start of a new word. + // Match is only partial and the initialism is not recognized: + // move on to the next match, but do not advance the rune position + continue + } + } + + // this is a pluralized match: keep it + currentRunePosition++ + match.complete = true + match.hasPlural = simplePlural + match.end = currentRunePosition + *newMatches = append(*newMatches, match) + + // match is complete: keep it then move on to the next match + continue + } + + // other cases + // example: invariant plural such as "TLS" + if newWord := unicode.IsLower(nextRune); newWord { + // it is the start of a new word + // Match is only partial and the initialism is not recognized : move on + continue + } + } + + match.complete = true + match.end = currentRunePosition + } + + // append the ongoing matching attempt: it is not necessarily complete, but was successful so far. + // Let's see if it still matches on the next rune. + *newMatches = append(*newMatches, match) + } + + s.findMatches(newMatches, nameRunes, currentRune, currentRunePosition) + + poolOfMatches.RedeemMatches(matches) + matches = newMatches + } + + // it is up to the caller to redeem this last slice + return matches +} + +func (s splitter) findMatches(newMatches *initialismMatches, nameRunes []rune, currentRune rune, currentRunePosition int) { + // check for new initialism matches, based on the first character + for i, r := range s.initialismsRunes { + if r[0] != currentRune { + continue + } + + if currentRunePosition+len(r) > len(nameRunes) { + continue // not eligible: would spilll over the initial string + } + + // possible matches: all initialisms starting with the current rune and that can fit the given string (nameRunes) + *newMatches = append(*newMatches, initialismMatch{ + start: currentRunePosition, + body: r, + complete: false, + hasPlural: s.initialismsPluralForm[i], + }) + } +} + +func (s splitter) mapMatchesToNameLexems(nameRunes []rune, matches *initialismMatches) *[]nameLexem { + nameLexems := poolOfLexems.BorrowLexems() + + var lastAcceptedMatch initialismMatch + for _, match := range *matches { + if !match.complete { + continue + } + + if firstMatch := lastAcceptedMatch.isZero(); firstMatch { + s.appendBrokenDownCasualString(nameLexems, nameRunes[:match.start]) + *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) + + lastAcceptedMatch = match + + continue + } + + if overlappedMatch := match.start <= lastAcceptedMatch.end; overlappedMatch { + continue + } + + middle := nameRunes[lastAcceptedMatch.end+1 : match.start] + s.appendBrokenDownCasualString(nameLexems, middle) + *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) + + lastAcceptedMatch = match + } + + // we have not found any accepted matches + if lastAcceptedMatch.isZero() { + *nameLexems = (*nameLexems)[:0] + s.appendBrokenDownCasualString(nameLexems, nameRunes) + } else if lastAcceptedMatch.end+1 != len(nameRunes) { + rest := nameRunes[lastAcceptedMatch.end+1:] + s.appendBrokenDownCasualString(nameLexems, rest) + } + + poolOfMatches.RedeemMatches(matches) + + return nameLexems +} + +func (s splitter) breakInitialism(original string) nameLexem { + return newInitialismNameLexem(original, original) +} + +func (s splitter) appendBrokenDownCasualString(segments *[]nameLexem, str []rune) { + currentSegment := poolOfBuffers.BorrowBuffer(len(str)) // unlike strings.Builder, bytes.Buffer initial storage can reused + defer func() { + poolOfBuffers.RedeemBuffer(currentSegment) + }() + + addCasualNameLexem := func(original string) { + *segments = append(*segments, newCasualNameLexem(original)) + } + + addInitialismNameLexem := func(original, match string) { + *segments = append(*segments, newInitialismNameLexem(original, match)) + } + + var addNameLexem func(string) + if s.postSplitInitialismCheck { + addNameLexem = func(original string) { + for i := range s.initialisms { + if isEqualFoldIgnoreSpace(s.initialismsUpperCased[i], original) { + addInitialismNameLexem(original, s.initialisms[i]) + + return + } + } + + addCasualNameLexem(original) + } + } else { + addNameLexem = addCasualNameLexem + } + + // NOTE: (performance). The few remaining non-amortized allocations + // lay in the code below: using String() forces + for _, rn := range str { + if replace, found := s.replaceFunc(rn); found { + if currentSegment.Len() > 0 { + addNameLexem(currentSegment.String()) + currentSegment.Reset() + } + + if replace != "" { + addNameLexem(replace) + } + + continue + } + + if !unicode.In(rn, unicode.L, unicode.M, unicode.N, unicode.Pc) { + if currentSegment.Len() > 0 { + addNameLexem(currentSegment.String()) + currentSegment.Reset() + } + + continue + } + + if unicode.IsUpper(rn) { + if currentSegment.Len() > 0 { + addNameLexem(currentSegment.String()) + } + currentSegment.Reset() + } + + currentSegment.WriteRune(rn) + } + + if currentSegment.Len() > 0 { + addNameLexem(currentSegment.String()) + } +} diff --git a/api/vendor/github.com/go-openapi/swag/string_bytes.go b/vendor/github.com/go-openapi/swag/mangling/string_bytes.go similarity index 60% rename from api/vendor/github.com/go-openapi/swag/string_bytes.go rename to vendor/github.com/go-openapi/swag/mangling/string_bytes.go index 90745d5ca9f1..28daaf72b1a1 100644 --- a/api/vendor/github.com/go-openapi/swag/string_bytes.go +++ b/vendor/github.com/go-openapi/swag/mangling/string_bytes.go @@ -1,4 +1,7 @@ -package swag +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling import "unsafe" diff --git a/vendor/github.com/go-openapi/swag/mangling/util.go b/vendor/github.com/go-openapi/swag/mangling/util.go new file mode 100644 index 000000000000..0636417e360b --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling/util.go @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package mangling + +import ( + "strings" + "unicode" + "unicode/utf8" +) + +// Removes leading whitespaces +func trim(str string) string { return strings.TrimSpace(str) } + +// upper is strings.ToUpper() combined with trim +func upper(str string) string { + return strings.ToUpper(trim(str)) +} + +// lower is strings.ToLower() combined with trim +func lower(str string) string { + return strings.ToLower(trim(str)) +} + +// isEqualFoldIgnoreSpace is the same as strings.EqualFold, but +// it ignores leading and trailing blank spaces in the compared +// string. +// +// base is assumed to be composed of upper-cased runes, and be already +// trimmed. +// +// This code is heavily inspired from strings.EqualFold. +func isEqualFoldIgnoreSpace(base []rune, str string) bool { + var i, baseIndex int + // equivalent to b := []byte(str), but without data copy + b := hackStringBytes(str) + + for i < len(b) { + if c := b[i]; c < utf8.RuneSelf { + // fast path for ASCII + if c != ' ' && c != '\t' { + break + } + i++ + + continue + } + + // unicode case + r, size := utf8.DecodeRune(b[i:]) + if !unicode.IsSpace(r) { + break + } + i += size + } + + if i >= len(b) { + return len(base) == 0 + } + + for _, baseRune := range base { + if i >= len(b) { + break + } + + if c := b[i]; c < utf8.RuneSelf { + // single byte rune case (ASCII) + if baseRune >= utf8.RuneSelf { + return false + } + + baseChar := byte(baseRune) + if c != baseChar && ((c < 'a') || (c > 'z') || (c-'a'+'A' != baseChar)) { + return false + } + + baseIndex++ + i++ + + continue + } + + // unicode case + r, size := utf8.DecodeRune(b[i:]) + if unicode.ToUpper(r) != baseRune { + return false + } + baseIndex++ + i += size + } + + if baseIndex != len(base) { + return false + } + + // all passed: now we should only have blanks + for i < len(b) { + if c := b[i]; c < utf8.RuneSelf { + // fast path for ASCII + if c != ' ' && c != '\t' { + return false + } + i++ + + continue + } + + // unicode case + r, size := utf8.DecodeRune(b[i:]) + if !unicode.IsSpace(r) { + return false + } + + i += size + } + + return true +} diff --git a/vendor/github.com/go-openapi/swag/mangling_iface.go b/vendor/github.com/go-openapi/swag/mangling_iface.go new file mode 100644 index 000000000000..98b9a9992930 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/mangling_iface.go @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/mangling" + +// GoNamePrefixFunc sets an optional rule to prefix go names +// which do not start with a letter. +// +// GoNamePrefixFunc should not be written to while concurrently using the other mangling functions of this package. +// +// Deprecated: use [mangling.WithGoNamePrefixFunc] instead. +var GoNamePrefixFunc mangling.PrefixFunc + +// swagNameMangler is a global instance of the name mangler specifically alloted +// to support deprecated functions. +var swagNameMangler = mangling.NewNameMangler( + mangling.WithGoNamePrefixFuncPtr(&GoNamePrefixFunc), +) + +// AddInitialisms adds additional initialisms to the default list (see [mangling.DefaultInitialisms]). +// +// AddInitialisms is not safe to be called concurrently. +// +// Deprecated: use [mangling.WithAdditionalInitialisms] instead. +func AddInitialisms(words ...string) { + swagNameMangler.AddInitialisms(words...) +} + +// Camelize a single word. +// +// Deprecated: use [mangling.NameMangler.Camelize] instead. +func Camelize(word string) string { return swagNameMangler.Camelize(word) } + +// ToFileName lowercases and underscores a go type name. +// +// Deprecated: use [mangling.NameMangler.ToFileName] instead. +func ToFileName(name string) string { return swagNameMangler.ToFileName(name) } + +// ToCommandName lowercases and underscores a go type name. +// +// Deprecated: use [mangling.NameMangler.ToCommandName] instead. +func ToCommandName(name string) string { return swagNameMangler.ToCommandName(name) } + +// ToHumanNameLower represents a code name as a human series of words. +// +// Deprecated: use [mangling.NameMangler.ToHumanNameLower] instead. +func ToHumanNameLower(name string) string { return swagNameMangler.ToHumanNameLower(name) } + +// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized. +// +// Deprecated: use [mangling.NameMangler.ToHumanNameTitle] instead. +func ToHumanNameTitle(name string) string { return swagNameMangler.ToHumanNameTitle(name) } + +// ToJSONName camel-cases a name which can be underscored or pascal-cased. +// +// Deprecated: use [mangling.NameMangler.ToJSONName] instead. +func ToJSONName(name string) string { return swagNameMangler.ToJSONName(name) } + +// ToVarName camel-cases a name which can be underscored or pascal-cased. +// +// Deprecated: use [mangling.NameMangler.ToVarName] instead. +func ToVarName(name string) string { return swagNameMangler.ToVarName(name) } + +// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes. +// +// Deprecated: use [mangling.NameMangler.ToGoName] instead. +func ToGoName(name string) string { return swagNameMangler.ToGoName(name) } diff --git a/vendor/github.com/go-openapi/swag/name_lexem.go b/vendor/github.com/go-openapi/swag/name_lexem.go deleted file mode 100644 index 8bb64ac32f90..000000000000 --- a/vendor/github.com/go-openapi/swag/name_lexem.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "unicode" - "unicode/utf8" -) - -type ( - lexemKind uint8 - - nameLexem struct { - original string - matchedInitialism string - kind lexemKind - } -) - -const ( - lexemKindCasualName lexemKind = iota - lexemKindInitialismName -) - -func newInitialismNameLexem(original, matchedInitialism string) nameLexem { - return nameLexem{ - kind: lexemKindInitialismName, - original: original, - matchedInitialism: matchedInitialism, - } -} - -func newCasualNameLexem(original string) nameLexem { - return nameLexem{ - kind: lexemKindCasualName, - original: original, - } -} - -func (l nameLexem) GetUnsafeGoName() string { - if l.kind == lexemKindInitialismName { - return l.matchedInitialism - } - - var ( - first rune - rest string - ) - - for i, orig := range l.original { - if i == 0 { - first = orig - continue - } - - if i > 0 { - rest = l.original[i:] - break - } - } - - if len(l.original) > 1 { - b := poolOfBuffers.BorrowBuffer(utf8.UTFMax + len(rest)) - defer func() { - poolOfBuffers.RedeemBuffer(b) - }() - b.WriteRune(unicode.ToUpper(first)) - b.WriteString(lower(rest)) - return b.String() - } - - return l.original -} - -func (l nameLexem) GetOriginal() string { - return l.original -} - -func (l nameLexem) IsInitialism() bool { - return l.kind == lexemKindInitialismName -} diff --git a/vendor/github.com/go-openapi/swag/net.go b/vendor/github.com/go-openapi/swag/net.go deleted file mode 100644 index 821235f84d4a..000000000000 --- a/vendor/github.com/go-openapi/swag/net.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "net" - "strconv" -) - -// SplitHostPort splits a network address into a host and a port. -// The port is -1 when there is no port to be found -func SplitHostPort(addr string) (host string, port int, err error) { - h, p, err := net.SplitHostPort(addr) - if err != nil { - return "", -1, err - } - if p == "" { - return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} - } - - pi, err := strconv.Atoi(p) - if err != nil { - return "", -1, err - } - return h, pi, nil -} diff --git a/vendor/github.com/go-openapi/swag/netutils/LICENSE b/vendor/github.com/go-openapi/swag/netutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/netutils/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/go-openapi/swag/netutils/doc.go b/vendor/github.com/go-openapi/swag/netutils/doc.go new file mode 100644 index 000000000000..74282f8e51c5 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/netutils/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package netutils provides helpers for network-related tasks. +package netutils diff --git a/vendor/github.com/go-openapi/swag/netutils/net.go b/vendor/github.com/go-openapi/swag/netutils/net.go new file mode 100644 index 000000000000..82a1544af7bf --- /dev/null +++ b/vendor/github.com/go-openapi/swag/netutils/net.go @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package netutils + +import ( + "net" + "strconv" +) + +// SplitHostPort splits a network address into a host and a port. +// +// The difference with the standard net.SplitHostPort is that the port is converted to an int. +// +// The port is -1 when there is no port to be found. +func SplitHostPort(addr string) (host string, port int, err error) { + h, p, err := net.SplitHostPort(addr) + if err != nil { + return "", -1, err + } + if p == "" { + return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} + } + + pi, err := strconv.Atoi(p) + if err != nil { + return "", -1, err + } + + return h, pi, nil +} diff --git a/vendor/github.com/go-openapi/swag/netutils_iface.go b/vendor/github.com/go-openapi/swag/netutils_iface.go new file mode 100644 index 000000000000..d658de25b3f3 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/netutils_iface.go @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/netutils" + +// SplitHostPort splits a network address into a host and a port. +// +// Deprecated: use [netutils.SplitHostPort] instead. +func SplitHostPort(addr string) (host string, port int, err error) { + return netutils.SplitHostPort(addr) +} diff --git a/vendor/github.com/go-openapi/swag/split.go b/vendor/github.com/go-openapi/swag/split.go deleted file mode 100644 index 274727a866c4..000000000000 --- a/vendor/github.com/go-openapi/swag/split.go +++ /dev/null @@ -1,508 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "bytes" - "sync" - "unicode" - "unicode/utf8" -) - -type ( - splitter struct { - initialisms []string - initialismsRunes [][]rune - initialismsUpperCased [][]rune // initialisms cached in their trimmed, upper-cased version - postSplitInitialismCheck bool - } - - splitterOption func(*splitter) - - initialismMatch struct { - body []rune - start, end int - complete bool - } - initialismMatches []initialismMatch -) - -type ( - // memory pools of temporary objects. - // - // These are used to recycle temporarily allocated objects - // and relieve the GC from undue pressure. - - matchesPool struct { - *sync.Pool - } - - buffersPool struct { - *sync.Pool - } - - lexemsPool struct { - *sync.Pool - } - - splittersPool struct { - *sync.Pool - } -) - -var ( - // poolOfMatches holds temporary slices for recycling during the initialism match process - poolOfMatches = matchesPool{ - Pool: &sync.Pool{ - New: func() any { - s := make(initialismMatches, 0, maxAllocMatches) - - return &s - }, - }, - } - - poolOfBuffers = buffersPool{ - Pool: &sync.Pool{ - New: func() any { - return new(bytes.Buffer) - }, - }, - } - - poolOfLexems = lexemsPool{ - Pool: &sync.Pool{ - New: func() any { - s := make([]nameLexem, 0, maxAllocMatches) - - return &s - }, - }, - } - - poolOfSplitters = splittersPool{ - Pool: &sync.Pool{ - New: func() any { - s := newSplitter() - - return &s - }, - }, - } -) - -// nameReplaceTable finds a word representation for special characters. -func nameReplaceTable(r rune) (string, bool) { - switch r { - case '@': - return "At ", true - case '&': - return "And ", true - case '|': - return "Pipe ", true - case '$': - return "Dollar ", true - case '!': - return "Bang ", true - case '-': - return "", true - case '_': - return "", true - default: - return "", false - } -} - -// split calls the splitter. -// -// Use newSplitter for more control and options -func split(str string) []string { - s := poolOfSplitters.BorrowSplitter() - lexems := s.split(str) - result := make([]string, 0, len(*lexems)) - - for _, lexem := range *lexems { - result = append(result, lexem.GetOriginal()) - } - poolOfLexems.RedeemLexems(lexems) - poolOfSplitters.RedeemSplitter(s) - - return result - -} - -func newSplitter(options ...splitterOption) splitter { - s := splitter{ - postSplitInitialismCheck: false, - initialisms: initialisms, - initialismsRunes: initialismsRunes, - initialismsUpperCased: initialismsUpperCased, - } - - for _, option := range options { - option(&s) - } - - return s -} - -// withPostSplitInitialismCheck allows to catch initialisms after main split process -func withPostSplitInitialismCheck(s *splitter) { - s.postSplitInitialismCheck = true -} - -func (p matchesPool) BorrowMatches() *initialismMatches { - s := p.Get().(*initialismMatches) - *s = (*s)[:0] // reset slice, keep allocated capacity - - return s -} - -func (p buffersPool) BorrowBuffer(size int) *bytes.Buffer { - s := p.Get().(*bytes.Buffer) - s.Reset() - - if s.Cap() < size { - s.Grow(size) - } - - return s -} - -func (p lexemsPool) BorrowLexems() *[]nameLexem { - s := p.Get().(*[]nameLexem) - *s = (*s)[:0] // reset slice, keep allocated capacity - - return s -} - -func (p splittersPool) BorrowSplitter(options ...splitterOption) *splitter { - s := p.Get().(*splitter) - s.postSplitInitialismCheck = false // reset options - for _, apply := range options { - apply(s) - } - - return s -} - -func (p matchesPool) RedeemMatches(s *initialismMatches) { - p.Put(s) -} - -func (p buffersPool) RedeemBuffer(s *bytes.Buffer) { - p.Put(s) -} - -func (p lexemsPool) RedeemLexems(s *[]nameLexem) { - p.Put(s) -} - -func (p splittersPool) RedeemSplitter(s *splitter) { - p.Put(s) -} - -func (m initialismMatch) isZero() bool { - return m.start == 0 && m.end == 0 -} - -func (s splitter) split(name string) *[]nameLexem { - nameRunes := []rune(name) - matches := s.gatherInitialismMatches(nameRunes) - if matches == nil { - return poolOfLexems.BorrowLexems() - } - - return s.mapMatchesToNameLexems(nameRunes, matches) -} - -func (s splitter) gatherInitialismMatches(nameRunes []rune) *initialismMatches { - var matches *initialismMatches - - for currentRunePosition, currentRune := range nameRunes { - // recycle these allocations as we loop over runes - // with such recycling, only 2 slices should be allocated per call - // instead of o(n). - newMatches := poolOfMatches.BorrowMatches() - - // check current initialism matches - if matches != nil { // skip first iteration - for _, match := range *matches { - if keepCompleteMatch := match.complete; keepCompleteMatch { - *newMatches = append(*newMatches, match) - continue - } - - // drop failed match - currentMatchRune := match.body[currentRunePosition-match.start] - if currentMatchRune != currentRune { - continue - } - - // try to complete ongoing match - if currentRunePosition-match.start == len(match.body)-1 { - // we are close; the next step is to check the symbol ahead - // if it is a small letter, then it is not the end of match - // but beginning of the next word - - if currentRunePosition < len(nameRunes)-1 { - nextRune := nameRunes[currentRunePosition+1] - if newWord := unicode.IsLower(nextRune); newWord { - // oh ok, it was the start of a new word - continue - } - } - - match.complete = true - match.end = currentRunePosition - } - - *newMatches = append(*newMatches, match) - } - } - - // check for new initialism matches - for i := range s.initialisms { - initialismRunes := s.initialismsRunes[i] - if initialismRunes[0] == currentRune { - *newMatches = append(*newMatches, initialismMatch{ - start: currentRunePosition, - body: initialismRunes, - complete: false, - }) - } - } - - if matches != nil { - poolOfMatches.RedeemMatches(matches) - } - matches = newMatches - } - - // up to the caller to redeem this last slice - return matches -} - -func (s splitter) mapMatchesToNameLexems(nameRunes []rune, matches *initialismMatches) *[]nameLexem { - nameLexems := poolOfLexems.BorrowLexems() - - var lastAcceptedMatch initialismMatch - for _, match := range *matches { - if !match.complete { - continue - } - - if firstMatch := lastAcceptedMatch.isZero(); firstMatch { - s.appendBrokenDownCasualString(nameLexems, nameRunes[:match.start]) - *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) - - lastAcceptedMatch = match - - continue - } - - if overlappedMatch := match.start <= lastAcceptedMatch.end; overlappedMatch { - continue - } - - middle := nameRunes[lastAcceptedMatch.end+1 : match.start] - s.appendBrokenDownCasualString(nameLexems, middle) - *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) - - lastAcceptedMatch = match - } - - // we have not found any accepted matches - if lastAcceptedMatch.isZero() { - *nameLexems = (*nameLexems)[:0] - s.appendBrokenDownCasualString(nameLexems, nameRunes) - } else if lastAcceptedMatch.end+1 != len(nameRunes) { - rest := nameRunes[lastAcceptedMatch.end+1:] - s.appendBrokenDownCasualString(nameLexems, rest) - } - - poolOfMatches.RedeemMatches(matches) - - return nameLexems -} - -func (s splitter) breakInitialism(original string) nameLexem { - return newInitialismNameLexem(original, original) -} - -func (s splitter) appendBrokenDownCasualString(segments *[]nameLexem, str []rune) { - currentSegment := poolOfBuffers.BorrowBuffer(len(str)) // unlike strings.Builder, bytes.Buffer initial storage can reused - defer func() { - poolOfBuffers.RedeemBuffer(currentSegment) - }() - - addCasualNameLexem := func(original string) { - *segments = append(*segments, newCasualNameLexem(original)) - } - - addInitialismNameLexem := func(original, match string) { - *segments = append(*segments, newInitialismNameLexem(original, match)) - } - - var addNameLexem func(string) - if s.postSplitInitialismCheck { - addNameLexem = func(original string) { - for i := range s.initialisms { - if isEqualFoldIgnoreSpace(s.initialismsUpperCased[i], original) { - addInitialismNameLexem(original, s.initialisms[i]) - - return - } - } - - addCasualNameLexem(original) - } - } else { - addNameLexem = addCasualNameLexem - } - - for _, rn := range str { - if replace, found := nameReplaceTable(rn); found { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - currentSegment.Reset() - } - - if replace != "" { - addNameLexem(replace) - } - - continue - } - - if !unicode.In(rn, unicode.L, unicode.M, unicode.N, unicode.Pc) { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - currentSegment.Reset() - } - - continue - } - - if unicode.IsUpper(rn) { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - } - currentSegment.Reset() - } - - currentSegment.WriteRune(rn) - } - - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - } -} - -// isEqualFoldIgnoreSpace is the same as strings.EqualFold, but -// it ignores leading and trailing blank spaces in the compared -// string. -// -// base is assumed to be composed of upper-cased runes, and be already -// trimmed. -// -// This code is heavily inspired from strings.EqualFold. -func isEqualFoldIgnoreSpace(base []rune, str string) bool { - var i, baseIndex int - // equivalent to b := []byte(str), but without data copy - b := hackStringBytes(str) - - for i < len(b) { - if c := b[i]; c < utf8.RuneSelf { - // fast path for ASCII - if c != ' ' && c != '\t' { - break - } - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if !unicode.IsSpace(r) { - break - } - i += size - } - - if i >= len(b) { - return len(base) == 0 - } - - for _, baseRune := range base { - if i >= len(b) { - break - } - - if c := b[i]; c < utf8.RuneSelf { - // single byte rune case (ASCII) - if baseRune >= utf8.RuneSelf { - return false - } - - baseChar := byte(baseRune) - if c != baseChar && - !('a' <= c && c <= 'z' && c-'a'+'A' == baseChar) { - return false - } - - baseIndex++ - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if unicode.ToUpper(r) != baseRune { - return false - } - baseIndex++ - i += size - } - - if baseIndex != len(base) { - return false - } - - // all passed: now we should only have blanks - for i < len(b) { - if c := b[i]; c < utf8.RuneSelf { - // fast path for ASCII - if c != ' ' && c != '\t' { - return false - } - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if !unicode.IsSpace(r) { - return false - } - - i += size - } - - return true -} diff --git a/vendor/github.com/go-openapi/swag/stringutils/LICENSE b/vendor/github.com/go-openapi/swag/stringutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/stringutils/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/go-openapi/swag/stringutils/collection_formats.go b/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go new file mode 100644 index 000000000000..28056ad25c38 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package stringutils + +import "strings" + +const ( + // collectionFormatComma = "csv" + collectionFormatSpace = "ssv" + collectionFormatTab = "tsv" + collectionFormatPipe = "pipes" + collectionFormatMulti = "multi" + + collectionFormatDefaultSep = "," +) + +// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute): +// +// ssv: space separated value +// tsv: tab separated value +// pipes: pipe (|) separated value +// csv: comma separated value (default) +func JoinByFormat(data []string, format string) []string { + if len(data) == 0 { + return data + } + var sep string + switch format { + case collectionFormatSpace: + sep = " " + case collectionFormatTab: + sep = "\t" + case collectionFormatPipe: + sep = "|" + case collectionFormatMulti: + return data + default: + sep = collectionFormatDefaultSep + } + return []string{strings.Join(data, sep)} +} + +// SplitByFormat splits a string by a known format: +// +// ssv: space separated value +// tsv: tab separated value +// pipes: pipe (|) separated value +// csv: comma separated value (default) +func SplitByFormat(data, format string) []string { + if data == "" { + return nil + } + var sep string + switch format { + case collectionFormatSpace: + sep = " " + case collectionFormatTab: + sep = "\t" + case collectionFormatPipe: + sep = "|" + case collectionFormatMulti: + return nil + default: + sep = collectionFormatDefaultSep + } + var result []string + for _, s := range strings.Split(data, sep) { + if ts := strings.TrimSpace(s); ts != "" { + result = append(result, ts) + } + } + return result +} diff --git a/vendor/github.com/go-openapi/swag/stringutils/doc.go b/vendor/github.com/go-openapi/swag/stringutils/doc.go new file mode 100644 index 000000000000..c6d17a1160bd --- /dev/null +++ b/vendor/github.com/go-openapi/swag/stringutils/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package stringutils exposes helpers to search and process strings. +package stringutils diff --git a/vendor/github.com/go-openapi/swag/stringutils/strings.go b/vendor/github.com/go-openapi/swag/stringutils/strings.go new file mode 100644 index 000000000000..cd792b7d0834 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/stringutils/strings.go @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package stringutils + +import ( + "slices" + "strings" +) + +// ContainsStrings searches a slice of strings for a case-sensitive match +// +// Now equivalent to the standard library [slice.Contains]. +func ContainsStrings(coll []string, item string) bool { + return slices.Contains(coll, item) +} + +// ContainsStringsCI searches a slice of strings for a case-insensitive match +func ContainsStringsCI(coll []string, item string) bool { + return slices.ContainsFunc(coll, func(e string) bool { + return strings.EqualFold(e, item) + }) +} diff --git a/vendor/github.com/go-openapi/swag/stringutils_iface.go b/vendor/github.com/go-openapi/swag/stringutils_iface.go new file mode 100644 index 000000000000..dbfa48484306 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/stringutils_iface.go @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/stringutils" + +// ContainsStrings searches a slice of strings for a case-sensitive match. +// +// Deprecated: use [slices.Contains] or [stringutils.ContainsStrings] instead. +func ContainsStrings(coll []string, item string) bool { + return stringutils.ContainsStrings(coll, item) +} + +// ContainsStringsCI searches a slice of strings for a case-insensitive match. +// +// Deprecated: use [stringutils.ContainsStringsCI] instead. +func ContainsStringsCI(coll []string, item string) bool { + return stringutils.ContainsStringsCI(coll, item) +} + +// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute). +// +// Deprecated: use [stringutils.JoinByFormat] instead. +func JoinByFormat(data []string, format string) []string { + return stringutils.JoinByFormat(data, format) +} + +// SplitByFormat splits a string by a known format. +// +// Deprecated: use [stringutils.SplitByFormat] instead. +func SplitByFormat(data, format string) []string { + return stringutils.SplitByFormat(data, format) +} diff --git a/vendor/github.com/go-openapi/swag/typeutils/LICENSE b/vendor/github.com/go-openapi/swag/typeutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/typeutils/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/go-openapi/swag/typeutils/doc.go b/vendor/github.com/go-openapi/swag/typeutils/doc.go new file mode 100644 index 000000000000..66bed20dff0e --- /dev/null +++ b/vendor/github.com/go-openapi/swag/typeutils/doc.go @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package typeutils exposes utilities to inspect generic types. +package typeutils diff --git a/vendor/github.com/go-openapi/swag/typeutils/types.go b/vendor/github.com/go-openapi/swag/typeutils/types.go new file mode 100644 index 000000000000..55487a673c4b --- /dev/null +++ b/vendor/github.com/go-openapi/swag/typeutils/types.go @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package typeutils + +import "reflect" + +type zeroable interface { + IsZero() bool +} + +// 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 any) bool { + v := reflect.ValueOf(data) + // check for nil data + switch v.Kind() { //nolint:exhaustive + case + reflect.Interface, + reflect.Func, + reflect.Chan, + reflect.Pointer, + reflect.UnsafePointer, + reflect.Map, + 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 + switch v.Kind() { //nolint:exhaustive + case reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Struct, reflect.Array: + return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) + case reflect.Invalid: + return true + default: + return false + } +} + +// IsNil checks if input is nil. +// +// For types chan, func, interface, map, pointer, or slice it returns true if its argument is nil. +// +// See [reflect.Value.IsNil]. +func IsNil(input any) bool { + if input == nil { + return true + } + + kind := reflect.TypeOf(input).Kind() + switch kind { //nolint:exhaustive + case reflect.Pointer, + reflect.UnsafePointer, + reflect.Map, + reflect.Slice, + reflect.Chan, + reflect.Interface, + reflect.Func: + return reflect.ValueOf(input).IsNil() + default: + return false + } +} diff --git a/vendor/github.com/go-openapi/swag/typeutils_iface.go b/vendor/github.com/go-openapi/swag/typeutils_iface.go new file mode 100644 index 000000000000..b63813ea408e --- /dev/null +++ b/vendor/github.com/go-openapi/swag/typeutils_iface.go @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import "github.com/go-openapi/swag/typeutils" + +// IsZero returns true when the value passed into the function is a zero value. +// This allows for safer checking of interface values. +// +// Deprecated: use [typeutils.IsZero] instead. +func IsZero(data any) bool { return typeutils.IsZero(data) } diff --git a/vendor/github.com/go-openapi/swag/util.go b/vendor/github.com/go-openapi/swag/util.go deleted file mode 100644 index 5051401c49ff..000000000000 --- a/vendor/github.com/go-openapi/swag/util.go +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "reflect" - "strings" - "unicode" - "unicode/utf8" -) - -// GoNamePrefixFunc sets an optional rule to prefix go names -// which do not start with a letter. -// -// The prefix function is assumed to return a string that starts with an upper case letter. -// -// e.g. to help convert "123" into "{prefix}123" -// -// The default is to prefix with "X" -var GoNamePrefixFunc func(string) string - -func prefixFunc(name, in string) string { - if GoNamePrefixFunc == nil { - return "X" + in - } - - return GoNamePrefixFunc(name) + in -} - -const ( - // collectionFormatComma = "csv" - collectionFormatSpace = "ssv" - collectionFormatTab = "tsv" - collectionFormatPipe = "pipes" - collectionFormatMulti = "multi" -) - -// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute): -// -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func JoinByFormat(data []string, format string) []string { - if len(data) == 0 { - return data - } - var sep string - switch format { - case collectionFormatSpace: - sep = " " - case collectionFormatTab: - sep = "\t" - case collectionFormatPipe: - sep = "|" - case collectionFormatMulti: - return data - default: - sep = "," - } - return []string{strings.Join(data, sep)} -} - -// SplitByFormat splits a string by a known format: -// -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func SplitByFormat(data, format string) []string { - if data == "" { - return nil - } - var sep string - switch format { - case collectionFormatSpace: - sep = " " - case collectionFormatTab: - sep = "\t" - case collectionFormatPipe: - sep = "|" - case collectionFormatMulti: - return nil - default: - sep = "," - } - var result []string - for _, s := range strings.Split(data, sep) { - if ts := strings.TrimSpace(s); ts != "" { - result = append(result, ts) - } - } - return result -} - -// Removes leading whitespaces -func trim(str string) string { - return strings.TrimSpace(str) -} - -// Shortcut to strings.ToUpper() -func upper(str string) string { - return strings.ToUpper(trim(str)) -} - -// Shortcut to strings.ToLower() -func lower(str string) string { - return strings.ToLower(trim(str)) -} - -// Camelize an uppercased word -func Camelize(word string) string { - camelized := poolOfBuffers.BorrowBuffer(len(word)) - defer func() { - poolOfBuffers.RedeemBuffer(camelized) - }() - - for pos, ru := range []rune(word) { - if pos > 0 { - camelized.WriteRune(unicode.ToLower(ru)) - } else { - camelized.WriteRune(unicode.ToUpper(ru)) - } - } - return camelized.String() -} - -// ToFileName lowercases and underscores a go type name -func ToFileName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for _, w := range in { - out = append(out, lower(w)) - } - - return strings.Join(out, "_") -} - -// ToCommandName lowercases and underscores a go type name -func ToCommandName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for _, w := range in { - out = append(out, lower(w)) - } - return strings.Join(out, "-") -} - -// ToHumanNameLower represents a code name as a human series of words -func ToHumanNameLower(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - in := s.split(name) - poolOfSplitters.RedeemSplitter(s) - out := make([]string, 0, len(*in)) - - for _, w := range *in { - if !w.IsInitialism() { - out = append(out, lower(w.GetOriginal())) - } else { - out = append(out, trim(w.GetOriginal())) - } - } - poolOfLexems.RedeemLexems(in) - - return strings.Join(out, " ") -} - -// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized -func ToHumanNameTitle(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - in := s.split(name) - poolOfSplitters.RedeemSplitter(s) - - out := make([]string, 0, len(*in)) - for _, w := range *in { - original := trim(w.GetOriginal()) - if !w.IsInitialism() { - out = append(out, Camelize(original)) - } else { - out = append(out, original) - } - } - poolOfLexems.RedeemLexems(in) - - return strings.Join(out, " ") -} - -// ToJSONName camelcases a name which can be underscored or pascal cased -func ToJSONName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for i, w := range in { - if i == 0 { - out = append(out, lower(w)) - continue - } - out = append(out, Camelize(trim(w))) - } - return strings.Join(out, "") -} - -// ToVarName camelcases a name which can be underscored or pascal cased -func ToVarName(name string) string { - res := ToGoName(name) - if isInitialism(res) { - return lower(res) - } - if len(res) <= 1 { - return lower(res) - } - return lower(res[:1]) + res[1:] -} - -// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes -func ToGoName(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - lexems := s.split(name) - poolOfSplitters.RedeemSplitter(s) - defer func() { - poolOfLexems.RedeemLexems(lexems) - }() - lexemes := *lexems - - if len(lexemes) == 0 { - return "" - } - - result := poolOfBuffers.BorrowBuffer(len(name)) - defer func() { - poolOfBuffers.RedeemBuffer(result) - }() - - // check if not starting with a letter, upper case - firstPart := lexemes[0].GetUnsafeGoName() - if lexemes[0].IsInitialism() { - firstPart = upper(firstPart) - } - - if c := firstPart[0]; c < utf8.RuneSelf { - // ASCII - switch { - case 'A' <= c && c <= 'Z': - result.WriteString(firstPart) - case 'a' <= c && c <= 'z': - result.WriteByte(c - 'a' + 'A') - result.WriteString(firstPart[1:]) - default: - result.WriteString(prefixFunc(name, firstPart)) - // NOTE: no longer check if prefixFunc returns a string that starts with uppercase: - // assume this is always the case - } - } else { - // unicode - firstRune, _ := utf8.DecodeRuneInString(firstPart) - switch { - case !unicode.IsLetter(firstRune): - result.WriteString(prefixFunc(name, firstPart)) - case !unicode.IsUpper(firstRune): - result.WriteString(prefixFunc(name, firstPart)) - /* - result.WriteRune(unicode.ToUpper(firstRune)) - result.WriteString(firstPart[offset:]) - */ - default: - result.WriteString(firstPart) - } - } - - for _, lexem := range lexemes[1:] { - goName := lexem.GetUnsafeGoName() - - // to support old behavior - if lexem.IsInitialism() { - goName = upper(goName) - } - result.WriteString(goName) - } - - return result.String() -} - -// ContainsStrings searches a slice of strings for a case-sensitive match -func ContainsStrings(coll []string, item string) bool { - for _, a := range coll { - if a == item { - return true - } - } - return false -} - -// ContainsStringsCI searches a slice of strings for a case-insensitive match -func ContainsStringsCI(coll []string, item string) bool { - for _, a := range coll { - if strings.EqualFold(a, item) { - return true - } - } - return false -} - -type zeroable interface { - IsZero() bool -} - -// 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() { //nolint:exhaustive - 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 - switch v.Kind() { //nolint:exhaustive - case reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Struct, reflect.Array: - return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) - case reflect.Invalid: - return true - default: - return false - } -} - -// CommandLineOptionsGroup represents a group of user-defined command line options -type CommandLineOptionsGroup struct { - ShortDescription string - LongDescription string - Options interface{} -} diff --git a/vendor/github.com/go-openapi/swag/yaml.go b/vendor/github.com/go-openapi/swag/yaml.go deleted file mode 100644 index 575346539ac8..000000000000 --- a/vendor/github.com/go-openapi/swag/yaml.go +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "encoding/json" - "fmt" - "path/filepath" - "reflect" - "sort" - "strconv" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" - yaml "gopkg.in/yaml.v3" -) - -// YAMLMatcher matches yaml -func YAMLMatcher(path string) bool { - ext := filepath.Ext(path) - return ext == ".yaml" || ext == ".yml" -} - -// YAMLToJSON converts YAML unmarshaled data into json compatible data -func YAMLToJSON(data interface{}) (json.RawMessage, error) { - jm, err := transformData(data) - if err != nil { - return nil, err - } - b, err := WriteJSON(jm) - return json.RawMessage(b), err -} - -// BytesToYAMLDoc converts a byte slice into a YAML document -func BytesToYAMLDoc(data []byte) (interface{}, error) { - var document yaml.Node // preserve order that is present in the document - if err := yaml.Unmarshal(data, &document); err != nil { - return nil, err - } - if document.Kind != yaml.DocumentNode || len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { - return nil, fmt.Errorf("only YAML documents that are objects are supported: %w", ErrYAML) - } - return &document, nil -} - -func yamlNode(root *yaml.Node) (interface{}, error) { - switch root.Kind { - case yaml.DocumentNode: - return yamlDocument(root) - case yaml.SequenceNode: - return yamlSequence(root) - case yaml.MappingNode: - return yamlMapping(root) - case yaml.ScalarNode: - return yamlScalar(root) - case yaml.AliasNode: - return yamlNode(root.Alias) - default: - return nil, fmt.Errorf("unsupported YAML node type: %v: %w", root.Kind, ErrYAML) - } -} - -func yamlDocument(node *yaml.Node) (interface{}, error) { - if len(node.Content) != 1 { - return nil, fmt.Errorf("unexpected YAML Document node content length: %d: %w", len(node.Content), ErrYAML) - } - return yamlNode(node.Content[0]) -} - -func yamlMapping(node *yaml.Node) (interface{}, error) { - const sensibleAllocDivider = 2 - m := make(JSONMapSlice, len(node.Content)/sensibleAllocDivider) - - var j int - for i := 0; i < len(node.Content); i += 2 { - var nmi JSONMapItem - k, err := yamlStringScalarC(node.Content[i]) - if err != nil { - return nil, fmt.Errorf("unable to decode YAML map key: %w: %w", err, ErrYAML) - } - nmi.Key = k - v, err := yamlNode(node.Content[i+1]) - if err != nil { - return nil, fmt.Errorf("unable to process YAML map value for key %q: %w: %w", k, err, ErrYAML) - } - nmi.Value = v - m[j] = nmi - j++ - } - return m, nil -} - -func yamlSequence(node *yaml.Node) (interface{}, error) { - s := make([]interface{}, 0) - - for i := 0; i < len(node.Content); i++ { - - v, err := yamlNode(node.Content[i]) - if err != nil { - return nil, fmt.Errorf("unable to decode YAML sequence value: %w: %w", err, ErrYAML) - } - s = append(s, v) - } - return s, nil -} - -const ( // See https://yaml.org/type/ - yamlStringScalar = "tag:yaml.org,2002:str" - yamlIntScalar = "tag:yaml.org,2002:int" - yamlBoolScalar = "tag:yaml.org,2002:bool" - yamlFloatScalar = "tag:yaml.org,2002:float" - yamlTimestamp = "tag:yaml.org,2002:timestamp" - yamlNull = "tag:yaml.org,2002:null" -) - -func yamlScalar(node *yaml.Node) (interface{}, error) { - switch node.LongTag() { - case yamlStringScalar: - return node.Value, nil - case yamlBoolScalar: - b, err := strconv.ParseBool(node.Value) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting bool content: %w: %w", node.Value, err, ErrYAML) - } - return b, nil - case yamlIntScalar: - i, err := strconv.ParseInt(node.Value, 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting integer content: %w: %w", node.Value, err, ErrYAML) - } - return i, nil - case yamlFloatScalar: - f, err := strconv.ParseFloat(node.Value, 64) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting float content: %w: %w", node.Value, err, ErrYAML) - } - return f, nil - case yamlTimestamp: - return node.Value, nil - case yamlNull: - return nil, nil //nolint:nilnil - default: - return nil, fmt.Errorf("YAML tag %q is not supported: %w", node.LongTag(), ErrYAML) - } -} - -func yamlStringScalarC(node *yaml.Node) (string, error) { - if node.Kind != yaml.ScalarNode { - return "", fmt.Errorf("expecting a string scalar but got %q: %w", node.Kind, ErrYAML) - } - switch node.LongTag() { - case yamlStringScalar, yamlIntScalar, yamlFloatScalar: - return node.Value, nil - default: - return "", fmt.Errorf("YAML tag %q is not supported as map key: %w", node.LongTag(), ErrYAML) - } -} - -// JSONMapSlice represent a JSON object, with the order of keys maintained -type JSONMapSlice []JSONMapItem - -// MarshalJSON renders a JSONMapSlice as JSON -func (s JSONMapSlice) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -// MarshalEasyJSON renders a JSONMapSlice as JSON, using easyJSON -func (s JSONMapSlice) MarshalEasyJSON(w *jwriter.Writer) { - w.RawByte('{') - - ln := len(s) - last := ln - 1 - for i := 0; i < ln; i++ { - s[i].MarshalEasyJSON(w) - if i != last { // last item - w.RawByte(',') - } - } - - w.RawByte('}') -} - -// UnmarshalJSON makes a JSONMapSlice from JSON -func (s *JSONMapSlice) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON makes a JSONMapSlice from JSON, using easyJSON -func (s *JSONMapSlice) UnmarshalEasyJSON(in *jlexer.Lexer) { - if in.IsNull() { - in.Skip() - return - } - - var result JSONMapSlice - in.Delim('{') - for !in.IsDelim('}') { - var mi JSONMapItem - mi.UnmarshalEasyJSON(in) - result = append(result, mi) - } - *s = result -} - -func (s JSONMapSlice) MarshalYAML() (interface{}, error) { - var n yaml.Node - n.Kind = yaml.DocumentNode - var nodes []*yaml.Node - for _, item := range s { - nn, err := json2yaml(item.Value) - if err != nil { - return nil, err - } - ns := []*yaml.Node{ - { - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: item.Key, - }, - nn, - } - nodes = append(nodes, ns...) - } - - n.Content = []*yaml.Node{ - { - Kind: yaml.MappingNode, - Content: nodes, - }, - } - - return yaml.Marshal(&n) -} - -func isNil(input interface{}) bool { - if input == nil { - return true - } - kind := reflect.TypeOf(input).Kind() - switch kind { //nolint:exhaustive - case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: - return reflect.ValueOf(input).IsNil() - default: - return false - } -} - -func json2yaml(item interface{}) (*yaml.Node, error) { - if isNil(item) { - return &yaml.Node{ - Kind: yaml.ScalarNode, - Value: "null", - }, nil - } - - switch val := item.(type) { - case JSONMapSlice: - var n yaml.Node - n.Kind = yaml.MappingNode - for i := range val { - childNode, err := json2yaml(&val[i].Value) - if err != nil { - return nil, err - } - n.Content = append(n.Content, &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: val[i].Key, - }, childNode) - } - return &n, nil - case map[string]interface{}: - var n yaml.Node - n.Kind = yaml.MappingNode - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - v := val[k] - childNode, err := json2yaml(v) - if err != nil { - return nil, err - } - n.Content = append(n.Content, &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: k, - }, childNode) - } - return &n, nil - case []interface{}: - var n yaml.Node - n.Kind = yaml.SequenceNode - for i := range val { - childNode, err := json2yaml(val[i]) - if err != nil { - return nil, err - } - n.Content = append(n.Content, childNode) - } - return &n, nil - case string: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: val, - }, nil - case float64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlFloatScalar, - Value: strconv.FormatFloat(val, 'f', -1, 64), - }, nil - case int64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlIntScalar, - Value: strconv.FormatInt(val, 10), - }, nil - case uint64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlIntScalar, - Value: strconv.FormatUint(val, 10), - }, nil - case bool: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlBoolScalar, - Value: strconv.FormatBool(val), - }, nil - default: - return nil, fmt.Errorf("unhandled type: %T: %w", val, ErrYAML) - } -} - -// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice -type JSONMapItem struct { - Key string - Value interface{} -} - -// MarshalJSON renders a JSONMapItem as JSON -func (s JSONMapItem) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -// MarshalEasyJSON renders a JSONMapItem as JSON, using easyJSON -func (s JSONMapItem) MarshalEasyJSON(w *jwriter.Writer) { - w.String(s.Key) - w.RawByte(':') - w.Raw(WriteJSON(s.Value)) -} - -// UnmarshalJSON makes a JSONMapItem from JSON -func (s *JSONMapItem) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON makes a JSONMapItem from JSON, using easyJSON -func (s *JSONMapItem) UnmarshalEasyJSON(in *jlexer.Lexer) { - key := in.UnsafeString() - in.WantColon() - value := in.Interface() - in.WantComma() - s.Key = key - s.Value = value -} - -func transformData(input interface{}) (out interface{}, err error) { - format := func(t interface{}) (string, error) { - switch k := t.(type) { - case string: - return k, nil - case uint: - return strconv.FormatUint(uint64(k), 10), nil - case uint8: - return strconv.FormatUint(uint64(k), 10), nil - case uint16: - return strconv.FormatUint(uint64(k), 10), nil - case uint32: - return strconv.FormatUint(uint64(k), 10), nil - case uint64: - return strconv.FormatUint(k, 10), nil - case int: - return strconv.Itoa(k), nil - case int8: - return strconv.FormatInt(int64(k), 10), nil - case int16: - return strconv.FormatInt(int64(k), 10), nil - case int32: - return strconv.FormatInt(int64(k), 10), nil - case int64: - return strconv.FormatInt(k, 10), nil - default: - return "", fmt.Errorf("unexpected map key type, got: %T: %w", k, ErrYAML) - } - } - - switch in := input.(type) { - case yaml.Node: - return yamlNode(&in) - case *yaml.Node: - return yamlNode(in) - case map[interface{}]interface{}: - o := make(JSONMapSlice, 0, len(in)) - for ke, va := range in { - var nmi JSONMapItem - if nmi.Key, err = format(ke); err != nil { - return nil, err - } - - v, ert := transformData(va) - if ert != nil { - return nil, ert - } - nmi.Value = v - o = append(o, nmi) - } - return o, nil - case []interface{}: - len1 := len(in) - o := make([]interface{}, len1) - for i := 0; i < len1; i++ { - o[i], err = transformData(in[i]) - if err != nil { - return nil, err - } - } - return o, nil - } - return input, nil -} - -// YAMLDoc loads a yaml document from either http or a file and converts it to json -func YAMLDoc(path string) (json.RawMessage, error) { - yamlDoc, err := YAMLData(path) - if err != nil { - return nil, err - } - - data, err := YAMLToJSON(yamlDoc) - if err != nil { - return nil, err - } - - return data, nil -} - -// YAMLData loads a yaml document from either http or a file -func YAMLData(path string) (interface{}, error) { - data, err := LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - - return BytesToYAMLDoc(data) -} diff --git a/vendor/github.com/go-openapi/swag/yamlutils/LICENSE b/vendor/github.com/go-openapi/swag/yamlutils/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/yamlutils/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/go-openapi/swag/yamlutils/doc.go b/vendor/github.com/go-openapi/swag/yamlutils/doc.go new file mode 100644 index 000000000000..7bb92a82f1b0 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/yamlutils/doc.go @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package yamlutils provides utilities to work with YAML documents. +// +// - [BytesToYAMLDoc] to construct a [yaml.Node] document +// - [YAMLToJSON] to convert a [yaml.Node] document to JSON bytes +// - [YAMLMapSlice] to serialize and deserialize YAML with the order of keys maintained +package yamlutils + +import ( + _ "go.yaml.in/yaml/v3" // for documentation purpose only +) diff --git a/vendor/github.com/go-openapi/swag/yamlutils/errors.go b/vendor/github.com/go-openapi/swag/yamlutils/errors.go new file mode 100644 index 000000000000..e87bc5e8beb3 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/yamlutils/errors.go @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package yamlutils + +type yamlError string + +const ( + // ErrYAML is an error raised by YAML utilities + ErrYAML yamlError = "yaml error" +) + +func (e yamlError) Error() string { + return string(e) +} diff --git a/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go b/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go new file mode 100644 index 000000000000..3daf68dbba0c --- /dev/null +++ b/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go @@ -0,0 +1,316 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package yamlutils + +import ( + "fmt" + "iter" + "slices" + "sort" + "strconv" + + "github.com/go-openapi/swag/conv" + "github.com/go-openapi/swag/jsonutils" + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" + "github.com/go-openapi/swag/typeutils" + yaml "go.yaml.in/yaml/v3" +) + +var ( + _ yaml.Marshaler = YAMLMapSlice{} + _ yaml.Unmarshaler = &YAMLMapSlice{} +) + +// YAMLMapSlice represents a YAML object, with the order of keys maintained. +// +// It is similar to [jsonutils.JSONMapSlice] and also knows how to marshal and unmarshal YAML. +// +// It behaves like an ordered map, but keys can't be accessed in constant time. +type YAMLMapSlice []YAMLMapItem + +// YAMLMapItem represents the value of a key in a YAML object held by [YAMLMapSlice]. +// +// It is entirely equivalent to [jsonutils.JSONMapItem], with the same limitation that +// you should not Marshal or Unmarshal directly this type, outside of a [YAMLMapSlice]. +type YAMLMapItem = jsonutils.JSONMapItem + +func (s YAMLMapSlice) OrderedItems() iter.Seq2[string, any] { + return func(yield func(string, any) bool) { + for _, item := range s { + if !yield(item.Key, item.Value) { + return + } + } + } +} + +// SetOrderedItems implements [ifaces.SetOrdered]: it merges keys passed by the iterator argument +// into the [YAMLMapSlice]. +func (s *YAMLMapSlice) SetOrderedItems(items iter.Seq2[string, any]) { + if items == nil { + // force receiver to be a nil slice + *s = nil + + return + } + + m := *s + if len(m) > 0 { + // update mode: short-circuited when unmarshaling fresh data structures + idx := make(map[string]int, len(m)) + + for i, item := range m { + idx[item.Key] = i + } + + for k, v := range items { + idx, ok := idx[k] + if ok { + m[idx].Value = v + + continue + } + + m = append(m, YAMLMapItem{Key: k, Value: v}) + } + + *s = m + + return + } + + for k, v := range items { + m = append(m, YAMLMapItem{Key: k, Value: v}) + } + + *s = m +} + +// MarshalJSON renders this YAML object as JSON bytes. +// +// The difference with standard JSON marshaling is that the order of keys is maintained. +func (s YAMLMapSlice) MarshalJSON() ([]byte, error) { + return jsonutils.JSONMapSlice(s).MarshalJSON() +} + +// UnmarshalJSON builds this YAML object from JSON bytes. +// +// The difference with standard JSON marshaling is that the order of keys is maintained. +func (s *YAMLMapSlice) UnmarshalJSON(data []byte) error { + js := jsonutils.JSONMapSlice(*s) + + if err := js.UnmarshalJSON(data); err != nil { + return err + } + + *s = YAMLMapSlice(js) + + return nil +} + +// MarshalYAML produces a YAML document as bytes +// +// The difference with standard YAML marshaling is that the order of keys is maintained. +// +// It implements [yaml.Marshaler]. +func (s YAMLMapSlice) MarshalYAML() (any, error) { + if typeutils.IsNil(s) { + return []byte("null\n"), nil + } + var n yaml.Node + n.Kind = yaml.DocumentNode + var nodes []*yaml.Node + + for _, item := range s { + nn, err := json2yaml(item.Value) + if err != nil { + return nil, err + } + + ns := []*yaml.Node{ + { + Kind: yaml.ScalarNode, + Tag: yamlStringScalar, + Value: item.Key, + }, + nn, + } + nodes = append(nodes, ns...) + } + + n.Content = []*yaml.Node{ + { + Kind: yaml.MappingNode, + Content: nodes, + }, + } + + return yaml.Marshal(&n) +} + +// UnmarshalYAML builds a YAMLMapSlice object from a YAML document [yaml.Node]. +// +// It implements [yaml.Unmarshaler]. +func (s *YAMLMapSlice) UnmarshalYAML(node *yaml.Node) error { + if typeutils.IsNil(*s) { + // allow to unmarshal with a simple var declaration (nil slice) + *s = YAMLMapSlice{} + } + if node == nil { + *s = nil + return nil + } + + const sensibleAllocDivider = 2 + m := slices.Grow(*s, len(node.Content)/sensibleAllocDivider) + m = m[:0] + + for i := 0; i < len(node.Content); i += 2 { + var nmi YAMLMapItem + k, err := yamlStringScalarC(node.Content[i]) + if err != nil { + return fmt.Errorf("unable to decode YAML map key: %w: %w", err, ErrYAML) + } + nmi.Key = k + v, err := yamlNode(node.Content[i+1]) + if err != nil { + return fmt.Errorf("unable to process YAML map value for key %q: %w: %w", k, err, ErrYAML) + } + nmi.Value = v + m = append(m, nmi) + } + + *s = m + + return nil +} + +func json2yaml(item any) (*yaml.Node, error) { + if typeutils.IsNil(item) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Value: "null", + }, nil + } + + switch val := item.(type) { + case ifaces.Ordered: + return orderedYAML(val) + + case map[string]any: + var n yaml.Node + n.Kind = yaml.MappingNode + keys := make([]string, 0, len(val)) + for k := range val { + keys = append(keys, k) + } + sort.Strings(keys) + + for _, k := range keys { + v := val[k] + childNode, err := json2yaml(v) + if err != nil { + return nil, err + } + n.Content = append(n.Content, &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlStringScalar, + Value: k, + }, childNode) + } + return &n, nil + + case []any: + var n yaml.Node + n.Kind = yaml.SequenceNode + for i := range val { + childNode, err := json2yaml(val[i]) + if err != nil { + return nil, err + } + n.Content = append(n.Content, childNode) + } + return &n, nil + case string: + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlStringScalar, + Value: val, + }, nil + case float32: + return floatNode(val) + case float64: + return floatNode(val) + case int: + return integerNode(val) + case int8: + return integerNode(val) + case int16: + return integerNode(val) + case int32: + return integerNode(val) + case int64: + return integerNode(val) + case uint: + return uintegerNode(val) + case uint8: + return uintegerNode(val) + case uint16: + return uintegerNode(val) + case uint32: + return uintegerNode(val) + case uint64: + return uintegerNode(val) + case bool: + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlBoolScalar, + Value: strconv.FormatBool(val), + }, nil + default: + return nil, fmt.Errorf("unhandled type: %T: %w", val, ErrYAML) + } +} + +func floatNode[T conv.Float](val T) (*yaml.Node, error) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlFloatScalar, + Value: conv.FormatFloat(val), + }, nil +} + +func integerNode[T conv.Signed](val T) (*yaml.Node, error) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlIntScalar, + Value: conv.FormatInteger(val), + }, nil +} + +func uintegerNode[T conv.Unsigned](val T) (*yaml.Node, error) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlIntScalar, + Value: conv.FormatUinteger(val), + }, nil +} + +func orderedYAML[T ifaces.Ordered](val T) (*yaml.Node, error) { + var n yaml.Node + n.Kind = yaml.MappingNode + for key, value := range val.OrderedItems() { + childNode, err := json2yaml(value) + if err != nil { + return nil, err + } + + n.Content = append(n.Content, &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: yamlStringScalar, + Value: key, + }, childNode) + } + return &n, nil +} diff --git a/vendor/github.com/go-openapi/swag/yamlutils/yaml.go b/vendor/github.com/go-openapi/swag/yamlutils/yaml.go new file mode 100644 index 000000000000..e3aff3c2fde9 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/yamlutils/yaml.go @@ -0,0 +1,211 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package yamlutils + +import ( + json "encoding/json" + "fmt" + "strconv" + + "github.com/go-openapi/swag/jsonutils" + yaml "go.yaml.in/yaml/v3" +) + +// YAMLToJSON converts a YAML document into JSON bytes. +// +// Note: a YAML document is the output from a [yaml.Marshaler], e.g a pointer to a [yaml.Node]. +// +// [YAMLToJSON] is typically called after [BytesToYAMLDoc]. +func YAMLToJSON(value any) (json.RawMessage, error) { + jm, err := transformData(value) + if err != nil { + return nil, err + } + + b, err := jsonutils.WriteJSON(jm) + + return json.RawMessage(b), err +} + +// BytesToYAMLDoc converts a byte slice into a YAML document. +// +// This function only supports root documents that are objects. +// +// A YAML document is a pointer to a [yaml.Node]. +func BytesToYAMLDoc(data []byte) (any, error) { + var document yaml.Node // preserve order that is present in the document + if err := yaml.Unmarshal(data, &document); err != nil { + return nil, err + } + if document.Kind != yaml.DocumentNode || len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { + return nil, fmt.Errorf("only YAML documents that are objects are supported: %w", ErrYAML) + } + return &document, nil +} + +func yamlNode(root *yaml.Node) (any, error) { + switch root.Kind { + case yaml.DocumentNode: + return yamlDocument(root) + case yaml.SequenceNode: + return yamlSequence(root) + case yaml.MappingNode: + return yamlMapping(root) + case yaml.ScalarNode: + return yamlScalar(root) + case yaml.AliasNode: + return yamlNode(root.Alias) + default: + return nil, fmt.Errorf("unsupported YAML node type: %v: %w", root.Kind, ErrYAML) + } +} + +func yamlDocument(node *yaml.Node) (any, error) { + if len(node.Content) != 1 { + return nil, fmt.Errorf("unexpected YAML Document node content length: %d: %w", len(node.Content), ErrYAML) + } + return yamlNode(node.Content[0]) +} + +func yamlMapping(node *yaml.Node) (any, error) { + const sensibleAllocDivider = 2 // nodes concatenate (key,value) sequences + m := make(YAMLMapSlice, len(node.Content)/sensibleAllocDivider) + + if err := m.UnmarshalYAML(node); err != nil { + return nil, err + } + + return m, nil +} + +func yamlSequence(node *yaml.Node) (any, error) { + s := make([]any, 0) + + for i := range len(node.Content) { + v, err := yamlNode(node.Content[i]) + if err != nil { + return nil, fmt.Errorf("unable to decode YAML sequence value: %w: %w", err, ErrYAML) + } + s = append(s, v) + } + return s, nil +} + +const ( // See https://yaml.org/type/ + yamlStringScalar = "tag:yaml.org,2002:str" + yamlIntScalar = "tag:yaml.org,2002:int" + yamlBoolScalar = "tag:yaml.org,2002:bool" + yamlFloatScalar = "tag:yaml.org,2002:float" + yamlTimestamp = "tag:yaml.org,2002:timestamp" + yamlNull = "tag:yaml.org,2002:null" +) + +func yamlScalar(node *yaml.Node) (any, error) { + switch node.LongTag() { + case yamlStringScalar: + return node.Value, nil + case yamlBoolScalar: + b, err := strconv.ParseBool(node.Value) + if err != nil { + return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting bool content: %w: %w", node.Value, err, ErrYAML) + } + return b, nil + case yamlIntScalar: + i, err := strconv.ParseInt(node.Value, 10, 64) + if err != nil { + return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting integer content: %w: %w", node.Value, err, ErrYAML) + } + return i, nil + case yamlFloatScalar: + f, err := strconv.ParseFloat(node.Value, 64) + if err != nil { + return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting float content: %w: %w", node.Value, err, ErrYAML) + } + return f, nil + case yamlTimestamp: + // YAML timestamp is marshaled as string, not time + return node.Value, nil + case yamlNull: + return nil, nil //nolint:nilnil + default: + return nil, fmt.Errorf("YAML tag %q is not supported: %w", node.LongTag(), ErrYAML) + } +} + +func yamlStringScalarC(node *yaml.Node) (string, error) { + if node.Kind != yaml.ScalarNode { + return "", fmt.Errorf("expecting a string scalar but got %q: %w", node.Kind, ErrYAML) + } + switch node.LongTag() { + case yamlStringScalar, yamlIntScalar, yamlFloatScalar: + return node.Value, nil + default: + return "", fmt.Errorf("YAML tag %q is not supported as map key: %w", node.LongTag(), ErrYAML) + } +} + +func format(t any) (string, error) { + switch k := t.(type) { + case string: + return k, nil + case uint: + return strconv.FormatUint(uint64(k), 10), nil + case uint8: + return strconv.FormatUint(uint64(k), 10), nil + case uint16: + return strconv.FormatUint(uint64(k), 10), nil + case uint32: + return strconv.FormatUint(uint64(k), 10), nil + case uint64: + return strconv.FormatUint(k, 10), nil + case int: + return strconv.Itoa(k), nil + case int8: + return strconv.FormatInt(int64(k), 10), nil + case int16: + return strconv.FormatInt(int64(k), 10), nil + case int32: + return strconv.FormatInt(int64(k), 10), nil + case int64: + return strconv.FormatInt(k, 10), nil + default: + return "", fmt.Errorf("unexpected map key type, got: %T: %w", k, ErrYAML) + } +} + +func transformData(input any) (out any, err error) { + switch in := input.(type) { + case yaml.Node: + return yamlNode(&in) + case *yaml.Node: + return yamlNode(in) + case map[any]any: + o := make(YAMLMapSlice, 0, len(in)) + for ke, va := range in { + var nmi YAMLMapItem + if nmi.Key, err = format(ke); err != nil { + return nil, err + } + + v, ert := transformData(va) + if ert != nil { + return nil, ert + } + nmi.Value = v + o = append(o, nmi) + } + return o, nil + case []any: + len1 := len(in) + o := make([]any, len1) + for i := range len1 { + o[i], err = transformData(in[i]) + if err != nil { + return nil, err + } + } + return o, nil + } + return input, nil +} diff --git a/vendor/github.com/go-openapi/swag/yamlutils_iface.go b/vendor/github.com/go-openapi/swag/yamlutils_iface.go new file mode 100644 index 000000000000..57767efc567f --- /dev/null +++ b/vendor/github.com/go-openapi/swag/yamlutils_iface.go @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package swag + +import ( + "encoding/json" + + "github.com/go-openapi/swag/yamlutils" +) + +// YAMLToJSON converts YAML unmarshaled data into json compatible data +// +// Deprecated: use [yamlutils.YAMLToJSON] instead. +func YAMLToJSON(data any) (json.RawMessage, error) { return yamlutils.YAMLToJSON(data) } + +// BytesToYAMLDoc converts a byte slice into a YAML document +// +// Deprecated: use [yamlutils.BytesToYAMLDoc] instead. +func BytesToYAMLDoc(data []byte) (any, error) { return yamlutils.BytesToYAMLDoc(data) } diff --git a/vendor/github.com/go-openapi/validate/BENCHMARK.md b/vendor/github.com/go-openapi/validate/BENCHMARK.md new file mode 100644 index 000000000000..79cf6a077ba2 --- /dev/null +++ b/vendor/github.com/go-openapi/validate/BENCHMARK.md @@ -0,0 +1,31 @@ +# Benchmark + +Validating the Kubernetes Swagger API + +## v0.22.6: 60,000,000 allocs +``` +goos: linux +goarch: amd64 +pkg: github.com/go-openapi/validate +cpu: AMD Ryzen 7 5800X 8-Core Processor +Benchmark_KubernetesSpec/validating_kubernetes_API-16 1 8549863982 ns/op 7067424936 B/op 59583275 allocs/op +``` + +## After refact PR: minor but noticable improvements: 25,000,000 allocs +``` +go test -bench Spec +goos: linux +goarch: amd64 +pkg: github.com/go-openapi/validate +cpu: AMD Ryzen 7 5800X 8-Core Processor +Benchmark_KubernetesSpec/validating_kubernetes_API-16 1 4064535557 ns/op 3379715592 B/op 25320330 allocs/op +``` + +## After reduce GC pressure PR: 17,000,000 allocs +``` +goos: linux +goarch: amd64 +pkg: github.com/go-openapi/validate +cpu: AMD Ryzen 7 5800X 8-Core Processor +Benchmark_KubernetesSpec/validating_kubernetes_API-16 1 3758414145 ns/op 2593881496 B/op 17111373 allocs/op +``` diff --git a/vendor/github.com/go-openapi/validate/default_validator.go b/vendor/github.com/go-openapi/validate/default_validator.go index 7f7fd0be9c02..e0dd93839eca 100644 --- a/vendor/github.com/go-openapi/validate/default_validator.go +++ b/vendor/github.com/go-openapi/validate/default_validator.go @@ -25,48 +25,55 @@ import ( // According to Swagger spec, default values MUST validate their schema. type defaultValidator struct { SpecValidator *SpecValidator - visitedSchemas map[string]bool + visitedSchemas map[string]struct{} + schemaOptions *SchemaValidatorOptions } // resetVisited resets the internal state of visited schemas func (d *defaultValidator) resetVisited() { - d.visitedSchemas = map[string]bool{} + if d.visitedSchemas == nil { + d.visitedSchemas = make(map[string]struct{}) + + return + } + + // TODO(go1.21): clear(ex.visitedSchemas) + for k := range d.visitedSchemas { + delete(d.visitedSchemas, k) + } } -func isVisited(path string, visitedSchemas map[string]bool) bool { - found := visitedSchemas[path] - if !found { - // search for overlapping paths - frags := strings.Split(path, ".") - if len(frags) < 2 { - // shortcut exit on smaller paths - return found +func isVisited(path string, visitedSchemas map[string]struct{}) bool { + _, found := visitedSchemas[path] + if found { + return true + } + + // search for overlapping paths + var ( + parent string + suffix string + ) + for i := len(path) - 2; i >= 0; i-- { + r := path[i] + if r != '.' { + continue } - last := len(frags) - 1 - var currentFragStr, parent string - for i := range frags { - if i == 0 { - currentFragStr = frags[last] - } else { - currentFragStr = strings.Join([]string{frags[last-i], currentFragStr}, ".") - } - if i < last { - parent = strings.Join(frags[0:last-i], ".") - } else { - parent = "" - } - if strings.HasSuffix(parent, currentFragStr) { - found = true - break - } + + parent = path[0:i] + suffix = path[i+1:] + + if strings.HasSuffix(parent, suffix) { + return true } } - return found + + return false } // beingVisited asserts a schema is being visited func (d *defaultValidator) beingVisited(path string) { - d.visitedSchemas[path] = true + d.visitedSchemas[path] = struct{}{} } // isVisited tells if a path has already been visited @@ -75,8 +82,9 @@ func (d *defaultValidator) isVisited(path string) bool { } // Validate validates the default values declared in the swagger spec -func (d *defaultValidator) Validate() (errs *Result) { - errs = new(Result) +func (d *defaultValidator) Validate() *Result { + errs := pools.poolOfResults.BorrowResult() // will redeem when merged + if d == nil || d.SpecValidator == nil { return errs } @@ -89,7 +97,7 @@ func (d *defaultValidator) validateDefaultValueValidAgainstSchema() *Result { // every default value that is specified must validate against the schema for that property // headers, items, parameters, schema - res := new(Result) + res := pools.poolOfResults.BorrowResult() // will redeem when merged s := d.SpecValidator for method, pathItem := range s.expandedAnalyzer().Operations() { @@ -107,10 +115,12 @@ func (d *defaultValidator) validateDefaultValueValidAgainstSchema() *Result { // default values provided must validate against their inline definition (no explicit schema) if param.Default != nil && param.Schema == nil { // check param default value is valid - red := NewParamValidator(¶m, s.KnownFormats).Validate(param.Default) //#nosec + red := newParamValidator(¶m, s.KnownFormats, d.schemaOptions).Validate(param.Default) //#nosec if red.HasErrorsOrWarnings() { res.AddErrors(defaultValueDoesNotValidateMsg(param.Name, param.In)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } @@ -120,6 +130,8 @@ func (d *defaultValidator) validateDefaultValueValidAgainstSchema() *Result { if red.HasErrorsOrWarnings() { res.AddErrors(defaultValueItemsDoesNotValidateMsg(param.Name, param.In)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } @@ -129,6 +141,8 @@ func (d *defaultValidator) validateDefaultValueValidAgainstSchema() *Result { if red.HasErrorsOrWarnings() { res.AddErrors(defaultValueDoesNotValidateMsg(param.Name, param.In)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } } @@ -154,7 +168,7 @@ func (d *defaultValidator) validateDefaultValueValidAgainstSchema() *Result { // reset explored schemas to get depth-first recursive-proof exploration d.resetVisited() for nm, sch := range s.spec.Spec().Definitions { - res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("definitions.%s", nm), "body", &sch)) //#nosec + res.Merge(d.validateDefaultValueSchemaAgainstSchema("definitions."+nm, "body", &sch)) //#nosec } } return res @@ -176,10 +190,12 @@ func (d *defaultValidator) validateDefaultInResponse(resp *spec.Response, respon d.resetVisited() if h.Default != nil { - red := NewHeaderValidator(nm, &h, s.KnownFormats).Validate(h.Default) //#nosec + red := newHeaderValidator(nm, &h, s.KnownFormats, d.schemaOptions).Validate(h.Default) //#nosec if red.HasErrorsOrWarnings() { res.AddErrors(defaultValueHeaderDoesNotValidateMsg(operationID, nm, responseName)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } @@ -189,6 +205,8 @@ func (d *defaultValidator) validateDefaultInResponse(resp *spec.Response, respon if red.HasErrorsOrWarnings() { res.AddErrors(defaultValueHeaderItemsDoesNotValidateMsg(operationID, nm, responseName)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } @@ -208,6 +226,8 @@ func (d *defaultValidator) validateDefaultInResponse(resp *spec.Response, respon // Additional message to make sure the context of the error is not lost res.AddErrors(defaultValueInDoesNotValidateMsg(operationID, responseName)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } return res @@ -219,11 +239,13 @@ func (d *defaultValidator) validateDefaultValueSchemaAgainstSchema(path, in stri return nil } d.beingVisited(path) - res := new(Result) + res := pools.poolOfResults.BorrowResult() s := d.SpecValidator if schema.Default != nil { - res.Merge(NewSchemaValidator(schema, s.spec.Spec(), path+".default", s.KnownFormats, SwaggerSchema(true)).Validate(schema.Default)) + res.Merge( + newSchemaValidator(schema, s.spec.Spec(), path+".default", s.KnownFormats, d.schemaOptions).Validate(schema.Default), + ) } if schema.Items != nil { if schema.Items.Schema != nil { @@ -241,7 +263,7 @@ func (d *defaultValidator) validateDefaultValueSchemaAgainstSchema(path, in stri } if schema.AdditionalItems != nil && schema.AdditionalItems.Schema != nil { // NOTE: we keep validating values, even though additionalItems is not supported by Swagger 2.0 (and 3.0 as well) - res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalItems", path), in, schema.AdditionalItems.Schema)) + res.Merge(d.validateDefaultValueSchemaAgainstSchema(path+".additionalItems", in, schema.AdditionalItems.Schema)) } for propName, prop := range schema.Properties { res.Merge(d.validateDefaultValueSchemaAgainstSchema(path+"."+propName, in, &prop)) //#nosec @@ -250,7 +272,7 @@ func (d *defaultValidator) validateDefaultValueSchemaAgainstSchema(path, in stri res.Merge(d.validateDefaultValueSchemaAgainstSchema(path+"."+propName, in, &prop)) //#nosec } if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil { - res.Merge(d.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalProperties", path), in, schema.AdditionalProperties.Schema)) + res.Merge(d.validateDefaultValueSchemaAgainstSchema(path+".additionalProperties", in, schema.AdditionalProperties.Schema)) } if schema.AllOf != nil { for i, aoSch := range schema.AllOf { @@ -263,11 +285,13 @@ func (d *defaultValidator) validateDefaultValueSchemaAgainstSchema(path, in stri // TODO: Temporary duplicated code. Need to refactor with examples func (d *defaultValidator) validateDefaultValueItemsAgainstSchema(path, in string, root interface{}, items *spec.Items) *Result { - res := new(Result) + res := pools.poolOfResults.BorrowResult() s := d.SpecValidator if items != nil { if items.Default != nil { - res.Merge(newItemsValidator(path, in, items, root, s.KnownFormats).Validate(0, items.Default)) + res.Merge( + newItemsValidator(path, in, items, root, s.KnownFormats, d.schemaOptions).Validate(0, items.Default), + ) } if items.Items != nil { res.Merge(d.validateDefaultValueItemsAgainstSchema(path+"[0].default", in, root, items.Items)) diff --git a/vendor/github.com/go-openapi/validate/example_validator.go b/vendor/github.com/go-openapi/validate/example_validator.go index d5d4b8833209..d08956973ce5 100644 --- a/vendor/github.com/go-openapi/validate/example_validator.go +++ b/vendor/github.com/go-openapi/validate/example_validator.go @@ -23,17 +23,27 @@ import ( // ExampleValidator validates example values defined in a spec type exampleValidator struct { SpecValidator *SpecValidator - visitedSchemas map[string]bool + visitedSchemas map[string]struct{} + schemaOptions *SchemaValidatorOptions } // resetVisited resets the internal state of visited schemas func (ex *exampleValidator) resetVisited() { - ex.visitedSchemas = map[string]bool{} + if ex.visitedSchemas == nil { + ex.visitedSchemas = make(map[string]struct{}) + + return + } + + // TODO(go1.21): clear(ex.visitedSchemas) + for k := range ex.visitedSchemas { + delete(ex.visitedSchemas, k) + } } // beingVisited asserts a schema is being visited func (ex *exampleValidator) beingVisited(path string) { - ex.visitedSchemas[path] = true + ex.visitedSchemas[path] = struct{}{} } // isVisited tells if a path has already been visited @@ -48,8 +58,9 @@ func (ex *exampleValidator) isVisited(path string) bool { // - schemas // - individual property // - responses -func (ex *exampleValidator) Validate() (errs *Result) { - errs = new(Result) +func (ex *exampleValidator) Validate() *Result { + errs := pools.poolOfResults.BorrowResult() + if ex == nil || ex.SpecValidator == nil { return errs } @@ -64,7 +75,7 @@ func (ex *exampleValidator) validateExampleValueValidAgainstSchema() *Result { // in: schemas, properties, object, items // not in: headers, parameters without schema - res := new(Result) + res := pools.poolOfResults.BorrowResult() s := ex.SpecValidator for method, pathItem := range s.expandedAnalyzer().Operations() { @@ -82,10 +93,12 @@ func (ex *exampleValidator) validateExampleValueValidAgainstSchema() *Result { // default values provided must validate against their inline definition (no explicit schema) if param.Example != nil && param.Schema == nil { // check param default value is valid - red := NewParamValidator(¶m, s.KnownFormats).Validate(param.Example) //#nosec + red := newParamValidator(¶m, s.KnownFormats, ex.schemaOptions).Validate(param.Example) //#nosec if red.HasErrorsOrWarnings() { res.AddWarnings(exampleValueDoesNotValidateMsg(param.Name, param.In)) res.MergeAsWarnings(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } @@ -95,6 +108,8 @@ func (ex *exampleValidator) validateExampleValueValidAgainstSchema() *Result { if red.HasErrorsOrWarnings() { res.AddWarnings(exampleValueItemsDoesNotValidateMsg(param.Name, param.In)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } @@ -104,6 +119,8 @@ func (ex *exampleValidator) validateExampleValueValidAgainstSchema() *Result { if red.HasErrorsOrWarnings() { res.AddWarnings(exampleValueDoesNotValidateMsg(param.Name, param.In)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } } @@ -129,7 +146,7 @@ func (ex *exampleValidator) validateExampleValueValidAgainstSchema() *Result { // reset explored schemas to get depth-first recursive-proof exploration ex.resetVisited() for nm, sch := range s.spec.Spec().Definitions { - res.Merge(ex.validateExampleValueSchemaAgainstSchema(fmt.Sprintf("definitions.%s", nm), "body", &sch)) //#nosec + res.Merge(ex.validateExampleValueSchemaAgainstSchema("definitions."+nm, "body", &sch)) //#nosec } } return res @@ -151,10 +168,12 @@ func (ex *exampleValidator) validateExampleInResponse(resp *spec.Response, respo ex.resetVisited() if h.Example != nil { - red := NewHeaderValidator(nm, &h, s.KnownFormats).Validate(h.Example) //#nosec + red := newHeaderValidator(nm, &h, s.KnownFormats, ex.schemaOptions).Validate(h.Example) //#nosec if red.HasErrorsOrWarnings() { res.AddWarnings(exampleValueHeaderDoesNotValidateMsg(operationID, nm, responseName)) res.MergeAsWarnings(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } @@ -164,6 +183,8 @@ func (ex *exampleValidator) validateExampleInResponse(resp *spec.Response, respo if red.HasErrorsOrWarnings() { res.AddWarnings(exampleValueHeaderItemsDoesNotValidateMsg(operationID, nm, responseName)) res.MergeAsWarnings(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } @@ -183,13 +204,17 @@ func (ex *exampleValidator) validateExampleInResponse(resp *spec.Response, respo // Additional message to make sure the context of the error is not lost res.AddWarnings(exampleValueInDoesNotValidateMsg(operationID, responseName)) res.Merge(red) + } else if red.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(red) } } if response.Examples != nil { if response.Schema != nil { if example, ok := response.Examples["application/json"]; ok { - res.MergeAsWarnings(NewSchemaValidator(response.Schema, s.spec.Spec(), path+".examples", s.KnownFormats, SwaggerSchema(true)).Validate(example)) + res.MergeAsWarnings( + newSchemaValidator(response.Schema, s.spec.Spec(), path+".examples", s.KnownFormats, s.schemaOptions).Validate(example), + ) } else { // TODO: validate other media types too res.AddWarnings(examplesMimeNotSupportedMsg(operationID, responseName)) @@ -208,10 +233,12 @@ func (ex *exampleValidator) validateExampleValueSchemaAgainstSchema(path, in str } ex.beingVisited(path) s := ex.SpecValidator - res := new(Result) + res := pools.poolOfResults.BorrowResult() if schema.Example != nil { - res.MergeAsWarnings(NewSchemaValidator(schema, s.spec.Spec(), path+".example", s.KnownFormats, SwaggerSchema(true)).Validate(schema.Example)) + res.MergeAsWarnings( + newSchemaValidator(schema, s.spec.Spec(), path+".example", s.KnownFormats, ex.schemaOptions).Validate(schema.Example), + ) } if schema.Items != nil { if schema.Items.Schema != nil { @@ -229,7 +256,7 @@ func (ex *exampleValidator) validateExampleValueSchemaAgainstSchema(path, in str } if schema.AdditionalItems != nil && schema.AdditionalItems.Schema != nil { // NOTE: we keep validating values, even though additionalItems is unsupported in Swagger 2.0 (and 3.0 as well) - res.Merge(ex.validateExampleValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalItems", path), in, schema.AdditionalItems.Schema)) + res.Merge(ex.validateExampleValueSchemaAgainstSchema(path+".additionalItems", in, schema.AdditionalItems.Schema)) } for propName, prop := range schema.Properties { res.Merge(ex.validateExampleValueSchemaAgainstSchema(path+"."+propName, in, &prop)) //#nosec @@ -238,7 +265,7 @@ func (ex *exampleValidator) validateExampleValueSchemaAgainstSchema(path, in str res.Merge(ex.validateExampleValueSchemaAgainstSchema(path+"."+propName, in, &prop)) //#nosec } if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil { - res.Merge(ex.validateExampleValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalProperties", path), in, schema.AdditionalProperties.Schema)) + res.Merge(ex.validateExampleValueSchemaAgainstSchema(path+".additionalProperties", in, schema.AdditionalProperties.Schema)) } if schema.AllOf != nil { for i, aoSch := range schema.AllOf { @@ -252,11 +279,13 @@ func (ex *exampleValidator) validateExampleValueSchemaAgainstSchema(path, in str // func (ex *exampleValidator) validateExampleValueItemsAgainstSchema(path, in string, root interface{}, items *spec.Items) *Result { - res := new(Result) + res := pools.poolOfResults.BorrowResult() s := ex.SpecValidator if items != nil { if items.Example != nil { - res.MergeAsWarnings(newItemsValidator(path, in, items, root, s.KnownFormats).Validate(0, items.Example)) + res.MergeAsWarnings( + newItemsValidator(path, in, items, root, s.KnownFormats, ex.schemaOptions).Validate(0, items.Example), + ) } if items.Items != nil { res.Merge(ex.validateExampleValueItemsAgainstSchema(path+"[0].example", in, root, items.Items)) @@ -265,5 +294,6 @@ func (ex *exampleValidator) validateExampleValueItemsAgainstSchema(path, in stri res.AddErrors(invalidPatternInMsg(path, in, items.Pattern)) } } + return res } diff --git a/vendor/github.com/go-openapi/validate/formats.go b/vendor/github.com/go-openapi/validate/formats.go index 0ad996cbbc2f..f4e355213060 100644 --- a/vendor/github.com/go-openapi/validate/formats.go +++ b/vendor/github.com/go-openapi/validate/formats.go @@ -22,10 +22,32 @@ import ( ) type formatValidator struct { - Format string Path string In string + Format string KnownFormats strfmt.Registry + Options *SchemaValidatorOptions +} + +func newFormatValidator(path, in, format string, formats strfmt.Registry, opts *SchemaValidatorOptions) *formatValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var f *formatValidator + if opts.recycleValidators { + f = pools.poolOfFormatValidators.BorrowValidator() + } else { + f = new(formatValidator) + } + + f.Path = path + f.In = in + f.Format = format + f.KnownFormats = formats + f.Options = opts + + return f } func (f *formatValidator) SetPath(path string) { @@ -33,37 +55,45 @@ func (f *formatValidator) SetPath(path string) { } func (f *formatValidator) Applies(source interface{}, kind reflect.Kind) bool { - doit := func() bool { - if source == nil { - return false - } - switch source := source.(type) { - case *spec.Items: - return kind == reflect.String && f.KnownFormats.ContainsName(source.Format) - case *spec.Parameter: - return kind == reflect.String && f.KnownFormats.ContainsName(source.Format) - case *spec.Schema: - return kind == reflect.String && f.KnownFormats.ContainsName(source.Format) - case *spec.Header: - return kind == reflect.String && f.KnownFormats.ContainsName(source.Format) - } + if source == nil || f.KnownFormats == nil { + return false + } + + switch source := source.(type) { + case *spec.Items: + return kind == reflect.String && f.KnownFormats.ContainsName(source.Format) + case *spec.Parameter: + return kind == reflect.String && f.KnownFormats.ContainsName(source.Format) + case *spec.Schema: + return kind == reflect.String && f.KnownFormats.ContainsName(source.Format) + case *spec.Header: + return kind == reflect.String && f.KnownFormats.ContainsName(source.Format) + default: return false } - r := doit() - debugLog("format validator for %q applies %t for %T (kind: %v)\n", f.Path, r, source, kind) - return r } func (f *formatValidator) Validate(val interface{}) *Result { - result := new(Result) - debugLog("validating \"%v\" against format: %s", val, f.Format) + if f.Options.recycleValidators { + defer func() { + f.redeem() + }() + } + + var result *Result + if f.Options.recycleResult { + result = pools.poolOfResults.BorrowResult() + } else { + result = new(Result) + } if err := FormatOf(f.Path, f.In, f.Format, val.(string), f.KnownFormats); err != nil { result.AddErrors(err) } - if result.HasErrors() { - return result - } - return nil + return result +} + +func (f *formatValidator) redeem() { + pools.poolOfFormatValidators.RedeemValidator(f) } diff --git a/vendor/github.com/go-openapi/validate/helpers.go b/vendor/github.com/go-openapi/validate/helpers.go index fc7500c844b9..757e403d912d 100644 --- a/vendor/github.com/go-openapi/validate/helpers.go +++ b/vendor/github.com/go-openapi/validate/helpers.go @@ -101,9 +101,17 @@ type errorHelper struct { // A collection of unexported helpers for error construction } -func (h *errorHelper) sErr(err errors.Error) *Result { +func (h *errorHelper) sErr(err errors.Error, recycle bool) *Result { // Builds a Result from standard errors.Error - return &Result{Errors: []error{err}} + var result *Result + if recycle { + result = pools.poolOfResults.BorrowResult() + } else { + result = new(Result) + } + result.Errors = []error{err} + + return result } func (h *errorHelper) addPointerError(res *Result, err error, ref string, fromPath string) *Result { @@ -225,7 +233,7 @@ func (h *paramHelper) safeExpandedParamsFor(path, method, operationID string, re operation.Parameters = resolvedParams for _, ppr := range s.expandedAnalyzer().SafeParamsFor(method, path, - func(p spec.Parameter, err error) bool { + func(_ spec.Parameter, err error) bool { // since params have already been expanded, there are few causes for error res.AddErrors(someParametersBrokenMsg(path, method, operationID)) // original error from analyzer @@ -306,6 +314,7 @@ func (r *responseHelper) expandResponseRef( errorHelp.addPointerError(res, err, response.Ref.String(), path) return nil, res } + return response, res } diff --git a/vendor/github.com/go-openapi/validate/object_validator.go b/vendor/github.com/go-openapi/validate/object_validator.go index 7bb12615d8e2..dff73fa98a15 100644 --- a/vendor/github.com/go-openapi/validate/object_validator.go +++ b/vendor/github.com/go-openapi/validate/object_validator.go @@ -15,8 +15,8 @@ package validate import ( + "fmt" "reflect" - "regexp" "strings" "github.com/go-openapi/errors" @@ -35,62 +35,116 @@ type objectValidator struct { PatternProperties map[string]spec.Schema Root interface{} KnownFormats strfmt.Registry - Options SchemaValidatorOptions + Options *SchemaValidatorOptions + splitPath []string +} + +func newObjectValidator(path, in string, + maxProperties, minProperties *int64, required []string, properties spec.SchemaProperties, + additionalProperties *spec.SchemaOrBool, patternProperties spec.SchemaProperties, + root interface{}, formats strfmt.Registry, opts *SchemaValidatorOptions) *objectValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var v *objectValidator + if opts.recycleValidators { + v = pools.poolOfObjectValidators.BorrowValidator() + } else { + v = new(objectValidator) + } + + v.Path = path + v.In = in + v.MaxProperties = maxProperties + v.MinProperties = minProperties + v.Required = required + v.Properties = properties + v.AdditionalProperties = additionalProperties + v.PatternProperties = patternProperties + v.Root = root + v.KnownFormats = formats + v.Options = opts + v.splitPath = strings.Split(v.Path, ".") + + return v } func (o *objectValidator) SetPath(path string) { o.Path = path + o.splitPath = strings.Split(path, ".") } func (o *objectValidator) Applies(source interface{}, kind reflect.Kind) bool { // TODO: this should also work for structs // there is a problem in the type validator where it will be unhappy about null values // so that requires more testing - r := reflect.TypeOf(source) == specSchemaType && (kind == reflect.Map || kind == reflect.Struct) - debugLog("object validator for %q applies %t for %T (kind: %v)\n", o.Path, r, source, kind) - return r + _, isSchema := source.(*spec.Schema) + return isSchema && (kind == reflect.Map || kind == reflect.Struct) } func (o *objectValidator) isProperties() bool { - p := strings.Split(o.Path, ".") + p := o.splitPath return len(p) > 1 && p[len(p)-1] == jsonProperties && p[len(p)-2] != jsonProperties } func (o *objectValidator) isDefault() bool { - p := strings.Split(o.Path, ".") + p := o.splitPath return len(p) > 1 && p[len(p)-1] == jsonDefault && p[len(p)-2] != jsonDefault } func (o *objectValidator) isExample() bool { - p := strings.Split(o.Path, ".") + p := o.splitPath return len(p) > 1 && (p[len(p)-1] == swaggerExample || p[len(p)-1] == swaggerExamples) && p[len(p)-2] != swaggerExample } func (o *objectValidator) checkArrayMustHaveItems(res *Result, val map[string]interface{}) { // for swagger 2.0 schemas, there is an additional constraint to have array items defined explicitly. // with pure jsonschema draft 4, one may have arrays with undefined items (i.e. any type). - if t, typeFound := val[jsonType]; typeFound { - if tpe, ok := t.(string); ok && tpe == arrayType { - if item, itemsKeyFound := val[jsonItems]; !itemsKeyFound { - res.AddErrors(errors.Required(jsonItems, o.Path, item)) - } - } + if val == nil { + return + } + + t, typeFound := val[jsonType] + if !typeFound { + return + } + + tpe, isString := t.(string) + if !isString || tpe != arrayType { + return + } + + item, itemsKeyFound := val[jsonItems] + if itemsKeyFound { + return } + + res.AddErrors(errors.Required(jsonItems, o.Path, item)) } func (o *objectValidator) checkItemsMustBeTypeArray(res *Result, val map[string]interface{}) { - if !o.isProperties() && !o.isDefault() && !o.isExample() { - if _, itemsKeyFound := val[jsonItems]; itemsKeyFound { - t, typeFound := val[jsonType] - if typeFound { - if tpe, ok := t.(string); !ok || tpe != arrayType { - res.AddErrors(errors.InvalidType(o.Path, o.In, arrayType, nil)) - } - } else { - // there is no type - res.AddErrors(errors.Required(jsonType, o.Path, t)) - } - } + if val == nil { + return + } + + if o.isProperties() || o.isDefault() || o.isExample() { + return + } + + _, itemsKeyFound := val[jsonItems] + if !itemsKeyFound { + return + } + + t, typeFound := val[jsonType] + if !typeFound { + // there is no type + res.AddErrors(errors.Required(jsonType, o.Path, t)) + } + + if tpe, isString := t.(string); !isString || tpe != arrayType { + res.AddErrors(errors.InvalidType(o.Path, o.In, arrayType, nil)) } } @@ -104,176 +158,274 @@ func (o *objectValidator) precheck(res *Result, val map[string]interface{}) { } func (o *objectValidator) Validate(data interface{}) *Result { - val := data.(map[string]interface{}) - // TODO: guard against nil data + if o.Options.recycleValidators { + defer func() { + o.redeem() + }() + } + + var val map[string]interface{} + if data != nil { + var ok bool + val, ok = data.(map[string]interface{}) + if !ok { + return errorHelp.sErr(invalidObjectMsg(o.Path, o.In), o.Options.recycleResult) + } + } numKeys := int64(len(val)) if o.MinProperties != nil && numKeys < *o.MinProperties { - return errorHelp.sErr(errors.TooFewProperties(o.Path, o.In, *o.MinProperties)) + return errorHelp.sErr(errors.TooFewProperties(o.Path, o.In, *o.MinProperties), o.Options.recycleResult) } if o.MaxProperties != nil && numKeys > *o.MaxProperties { - return errorHelp.sErr(errors.TooManyProperties(o.Path, o.In, *o.MaxProperties)) + return errorHelp.sErr(errors.TooManyProperties(o.Path, o.In, *o.MaxProperties), o.Options.recycleResult) } - res := new(Result) + var res *Result + if o.Options.recycleResult { + res = pools.poolOfResults.BorrowResult() + } else { + res = new(Result) + } o.precheck(res, val) // check validity of field names if o.AdditionalProperties != nil && !o.AdditionalProperties.Allows { // Case: additionalProperties: false - for k := range val { - _, regularProperty := o.Properties[k] - matched := false - - for pk := range o.PatternProperties { - if matches, _ := regexp.MatchString(pk, k); matches { - matched = true - break - } + o.validateNoAdditionalProperties(val, res) + } else { + // Cases: empty additionalProperties (implying: true), or additionalProperties: true, or additionalProperties: { <> } + o.validateAdditionalProperties(val, res) + } + + o.validatePropertiesSchema(val, res) + + // Check patternProperties + // TODO: it looks like we have done that twice in many cases + for key, value := range val { + _, regularProperty := o.Properties[key] + matched, _, patterns := o.validatePatternProperty(key, value, res) // applies to regular properties as well + if regularProperty || !matched { + continue + } + + for _, pName := range patterns { + if v, ok := o.PatternProperties[pName]; ok { + r := newSchemaValidator(&v, o.Root, o.Path+"."+key, o.KnownFormats, o.Options).Validate(value) + res.mergeForField(data.(map[string]interface{}), key, r) } + } + } - if !regularProperty && k != "$schema" && k != "id" && !matched { - // Special properties "$schema" and "id" are ignored - res.AddErrors(errors.PropertyNotAllowed(o.Path, o.In, k)) - - // BUG(fredbi): This section should move to a part dedicated to spec validation as - // it will conflict with regular schemas where a property "headers" is defined. - - // - // Croaks a more explicit message on top of the standard one - // on some recognized cases. - // - // NOTE: edge cases with invalid type assertion are simply ignored here. - // NOTE: prefix your messages here by "IMPORTANT!" so there are not filtered - // by higher level callers (the IMPORTANT! tag will be eventually - // removed). - if k == "headers" && val[k] != nil { - // $ref is forbidden in header - if headers, mapOk := val[k].(map[string]interface{}); mapOk { - for headerKey, headerBody := range headers { - if headerBody != nil { - if headerSchema, mapOfMapOk := headerBody.(map[string]interface{}); mapOfMapOk { - if _, found := headerSchema["$ref"]; found { - var msg string - if refString, stringOk := headerSchema["$ref"].(string); stringOk { - msg = strings.Join([]string{", one may not use $ref=\":", refString, "\""}, "") - } - res.AddErrors(refNotAllowedInHeaderMsg(o.Path, headerKey, msg)) - } - } - } - } - } - /* - case "$ref": - if val[k] != nil { - // TODO: check context of that ref: warn about siblings, check against invalid context - } - */ - } + return res +} + +func (o *objectValidator) validateNoAdditionalProperties(val map[string]interface{}, res *Result) { + for k := range val { + if k == "$schema" || k == "id" { + // special properties "$schema" and "id" are ignored + continue + } + + _, regularProperty := o.Properties[k] + if regularProperty { + continue + } + + matched := false + for pk := range o.PatternProperties { + re, err := compileRegexp(pk) + if err != nil { + continue + } + if matches := re.MatchString(k); matches { + matched = true + break } } - } else { - // Cases: no additionalProperties (implying: true), or additionalProperties: true, or additionalProperties: { <> } - for key, value := range val { - _, regularProperty := o.Properties[key] - - // Validates property against "patternProperties" if applicable - // BUG(fredbi): succeededOnce is always false - - // NOTE: how about regular properties which do not match patternProperties? - matched, succeededOnce, _ := o.validatePatternProperty(key, value, res) - - if !(regularProperty || matched || succeededOnce) { - - // Cases: properties which are not regular properties and have not been matched by the PatternProperties validator - if o.AdditionalProperties != nil && o.AdditionalProperties.Schema != nil { - // AdditionalProperties as Schema - r := NewSchemaValidator(o.AdditionalProperties.Schema, o.Root, o.Path+"."+key, o.KnownFormats, o.Options.Options()...).Validate(value) - res.mergeForField(data.(map[string]interface{}), key, r) - } else if regularProperty && !(matched || succeededOnce) { - // TODO: this is dead code since regularProperty=false here - res.AddErrors(errors.FailedAllPatternProperties(o.Path, o.In, key)) - } + if matched { + continue + } + + res.AddErrors(errors.PropertyNotAllowed(o.Path, o.In, k)) + + // BUG(fredbi): This section should move to a part dedicated to spec validation as + // it will conflict with regular schemas where a property "headers" is defined. + + // + // Croaks a more explicit message on top of the standard one + // on some recognized cases. + // + // NOTE: edge cases with invalid type assertion are simply ignored here. + // NOTE: prefix your messages here by "IMPORTANT!" so there are not filtered + // by higher level callers (the IMPORTANT! tag will be eventually + // removed). + if k != "headers" || val[k] == nil { + continue + } + + // $ref is forbidden in header + headers, mapOk := val[k].(map[string]interface{}) + if !mapOk { + continue + } + + for headerKey, headerBody := range headers { + if headerBody == nil { + continue + } + + headerSchema, mapOfMapOk := headerBody.(map[string]interface{}) + if !mapOfMapOk { + continue + } + + _, found := headerSchema["$ref"] + if !found { + continue + } + + refString, stringOk := headerSchema["$ref"].(string) + if !stringOk { + continue } + + msg := strings.Join([]string{", one may not use $ref=\":", refString, "\""}, "") + res.AddErrors(refNotAllowedInHeaderMsg(o.Path, headerKey, msg)) + /* + case "$ref": + if val[k] != nil { + // TODO: check context of that ref: warn about siblings, check against invalid context + } + */ + } + } +} + +func (o *objectValidator) validateAdditionalProperties(val map[string]interface{}, res *Result) { + for key, value := range val { + _, regularProperty := o.Properties[key] + if regularProperty { + continue + } + + // Validates property against "patternProperties" if applicable + // BUG(fredbi): succeededOnce is always false + + // NOTE: how about regular properties which do not match patternProperties? + matched, succeededOnce, _ := o.validatePatternProperty(key, value, res) + if matched || succeededOnce { + continue + } + + if o.AdditionalProperties == nil || o.AdditionalProperties.Schema == nil { + continue } - // Valid cases: additionalProperties: true or undefined + + // Cases: properties which are not regular properties and have not been matched by the PatternProperties validator + // AdditionalProperties as Schema + r := newSchemaValidator(o.AdditionalProperties.Schema, o.Root, o.Path+"."+key, o.KnownFormats, o.Options).Validate(value) + res.mergeForField(val, key, r) } + // Valid cases: additionalProperties: true or undefined +} - createdFromDefaults := map[string]bool{} +func (o *objectValidator) validatePropertiesSchema(val map[string]interface{}, res *Result) { + createdFromDefaults := map[string]struct{}{} // Property types: // - regular Property + pSchema := pools.poolOfSchemas.BorrowSchema() // recycle a spec.Schema object which lifespan extends only to the validation of properties + defer func() { + pools.poolOfSchemas.RedeemSchema(pSchema) + }() + for pName := range o.Properties { - pSchema := o.Properties[pName] // one instance per iteration - rName := pName - if o.Path != "" { + *pSchema = o.Properties[pName] + var rName string + if o.Path == "" { + rName = pName + } else { rName = o.Path + "." + pName } // Recursively validates each property against its schema - if v, ok := val[pName]; ok { - r := NewSchemaValidator(&pSchema, o.Root, rName, o.KnownFormats, o.Options.Options()...).Validate(v) - res.mergeForField(data.(map[string]interface{}), pName, r) - } else if pSchema.Default != nil { - // If a default value is defined, creates the property from defaults - // NOTE: JSON schema does not enforce default values to be valid against schema. Swagger does. - createdFromDefaults[pName] = true - res.addPropertySchemata(data.(map[string]interface{}), pName, &pSchema) + v, ok := val[pName] + if ok { + r := newSchemaValidator(pSchema, o.Root, rName, o.KnownFormats, o.Options).Validate(v) + res.mergeForField(val, pName, r) + + continue } - } - // Check required properties - if len(o.Required) > 0 { - for _, k := range o.Required { - if v, ok := val[k]; !ok && !createdFromDefaults[k] { - res.AddErrors(errors.Required(o.Path+"."+k, o.In, v)) - continue + if pSchema.Default != nil { + // if a default value is defined, creates the property from defaults + // NOTE: JSON schema does not enforce default values to be valid against schema. Swagger does. + createdFromDefaults[pName] = struct{}{} + if !o.Options.skipSchemataResult { + res.addPropertySchemata(val, pName, pSchema) // this shallow-clones the content of the pSchema pointer } } } - // Check patternProperties - // TODO: it looks like we have done that twice in many cases - for key, value := range val { - _, regularProperty := o.Properties[key] - matched, _ /*succeededOnce*/, patterns := o.validatePatternProperty(key, value, res) - if !regularProperty && (matched /*|| succeededOnce*/) { - for _, pName := range patterns { - if v, ok := o.PatternProperties[pName]; ok { - r := NewSchemaValidator(&v, o.Root, o.Path+"."+key, o.KnownFormats, o.Options.Options()...).Validate(value) - res.mergeForField(data.(map[string]interface{}), key, r) - } - } + if len(o.Required) == 0 { + return + } + + // Check required properties + for _, k := range o.Required { + v, ok := val[k] + if ok { + continue + } + _, isCreatedFromDefaults := createdFromDefaults[k] + if isCreatedFromDefaults { + continue } + + res.AddErrors(errors.Required(fmt.Sprintf("%s.%s", o.Path, k), o.In, v)) } - return res } // TODO: succeededOnce is not used anywhere func (o *objectValidator) validatePatternProperty(key string, value interface{}, result *Result) (bool, bool, []string) { + if len(o.PatternProperties) == 0 { + return false, false, nil + } + matched := false succeededOnce := false - var patterns []string + patterns := make([]string, 0, len(o.PatternProperties)) - for k, schema := range o.PatternProperties { - sch := schema - if match, _ := regexp.MatchString(k, key); match { - patterns = append(patterns, k) - matched = true - validator := NewSchemaValidator(&sch, o.Root, o.Path+"."+key, o.KnownFormats, o.Options.Options()...) + schema := pools.poolOfSchemas.BorrowSchema() + defer func() { + pools.poolOfSchemas.RedeemSchema(schema) + }() - res := validator.Validate(value) - result.Merge(res) + for k := range o.PatternProperties { + re, err := compileRegexp(k) + if err != nil { + continue } - } - // BUG(fredbi): can't get to here. Should remove dead code (commented out). + match := re.MatchString(key) + if !match { + continue + } - // if succeededOnce { - // result.Inc() - // } + *schema = o.PatternProperties[k] + patterns = append(patterns, k) + matched = true + validator := newSchemaValidator(schema, o.Root, fmt.Sprintf("%s.%s", o.Path, key), o.KnownFormats, o.Options) + + res := validator.Validate(value) + result.Merge(res) + } return matched, succeededOnce, patterns } + +func (o *objectValidator) redeem() { + pools.poolOfObjectValidators.RedeemValidator(o) +} diff --git a/vendor/github.com/go-openapi/validate/options.go b/vendor/github.com/go-openapi/validate/options.go index 8a22ce991148..cfe9b0660f60 100644 --- a/vendor/github.com/go-openapi/validate/options.go +++ b/vendor/github.com/go-openapi/validate/options.go @@ -31,6 +31,7 @@ type Opts struct { // GET:/v1/{shelve} and GET:/v1/{book}, where the IDs are "shelve/*" and // /"shelve/*/book/*" respectively. StrictPathParamUniqueness bool + SkipSchemataResult bool } var ( diff --git a/vendor/github.com/go-openapi/validate/pools.go b/vendor/github.com/go-openapi/validate/pools.go new file mode 100644 index 000000000000..3ddce4dcc2b4 --- /dev/null +++ b/vendor/github.com/go-openapi/validate/pools.go @@ -0,0 +1,366 @@ +//go:build !validatedebug + +package validate + +import ( + "sync" + + "github.com/go-openapi/spec" +) + +var pools allPools + +func init() { + resetPools() +} + +func resetPools() { + // NOTE: for testing purpose, we might want to reset pools after calling Validate twice. + // The pool is corrupted in that case: calling Put twice inserts a duplicate in the pool + // and further calls to Get are mishandled. + + pools = allPools{ + poolOfSchemaValidators: schemaValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &SchemaValidator{} + + return s + }, + }, + }, + poolOfObjectValidators: objectValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &objectValidator{} + + return s + }, + }, + }, + poolOfSliceValidators: sliceValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &schemaSliceValidator{} + + return s + }, + }, + }, + poolOfItemsValidators: itemsValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &itemsValidator{} + + return s + }, + }, + }, + poolOfBasicCommonValidators: basicCommonValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &basicCommonValidator{} + + return s + }, + }, + }, + poolOfHeaderValidators: headerValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &HeaderValidator{} + + return s + }, + }, + }, + poolOfParamValidators: paramValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &ParamValidator{} + + return s + }, + }, + }, + poolOfBasicSliceValidators: basicSliceValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &basicSliceValidator{} + + return s + }, + }, + }, + poolOfNumberValidators: numberValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &numberValidator{} + + return s + }, + }, + }, + poolOfStringValidators: stringValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &stringValidator{} + + return s + }, + }, + }, + poolOfSchemaPropsValidators: schemaPropsValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &schemaPropsValidator{} + + return s + }, + }, + }, + poolOfFormatValidators: formatValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &formatValidator{} + + return s + }, + }, + }, + poolOfTypeValidators: typeValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &typeValidator{} + + return s + }, + }, + }, + poolOfSchemas: schemasPool{ + Pool: &sync.Pool{ + New: func() any { + s := &spec.Schema{} + + return s + }, + }, + }, + poolOfResults: resultsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &Result{} + + return s + }, + }, + }, + } +} + +type ( + allPools struct { + // memory pools for all validator objects. + // + // Each pool can be borrowed from and redeemed to. + poolOfSchemaValidators schemaValidatorsPool + poolOfObjectValidators objectValidatorsPool + poolOfSliceValidators sliceValidatorsPool + poolOfItemsValidators itemsValidatorsPool + poolOfBasicCommonValidators basicCommonValidatorsPool + poolOfHeaderValidators headerValidatorsPool + poolOfParamValidators paramValidatorsPool + poolOfBasicSliceValidators basicSliceValidatorsPool + poolOfNumberValidators numberValidatorsPool + poolOfStringValidators stringValidatorsPool + poolOfSchemaPropsValidators schemaPropsValidatorsPool + poolOfFormatValidators formatValidatorsPool + poolOfTypeValidators typeValidatorsPool + poolOfSchemas schemasPool + poolOfResults resultsPool + } + + schemaValidatorsPool struct { + *sync.Pool + } + + objectValidatorsPool struct { + *sync.Pool + } + + sliceValidatorsPool struct { + *sync.Pool + } + + itemsValidatorsPool struct { + *sync.Pool + } + + basicCommonValidatorsPool struct { + *sync.Pool + } + + headerValidatorsPool struct { + *sync.Pool + } + + paramValidatorsPool struct { + *sync.Pool + } + + basicSliceValidatorsPool struct { + *sync.Pool + } + + numberValidatorsPool struct { + *sync.Pool + } + + stringValidatorsPool struct { + *sync.Pool + } + + schemaPropsValidatorsPool struct { + *sync.Pool + } + + formatValidatorsPool struct { + *sync.Pool + } + + typeValidatorsPool struct { + *sync.Pool + } + + schemasPool struct { + *sync.Pool + } + + resultsPool struct { + *sync.Pool + } +) + +func (p schemaValidatorsPool) BorrowValidator() *SchemaValidator { + return p.Get().(*SchemaValidator) +} + +func (p schemaValidatorsPool) RedeemValidator(s *SchemaValidator) { + // NOTE: s might be nil. In that case, Put is a noop. + p.Put(s) +} + +func (p objectValidatorsPool) BorrowValidator() *objectValidator { + return p.Get().(*objectValidator) +} + +func (p objectValidatorsPool) RedeemValidator(s *objectValidator) { + p.Put(s) +} + +func (p sliceValidatorsPool) BorrowValidator() *schemaSliceValidator { + return p.Get().(*schemaSliceValidator) +} + +func (p sliceValidatorsPool) RedeemValidator(s *schemaSliceValidator) { + p.Put(s) +} + +func (p itemsValidatorsPool) BorrowValidator() *itemsValidator { + return p.Get().(*itemsValidator) +} + +func (p itemsValidatorsPool) RedeemValidator(s *itemsValidator) { + p.Put(s) +} + +func (p basicCommonValidatorsPool) BorrowValidator() *basicCommonValidator { + return p.Get().(*basicCommonValidator) +} + +func (p basicCommonValidatorsPool) RedeemValidator(s *basicCommonValidator) { + p.Put(s) +} + +func (p headerValidatorsPool) BorrowValidator() *HeaderValidator { + return p.Get().(*HeaderValidator) +} + +func (p headerValidatorsPool) RedeemValidator(s *HeaderValidator) { + p.Put(s) +} + +func (p paramValidatorsPool) BorrowValidator() *ParamValidator { + return p.Get().(*ParamValidator) +} + +func (p paramValidatorsPool) RedeemValidator(s *ParamValidator) { + p.Put(s) +} + +func (p basicSliceValidatorsPool) BorrowValidator() *basicSliceValidator { + return p.Get().(*basicSliceValidator) +} + +func (p basicSliceValidatorsPool) RedeemValidator(s *basicSliceValidator) { + p.Put(s) +} + +func (p numberValidatorsPool) BorrowValidator() *numberValidator { + return p.Get().(*numberValidator) +} + +func (p numberValidatorsPool) RedeemValidator(s *numberValidator) { + p.Put(s) +} + +func (p stringValidatorsPool) BorrowValidator() *stringValidator { + return p.Get().(*stringValidator) +} + +func (p stringValidatorsPool) RedeemValidator(s *stringValidator) { + p.Put(s) +} + +func (p schemaPropsValidatorsPool) BorrowValidator() *schemaPropsValidator { + return p.Get().(*schemaPropsValidator) +} + +func (p schemaPropsValidatorsPool) RedeemValidator(s *schemaPropsValidator) { + p.Put(s) +} + +func (p formatValidatorsPool) BorrowValidator() *formatValidator { + return p.Get().(*formatValidator) +} + +func (p formatValidatorsPool) RedeemValidator(s *formatValidator) { + p.Put(s) +} + +func (p typeValidatorsPool) BorrowValidator() *typeValidator { + return p.Get().(*typeValidator) +} + +func (p typeValidatorsPool) RedeemValidator(s *typeValidator) { + p.Put(s) +} + +func (p schemasPool) BorrowSchema() *spec.Schema { + return p.Get().(*spec.Schema) +} + +func (p schemasPool) RedeemSchema(s *spec.Schema) { + p.Put(s) +} + +func (p resultsPool) BorrowResult() *Result { + return p.Get().(*Result).cleared() +} + +func (p resultsPool) RedeemResult(s *Result) { + if s == emptyResult { + return + } + p.Put(s) +} diff --git a/vendor/github.com/go-openapi/validate/pools_debug.go b/vendor/github.com/go-openapi/validate/pools_debug.go new file mode 100644 index 000000000000..12949f02a7e9 --- /dev/null +++ b/vendor/github.com/go-openapi/validate/pools_debug.go @@ -0,0 +1,1012 @@ +//go:build validatedebug + +package validate + +import ( + "fmt" + "runtime" + "sync" + "testing" + + "github.com/go-openapi/spec" +) + +// This version of the pools is to be used for debugging and testing, with build tag "validatedebug". +// +// In this mode, the pools are tracked for allocation and redemption of borrowed objects, so we can +// verify a few behaviors of the validators. The debug pools panic when an invalid usage pattern is detected. + +var pools allPools + +func init() { + resetPools() +} + +func resetPools() { + // NOTE: for testing purpose, we might want to reset pools after calling Validate twice. + // The pool is corrupted in that case: calling Put twice inserts a duplicate in the pool + // and further calls to Get are mishandled. + + pools = allPools{ + poolOfSchemaValidators: schemaValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &SchemaValidator{} + + return s + }, + }, + debugMap: make(map[*SchemaValidator]status), + allocMap: make(map[*SchemaValidator]string), + redeemMap: make(map[*SchemaValidator]string), + }, + poolOfObjectValidators: objectValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &objectValidator{} + + return s + }, + }, + debugMap: make(map[*objectValidator]status), + allocMap: make(map[*objectValidator]string), + redeemMap: make(map[*objectValidator]string), + }, + poolOfSliceValidators: sliceValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &schemaSliceValidator{} + + return s + }, + }, + debugMap: make(map[*schemaSliceValidator]status), + allocMap: make(map[*schemaSliceValidator]string), + redeemMap: make(map[*schemaSliceValidator]string), + }, + poolOfItemsValidators: itemsValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &itemsValidator{} + + return s + }, + }, + debugMap: make(map[*itemsValidator]status), + allocMap: make(map[*itemsValidator]string), + redeemMap: make(map[*itemsValidator]string), + }, + poolOfBasicCommonValidators: basicCommonValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &basicCommonValidator{} + + return s + }, + }, + debugMap: make(map[*basicCommonValidator]status), + allocMap: make(map[*basicCommonValidator]string), + redeemMap: make(map[*basicCommonValidator]string), + }, + poolOfHeaderValidators: headerValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &HeaderValidator{} + + return s + }, + }, + debugMap: make(map[*HeaderValidator]status), + allocMap: make(map[*HeaderValidator]string), + redeemMap: make(map[*HeaderValidator]string), + }, + poolOfParamValidators: paramValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &ParamValidator{} + + return s + }, + }, + debugMap: make(map[*ParamValidator]status), + allocMap: make(map[*ParamValidator]string), + redeemMap: make(map[*ParamValidator]string), + }, + poolOfBasicSliceValidators: basicSliceValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &basicSliceValidator{} + + return s + }, + }, + debugMap: make(map[*basicSliceValidator]status), + allocMap: make(map[*basicSliceValidator]string), + redeemMap: make(map[*basicSliceValidator]string), + }, + poolOfNumberValidators: numberValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &numberValidator{} + + return s + }, + }, + debugMap: make(map[*numberValidator]status), + allocMap: make(map[*numberValidator]string), + redeemMap: make(map[*numberValidator]string), + }, + poolOfStringValidators: stringValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &stringValidator{} + + return s + }, + }, + debugMap: make(map[*stringValidator]status), + allocMap: make(map[*stringValidator]string), + redeemMap: make(map[*stringValidator]string), + }, + poolOfSchemaPropsValidators: schemaPropsValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &schemaPropsValidator{} + + return s + }, + }, + debugMap: make(map[*schemaPropsValidator]status), + allocMap: make(map[*schemaPropsValidator]string), + redeemMap: make(map[*schemaPropsValidator]string), + }, + poolOfFormatValidators: formatValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &formatValidator{} + + return s + }, + }, + debugMap: make(map[*formatValidator]status), + allocMap: make(map[*formatValidator]string), + redeemMap: make(map[*formatValidator]string), + }, + poolOfTypeValidators: typeValidatorsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &typeValidator{} + + return s + }, + }, + debugMap: make(map[*typeValidator]status), + allocMap: make(map[*typeValidator]string), + redeemMap: make(map[*typeValidator]string), + }, + poolOfSchemas: schemasPool{ + Pool: &sync.Pool{ + New: func() any { + s := &spec.Schema{} + + return s + }, + }, + debugMap: make(map[*spec.Schema]status), + allocMap: make(map[*spec.Schema]string), + redeemMap: make(map[*spec.Schema]string), + }, + poolOfResults: resultsPool{ + Pool: &sync.Pool{ + New: func() any { + s := &Result{} + + return s + }, + }, + debugMap: make(map[*Result]status), + allocMap: make(map[*Result]string), + redeemMap: make(map[*Result]string), + }, + } +} + +const ( + statusFresh status = iota + 1 + statusRecycled + statusRedeemed +) + +func (s status) String() string { + switch s { + case statusFresh: + return "fresh" + case statusRecycled: + return "recycled" + case statusRedeemed: + return "redeemed" + default: + panic(fmt.Errorf("invalid status: %d", s)) + } +} + +type ( + // Debug + status uint8 + + allPools struct { + // memory pools for all validator objects. + // + // Each pool can be borrowed from and redeemed to. + poolOfSchemaValidators schemaValidatorsPool + poolOfObjectValidators objectValidatorsPool + poolOfSliceValidators sliceValidatorsPool + poolOfItemsValidators itemsValidatorsPool + poolOfBasicCommonValidators basicCommonValidatorsPool + poolOfHeaderValidators headerValidatorsPool + poolOfParamValidators paramValidatorsPool + poolOfBasicSliceValidators basicSliceValidatorsPool + poolOfNumberValidators numberValidatorsPool + poolOfStringValidators stringValidatorsPool + poolOfSchemaPropsValidators schemaPropsValidatorsPool + poolOfFormatValidators formatValidatorsPool + poolOfTypeValidators typeValidatorsPool + poolOfSchemas schemasPool + poolOfResults resultsPool + } + + schemaValidatorsPool struct { + *sync.Pool + debugMap map[*SchemaValidator]status + allocMap map[*SchemaValidator]string + redeemMap map[*SchemaValidator]string + mx sync.Mutex + } + + objectValidatorsPool struct { + *sync.Pool + debugMap map[*objectValidator]status + allocMap map[*objectValidator]string + redeemMap map[*objectValidator]string + mx sync.Mutex + } + + sliceValidatorsPool struct { + *sync.Pool + debugMap map[*schemaSliceValidator]status + allocMap map[*schemaSliceValidator]string + redeemMap map[*schemaSliceValidator]string + mx sync.Mutex + } + + itemsValidatorsPool struct { + *sync.Pool + debugMap map[*itemsValidator]status + allocMap map[*itemsValidator]string + redeemMap map[*itemsValidator]string + mx sync.Mutex + } + + basicCommonValidatorsPool struct { + *sync.Pool + debugMap map[*basicCommonValidator]status + allocMap map[*basicCommonValidator]string + redeemMap map[*basicCommonValidator]string + mx sync.Mutex + } + + headerValidatorsPool struct { + *sync.Pool + debugMap map[*HeaderValidator]status + allocMap map[*HeaderValidator]string + redeemMap map[*HeaderValidator]string + mx sync.Mutex + } + + paramValidatorsPool struct { + *sync.Pool + debugMap map[*ParamValidator]status + allocMap map[*ParamValidator]string + redeemMap map[*ParamValidator]string + mx sync.Mutex + } + + basicSliceValidatorsPool struct { + *sync.Pool + debugMap map[*basicSliceValidator]status + allocMap map[*basicSliceValidator]string + redeemMap map[*basicSliceValidator]string + mx sync.Mutex + } + + numberValidatorsPool struct { + *sync.Pool + debugMap map[*numberValidator]status + allocMap map[*numberValidator]string + redeemMap map[*numberValidator]string + mx sync.Mutex + } + + stringValidatorsPool struct { + *sync.Pool + debugMap map[*stringValidator]status + allocMap map[*stringValidator]string + redeemMap map[*stringValidator]string + mx sync.Mutex + } + + schemaPropsValidatorsPool struct { + *sync.Pool + debugMap map[*schemaPropsValidator]status + allocMap map[*schemaPropsValidator]string + redeemMap map[*schemaPropsValidator]string + mx sync.Mutex + } + + formatValidatorsPool struct { + *sync.Pool + debugMap map[*formatValidator]status + allocMap map[*formatValidator]string + redeemMap map[*formatValidator]string + mx sync.Mutex + } + + typeValidatorsPool struct { + *sync.Pool + debugMap map[*typeValidator]status + allocMap map[*typeValidator]string + redeemMap map[*typeValidator]string + mx sync.Mutex + } + + schemasPool struct { + *sync.Pool + debugMap map[*spec.Schema]status + allocMap map[*spec.Schema]string + redeemMap map[*spec.Schema]string + mx sync.Mutex + } + + resultsPool struct { + *sync.Pool + debugMap map[*Result]status + allocMap map[*Result]string + redeemMap map[*Result]string + mx sync.Mutex + } +) + +func (p *schemaValidatorsPool) BorrowValidator() *SchemaValidator { + s := p.Get().(*SchemaValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled schema should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *schemaValidatorsPool) RedeemValidator(s *SchemaValidator) { + // NOTE: s might be nil. In that case, Put is a noop. + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed schema should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed schema should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *objectValidatorsPool) BorrowValidator() *objectValidator { + s := p.Get().(*objectValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled object should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *objectValidatorsPool) RedeemValidator(s *objectValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed object should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed object should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *sliceValidatorsPool) BorrowValidator() *schemaSliceValidator { + s := p.Get().(*schemaSliceValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled schemaSliceValidator should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *sliceValidatorsPool) RedeemValidator(s *schemaSliceValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed schemaSliceValidator should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed schemaSliceValidator should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *itemsValidatorsPool) BorrowValidator() *itemsValidator { + s := p.Get().(*itemsValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled itemsValidator should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *itemsValidatorsPool) RedeemValidator(s *itemsValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed itemsValidator should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed itemsValidator should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *basicCommonValidatorsPool) BorrowValidator() *basicCommonValidator { + s := p.Get().(*basicCommonValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled basicCommonValidator should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *basicCommonValidatorsPool) RedeemValidator(s *basicCommonValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed basicCommonValidator should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed basicCommonValidator should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *headerValidatorsPool) BorrowValidator() *HeaderValidator { + s := p.Get().(*HeaderValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled HeaderValidator should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *headerValidatorsPool) RedeemValidator(s *HeaderValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed header should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed header should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *paramValidatorsPool) BorrowValidator() *ParamValidator { + s := p.Get().(*ParamValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled param should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *paramValidatorsPool) RedeemValidator(s *ParamValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed param should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed param should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *basicSliceValidatorsPool) BorrowValidator() *basicSliceValidator { + s := p.Get().(*basicSliceValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled basicSliceValidator should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *basicSliceValidatorsPool) RedeemValidator(s *basicSliceValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed basicSliceValidator should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed basicSliceValidator should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *numberValidatorsPool) BorrowValidator() *numberValidator { + s := p.Get().(*numberValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled number should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *numberValidatorsPool) RedeemValidator(s *numberValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed number should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed number should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *stringValidatorsPool) BorrowValidator() *stringValidator { + s := p.Get().(*stringValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled string should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *stringValidatorsPool) RedeemValidator(s *stringValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed string should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed string should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *schemaPropsValidatorsPool) BorrowValidator() *schemaPropsValidator { + s := p.Get().(*schemaPropsValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled param should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *schemaPropsValidatorsPool) RedeemValidator(s *schemaPropsValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed schemaProps should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed schemaProps should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *formatValidatorsPool) BorrowValidator() *formatValidator { + s := p.Get().(*formatValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled format should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *formatValidatorsPool) RedeemValidator(s *formatValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed format should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed format should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *typeValidatorsPool) BorrowValidator() *typeValidator { + s := p.Get().(*typeValidator) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled type should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *typeValidatorsPool) RedeemValidator(s *typeValidator) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed type should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic(fmt.Errorf("redeemed type should have been allocated from a fresh or recycled pointer. Got status %s, already redeamed at: %s", x, p.redeemMap[s])) + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *schemasPool) BorrowSchema() *spec.Schema { + s := p.Get().(*spec.Schema) + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled spec.Schema should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *schemasPool) RedeemSchema(s *spec.Schema) { + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed spec.Schema should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed spec.Schema should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *resultsPool) BorrowResult() *Result { + s := p.Get().(*Result).cleared() + + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + p.debugMap[s] = statusFresh + } else { + if x != statusRedeemed { + panic("recycled result should have been redeemed") + } + p.debugMap[s] = statusRecycled + } + p.allocMap[s] = caller() + + return s +} + +func (p *resultsPool) RedeemResult(s *Result) { + if s == emptyResult { + if len(s.Errors) > 0 || len(s.Warnings) > 0 { + panic("empty result should not mutate") + } + return + } + p.mx.Lock() + defer p.mx.Unlock() + x, ok := p.debugMap[s] + if !ok { + panic("redeemed Result should have been allocated") + } + if x != statusRecycled && x != statusFresh { + panic("redeemed Result should have been allocated from a fresh or recycled pointer") + } + p.debugMap[s] = statusRedeemed + p.redeemMap[s] = caller() + p.Put(s) +} + +func (p *allPools) allIsRedeemed(t testing.TB) bool { + outcome := true + for k, v := range p.poolOfSchemaValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("schemaValidator should be redeemed. Allocated by: %s", p.poolOfSchemaValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfObjectValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("objectValidator should be redeemed. Allocated by: %s", p.poolOfObjectValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfSliceValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("sliceValidator should be redeemed. Allocated by: %s", p.poolOfSliceValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfItemsValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("itemsValidator should be redeemed. Allocated by: %s", p.poolOfItemsValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfBasicCommonValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("basicCommonValidator should be redeemed. Allocated by: %s", p.poolOfBasicCommonValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfHeaderValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("headerValidator should be redeemed. Allocated by: %s", p.poolOfHeaderValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfParamValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("paramValidator should be redeemed. Allocated by: %s", p.poolOfParamValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfBasicSliceValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("basicSliceValidator should be redeemed. Allocated by: %s", p.poolOfBasicSliceValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfNumberValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("numberValidator should be redeemed. Allocated by: %s", p.poolOfNumberValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfStringValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("stringValidator should be redeemed. Allocated by: %s", p.poolOfStringValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfSchemaPropsValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("schemaPropsValidator should be redeemed. Allocated by: %s", p.poolOfSchemaPropsValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfFormatValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("formatValidator should be redeemed. Allocated by: %s", p.poolOfFormatValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfTypeValidators.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("typeValidator should be redeemed. Allocated by: %s", p.poolOfTypeValidators.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfSchemas.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("schemas should be redeemed. Allocated by: %s", p.poolOfSchemas.allocMap[k]) + outcome = false + } + for k, v := range p.poolOfResults.debugMap { + if v == statusRedeemed { + continue + } + t.Logf("result should be redeemed. Allocated by: %s", p.poolOfResults.allocMap[k]) + outcome = false + } + + return outcome +} + +func caller() string { + pc, _, _, _ := runtime.Caller(3) //nolint:dogsled + from, line := runtime.FuncForPC(pc).FileLine(pc) + + return fmt.Sprintf("%s:%d", from, line) +} diff --git a/vendor/github.com/go-openapi/validate/result.go b/vendor/github.com/go-openapi/validate/result.go index 0fe934fe6712..c80804a93d0b 100644 --- a/vendor/github.com/go-openapi/validate/result.go +++ b/vendor/github.com/go-openapi/validate/result.go @@ -15,7 +15,7 @@ package validate import ( - "fmt" + stderrors "errors" "reflect" "strings" @@ -23,6 +23,8 @@ import ( "github.com/go-openapi/spec" ) +var emptyResult = &Result{MatchCount: 1} + // Result represents a validation result set, composed of // errors and warnings. // @@ -50,8 +52,10 @@ type Result struct { // Schemata for slice items itemSchemata []itemSchemata - cachedFieldSchemta map[FieldKey][]*spec.Schema - cachedItemSchemata map[ItemKey][]*spec.Schema + cachedFieldSchemata map[FieldKey][]*spec.Schema + cachedItemSchemata map[ItemKey][]*spec.Schema + + wantsRedeemOnMerge bool } // FieldKey is a pair of an object and a field, usable as a key for a map. @@ -116,6 +120,9 @@ func (r *Result) Merge(others ...*Result) *Result { } r.mergeWithoutRootSchemata(other) r.rootObjectSchemata.Append(other.rootObjectSchemata) + if other.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(other) + } } return r } @@ -133,8 +140,8 @@ func (r *Result) RootObjectSchemata() []*spec.Schema { // FieldSchemata returns the schemata which apply to fields in objects. func (r *Result) FieldSchemata() map[FieldKey][]*spec.Schema { - if r.cachedFieldSchemta != nil { - return r.cachedFieldSchemta + if r.cachedFieldSchemata != nil { + return r.cachedFieldSchemata } ret := make(map[FieldKey][]*spec.Schema, len(r.fieldSchemata)) @@ -146,7 +153,8 @@ func (r *Result) FieldSchemata() map[FieldKey][]*spec.Schema { ret[key] = append(ret[key], fs.schemata.multiple...) } } - r.cachedFieldSchemta = ret + r.cachedFieldSchemata = ret + return ret } @@ -170,7 +178,7 @@ func (r *Result) ItemSchemata() map[ItemKey][]*spec.Schema { } func (r *Result) resetCaches() { - r.cachedFieldSchemta = nil + r.cachedFieldSchemata = nil r.cachedItemSchemata = nil } @@ -187,12 +195,16 @@ func (r *Result) mergeForField(obj map[string]interface{}, field string, other * if r.fieldSchemata == nil { r.fieldSchemata = make([]fieldSchemata, len(obj)) } + // clone other schemata, as other is about to be redeemed to the pool r.fieldSchemata = append(r.fieldSchemata, fieldSchemata{ obj: obj, field: field, - schemata: other.rootObjectSchemata, + schemata: other.rootObjectSchemata.Clone(), }) } + if other.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(other) + } return r } @@ -210,29 +222,38 @@ func (r *Result) mergeForSlice(slice reflect.Value, i int, other *Result) *Resul if r.itemSchemata == nil { r.itemSchemata = make([]itemSchemata, slice.Len()) } + // clone other schemata, as other is about to be redeemed to the pool r.itemSchemata = append(r.itemSchemata, itemSchemata{ slice: slice, index: i, - schemata: other.rootObjectSchemata, + schemata: other.rootObjectSchemata.Clone(), }) } + if other.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(other) + } + return r } // addRootObjectSchemata adds the given schemata for the root object of the result. -// The slice schemata might be reused. I.e. do not modify it after being added to a result. +// +// Since the slice schemata might be reused, it is shallow-cloned before saving it into the result. func (r *Result) addRootObjectSchemata(s *spec.Schema) { - r.rootObjectSchemata.Append(schemata{one: s}) + clone := *s + r.rootObjectSchemata.Append(schemata{one: &clone}) } // addPropertySchemata adds the given schemata for the object and field. -// The slice schemata might be reused. I.e. do not modify it after being added to a result. +// +// Since the slice schemata might be reused, it is shallow-cloned before saving it into the result. func (r *Result) addPropertySchemata(obj map[string]interface{}, fld string, schema *spec.Schema) { if r.fieldSchemata == nil { r.fieldSchemata = make([]fieldSchemata, 0, len(obj)) } - r.fieldSchemata = append(r.fieldSchemata, fieldSchemata{obj: obj, field: fld, schemata: schemata{one: schema}}) + clone := *schema + r.fieldSchemata = append(r.fieldSchemata, fieldSchemata{obj: obj, field: fld, schemata: schemata{one: &clone}}) } /* @@ -255,17 +276,21 @@ func (r *Result) mergeWithoutRootSchemata(other *Result) { if other.fieldSchemata != nil { if r.fieldSchemata == nil { - r.fieldSchemata = other.fieldSchemata - } else { - r.fieldSchemata = append(r.fieldSchemata, other.fieldSchemata...) + r.fieldSchemata = make([]fieldSchemata, 0, len(other.fieldSchemata)) + } + for _, field := range other.fieldSchemata { + field.schemata = field.schemata.Clone() + r.fieldSchemata = append(r.fieldSchemata, field) } } if other.itemSchemata != nil { if r.itemSchemata == nil { - r.itemSchemata = other.itemSchemata - } else { - r.itemSchemata = append(r.itemSchemata, other.itemSchemata...) + r.itemSchemata = make([]itemSchemata, 0, len(other.itemSchemata)) + } + for _, field := range other.itemSchemata { + field.schemata = field.schemata.Clone() + r.itemSchemata = append(r.itemSchemata, field) } } } @@ -280,6 +305,9 @@ func (r *Result) MergeAsErrors(others ...*Result) *Result { r.AddErrors(other.Errors...) r.AddErrors(other.Warnings...) r.MatchCount += other.MatchCount + if other.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(other) + } } } return r @@ -295,6 +323,9 @@ func (r *Result) MergeAsWarnings(others ...*Result) *Result { r.AddWarnings(other.Errors...) r.AddWarnings(other.Warnings...) r.MatchCount += other.MatchCount + if other.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(other) + } } } return r @@ -356,16 +387,21 @@ func (r *Result) keepRelevantErrors() *Result { strippedErrors := []error{} for _, e := range r.Errors { if strings.HasPrefix(e.Error(), "IMPORTANT!") { - strippedErrors = append(strippedErrors, fmt.Errorf(strings.TrimPrefix(e.Error(), "IMPORTANT!"))) + strippedErrors = append(strippedErrors, stderrors.New(strings.TrimPrefix(e.Error(), "IMPORTANT!"))) } } strippedWarnings := []error{} for _, e := range r.Warnings { if strings.HasPrefix(e.Error(), "IMPORTANT!") { - strippedWarnings = append(strippedWarnings, fmt.Errorf(strings.TrimPrefix(e.Error(), "IMPORTANT!"))) + strippedWarnings = append(strippedWarnings, stderrors.New(strings.TrimPrefix(e.Error(), "IMPORTANT!"))) } } - strippedResult := new(Result) + var strippedResult *Result + if r.wantsRedeemOnMerge { + strippedResult = pools.poolOfResults.BorrowResult() + } else { + strippedResult = new(Result) + } strippedResult.Errors = strippedErrors strippedResult.Warnings = strippedWarnings return strippedResult @@ -427,6 +463,27 @@ func (r *Result) AsError() error { return errors.CompositeValidationError(r.Errors...) } +func (r *Result) cleared() *Result { + // clear the Result to be reusable. Keep allocated capacity. + r.Errors = r.Errors[:0] + r.Warnings = r.Warnings[:0] + r.MatchCount = 0 + r.data = nil + r.rootObjectSchemata.one = nil + r.rootObjectSchemata.multiple = r.rootObjectSchemata.multiple[:0] + r.fieldSchemata = r.fieldSchemata[:0] + r.itemSchemata = r.itemSchemata[:0] + for k := range r.cachedFieldSchemata { + delete(r.cachedFieldSchemata, k) + } + for k := range r.cachedItemSchemata { + delete(r.cachedItemSchemata, k) + } + r.wantsRedeemOnMerge = true // mark this result as eligible for redeem when merged into another + + return r +} + // schemata is an arbitrary number of schemata. It does a distinction between zero, // one and many schemata to avoid slice allocations. type schemata struct { @@ -453,7 +510,7 @@ func (s *schemata) Slice() []*spec.Schema { return s.multiple } -// appendSchemata appends the schemata in other to s. It mutated s in-place. +// appendSchemata appends the schemata in other to s. It mutates s in-place. func (s *schemata) Append(other schemata) { if other.one == nil && len(other.multiple) == 0 { return @@ -484,3 +541,23 @@ func (s *schemata) Append(other schemata) { } } } + +func (s schemata) Clone() schemata { + var clone schemata + + if s.one != nil { + clone.one = new(spec.Schema) + *clone.one = *s.one + } + + if len(s.multiple) > 0 { + clone.multiple = make([]*spec.Schema, len(s.multiple)) + for idx := 0; idx < len(s.multiple); idx++ { + sp := new(spec.Schema) + *sp = *s.multiple[idx] + clone.multiple[idx] = sp + } + } + + return clone +} diff --git a/vendor/github.com/go-openapi/validate/schema.go b/vendor/github.com/go-openapi/validate/schema.go index 62b91dc5b0fd..db65264fd106 100644 --- a/vendor/github.com/go-openapi/validate/schema.go +++ b/vendor/github.com/go-openapi/validate/schema.go @@ -24,32 +24,32 @@ import ( "github.com/go-openapi/swag" ) -var ( - specSchemaType = reflect.TypeOf(&spec.Schema{}) - specParameterType = reflect.TypeOf(&spec.Parameter{}) - specHeaderType = reflect.TypeOf(&spec.Header{}) - // specItemsType = reflect.TypeOf(&spec.Items{}) -) - // SchemaValidator validates data against a JSON schema type SchemaValidator struct { Path string in string Schema *spec.Schema - validators []valueValidator + validators [8]valueValidator Root interface{} KnownFormats strfmt.Registry - Options SchemaValidatorOptions + Options *SchemaValidatorOptions } // AgainstSchema validates the specified data against the provided schema, using a registry of supported formats. // // When no pre-parsed *spec.Schema structure is provided, it uses a JSON schema as default. See example. func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registry, options ...Option) error { - res := NewSchemaValidator(schema, nil, "", formats, options...).Validate(data) + res := NewSchemaValidator(schema, nil, "", formats, + append(options, WithRecycleValidators(true), withRecycleResults(true))..., + ).Validate(data) + defer func() { + pools.poolOfResults.RedeemResult(res) + }() + if res.HasErrors() { return errors.CompositeValidationError(res.Errors...) } + return nil } @@ -57,6 +57,15 @@ func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registr // // Panics if the provided schema is invalid. func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry, options ...Option) *SchemaValidator { + opts := new(SchemaValidatorOptions) + for _, o := range options { + o(opts) + } + + return newSchemaValidator(schema, rootSchema, root, formats, opts) +} + +func newSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry, opts *SchemaValidatorOptions) *SchemaValidator { if schema == nil { return nil } @@ -72,17 +81,26 @@ func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string panic(msg) } } - s := SchemaValidator{ - Path: root, - in: "body", - Schema: schema, - Root: rootSchema, - KnownFormats: formats, - Options: SchemaValidatorOptions{}} - for _, o := range options { - o(&s.Options) + + if opts == nil { + opts = new(SchemaValidatorOptions) } - s.validators = []valueValidator{ + + var s *SchemaValidator + if opts.recycleValidators { + s = pools.poolOfSchemaValidators.BorrowValidator() + } else { + s = new(SchemaValidator) + } + + s.Path = root + s.in = "body" + s.Schema = schema + s.Root = rootSchema + s.Options = opts + s.KnownFormats = formats + + s.validators = [8]valueValidator{ s.typeValidator(), s.schemaPropsValidator(), s.stringValidator(), @@ -92,7 +110,8 @@ func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string s.commonValidator(), s.objectValidator(), } - return &s + + return s } // SetPath sets the path for this schema valdiator @@ -108,17 +127,39 @@ func (s *SchemaValidator) Applies(source interface{}, _ reflect.Kind) bool { // Validate validates the data against the schema func (s *SchemaValidator) Validate(data interface{}) *Result { - result := &Result{data: data} if s == nil { - return result + return emptyResult } - if s.Schema != nil { + + if s.Options.recycleValidators { + defer func() { + s.redeemChildren() + s.redeem() // one-time use validator + }() + } + + var result *Result + if s.Options.recycleResult { + result = pools.poolOfResults.BorrowResult() + result.data = data + } else { + result = &Result{data: data} + } + + if s.Schema != nil && !s.Options.skipSchemataResult { result.addRootObjectSchemata(s.Schema) } if data == nil { + // early exit with minimal validation result.Merge(s.validators[0].Validate(data)) // type validator result.Merge(s.validators[6].Validate(data)) // common validator + + if s.Options.recycleValidators { + s.validators[0] = nil + s.validators[6] = nil + } + return result } @@ -147,6 +188,7 @@ func (s *SchemaValidator) Validate(data interface{}) *Result { if erri != nil { result.AddErrors(invalidTypeConversionMsg(s.Path, erri)) result.Inc() + return result } d = in @@ -155,6 +197,7 @@ func (s *SchemaValidator) Validate(data interface{}) *Result { if errf != nil { result.AddErrors(invalidTypeConversionMsg(s.Path, errf)) result.Inc() + return result } d = nf @@ -164,14 +207,26 @@ func (s *SchemaValidator) Validate(data interface{}) *Result { kind = tpe.Kind() } - for _, v := range s.validators { + for idx, v := range s.validators { if !v.Applies(s.Schema, kind) { - debugLog("%T does not apply for %v", v, kind) + if s.Options.recycleValidators { + // Validate won't be called, so relinquish this validator + if redeemableChildren, ok := v.(interface{ redeemChildren() }); ok { + redeemableChildren.redeemChildren() + } + if redeemable, ok := v.(interface{ redeem() }); ok { + redeemable.redeem() + } + s.validators[idx] = nil // prevents further (unsafe) usage + } + continue } - err := v.Validate(d) - result.Merge(err) + result.Merge(v.Validate(d)) + if s.Options.recycleValidators { + s.validators[idx] = nil // prevents further (unsafe) usage + } result.Inc() } result.Inc() @@ -180,81 +235,120 @@ func (s *SchemaValidator) Validate(data interface{}) *Result { } func (s *SchemaValidator) typeValidator() valueValidator { - return &typeValidator{Type: s.Schema.Type, Nullable: s.Schema.Nullable, Format: s.Schema.Format, In: s.in, Path: s.Path} + return newTypeValidator( + s.Path, + s.in, + s.Schema.Type, + s.Schema.Nullable, + s.Schema.Format, + s.Options, + ) } func (s *SchemaValidator) commonValidator() valueValidator { - return &basicCommonValidator{ - Path: s.Path, - In: s.in, - Enum: s.Schema.Enum, - } + return newBasicCommonValidator( + s.Path, + s.in, + s.Schema.Default, + s.Schema.Enum, + s.Options, + ) } func (s *SchemaValidator) sliceValidator() valueValidator { - return &schemaSliceValidator{ - Path: s.Path, - In: s.in, - MaxItems: s.Schema.MaxItems, - MinItems: s.Schema.MinItems, - UniqueItems: s.Schema.UniqueItems, - AdditionalItems: s.Schema.AdditionalItems, - Items: s.Schema.Items, - Root: s.Root, - KnownFormats: s.KnownFormats, - Options: s.Options, - } + return newSliceValidator( + s.Path, + s.in, + s.Schema.MaxItems, + s.Schema.MinItems, + s.Schema.UniqueItems, + s.Schema.AdditionalItems, + s.Schema.Items, + s.Root, + s.KnownFormats, + s.Options, + ) } func (s *SchemaValidator) numberValidator() valueValidator { - return &numberValidator{ - Path: s.Path, - In: s.in, - Default: s.Schema.Default, - MultipleOf: s.Schema.MultipleOf, - Maximum: s.Schema.Maximum, - ExclusiveMaximum: s.Schema.ExclusiveMaximum, - Minimum: s.Schema.Minimum, - ExclusiveMinimum: s.Schema.ExclusiveMinimum, - } + return newNumberValidator( + s.Path, + s.in, + s.Schema.Default, + s.Schema.MultipleOf, + s.Schema.Maximum, + s.Schema.ExclusiveMaximum, + s.Schema.Minimum, + s.Schema.ExclusiveMinimum, + "", + "", + s.Options, + ) } func (s *SchemaValidator) stringValidator() valueValidator { - return &stringValidator{ - Path: s.Path, - In: s.in, - MaxLength: s.Schema.MaxLength, - MinLength: s.Schema.MinLength, - Pattern: s.Schema.Pattern, - } + return newStringValidator( + s.Path, + s.in, + nil, + false, + false, + s.Schema.MaxLength, + s.Schema.MinLength, + s.Schema.Pattern, + s.Options, + ) } func (s *SchemaValidator) formatValidator() valueValidator { - return &formatValidator{ - Path: s.Path, - In: s.in, - Format: s.Schema.Format, - KnownFormats: s.KnownFormats, - } + return newFormatValidator( + s.Path, + s.in, + s.Schema.Format, + s.KnownFormats, + s.Options, + ) } func (s *SchemaValidator) schemaPropsValidator() valueValidator { sch := s.Schema - return newSchemaPropsValidator(s.Path, s.in, sch.AllOf, sch.OneOf, sch.AnyOf, sch.Not, sch.Dependencies, s.Root, s.KnownFormats, s.Options.Options()...) + return newSchemaPropsValidator( + s.Path, s.in, sch.AllOf, sch.OneOf, sch.AnyOf, sch.Not, sch.Dependencies, s.Root, s.KnownFormats, + s.Options, + ) } func (s *SchemaValidator) objectValidator() valueValidator { - return &objectValidator{ - Path: s.Path, - In: s.in, - MaxProperties: s.Schema.MaxProperties, - MinProperties: s.Schema.MinProperties, - Required: s.Schema.Required, - Properties: s.Schema.Properties, - AdditionalProperties: s.Schema.AdditionalProperties, - PatternProperties: s.Schema.PatternProperties, - Root: s.Root, - KnownFormats: s.KnownFormats, - Options: s.Options, + return newObjectValidator( + s.Path, + s.in, + s.Schema.MaxProperties, + s.Schema.MinProperties, + s.Schema.Required, + s.Schema.Properties, + s.Schema.AdditionalProperties, + s.Schema.PatternProperties, + s.Root, + s.KnownFormats, + s.Options, + ) +} + +func (s *SchemaValidator) redeem() { + pools.poolOfSchemaValidators.RedeemValidator(s) +} + +func (s *SchemaValidator) redeemChildren() { + for i, validator := range s.validators { + if validator == nil { + continue + } + if redeemableChildren, ok := validator.(interface{ redeemChildren() }); ok { + redeemableChildren.redeemChildren() + } + if redeemable, ok := validator.(interface{ redeem() }); ok { + redeemable.redeem() + } + s.validators[i] = nil // free up allocated children if not in pool } } diff --git a/vendor/github.com/go-openapi/validate/schema_option.go b/vendor/github.com/go-openapi/validate/schema_option.go index 4b4879de8b1f..65eeebeaab31 100644 --- a/vendor/github.com/go-openapi/validate/schema_option.go +++ b/vendor/github.com/go-openapi/validate/schema_option.go @@ -18,6 +18,9 @@ package validate type SchemaValidatorOptions struct { EnableObjectArrayTypeCheck bool EnableArrayMustHaveItemsCheck bool + recycleValidators bool + recycleResult bool + skipSchemataResult bool } // Option sets optional rules for schema validation @@ -45,10 +48,36 @@ func SwaggerSchema(enable bool) Option { } } -// Options returns current options +// WithRecycleValidators saves memory allocations and makes validators +// available for a single use of Validate() only. +// +// When a validator is recycled, called MUST not call the Validate() method twice. +func WithRecycleValidators(enable bool) Option { + return func(svo *SchemaValidatorOptions) { + svo.recycleValidators = enable + } +} + +func withRecycleResults(enable bool) Option { + return func(svo *SchemaValidatorOptions) { + svo.recycleResult = enable + } +} + +// WithSkipSchemataResult skips the deep audit payload stored in validation Result +func WithSkipSchemataResult(enable bool) Option { + return func(svo *SchemaValidatorOptions) { + svo.skipSchemataResult = enable + } +} + +// Options returns the current set of options func (svo SchemaValidatorOptions) Options() []Option { return []Option{ EnableObjectArrayTypeCheck(svo.EnableObjectArrayTypeCheck), EnableArrayMustHaveItemsCheck(svo.EnableArrayMustHaveItemsCheck), + WithRecycleValidators(svo.recycleValidators), + withRecycleResults(svo.recycleResult), + WithSkipSchemataResult(svo.skipSchemataResult), } } diff --git a/vendor/github.com/go-openapi/validate/schema_props.go b/vendor/github.com/go-openapi/validate/schema_props.go index 9bac3d29fb9d..1ca379244dc7 100644 --- a/vendor/github.com/go-openapi/validate/schema_props.go +++ b/vendor/github.com/go-openapi/validate/schema_props.go @@ -30,211 +30,327 @@ type schemaPropsValidator struct { AnyOf []spec.Schema Not *spec.Schema Dependencies spec.Dependencies - anyOfValidators []SchemaValidator - allOfValidators []SchemaValidator - oneOfValidators []SchemaValidator + anyOfValidators []*SchemaValidator + allOfValidators []*SchemaValidator + oneOfValidators []*SchemaValidator notValidator *SchemaValidator Root interface{} KnownFormats strfmt.Registry - Options SchemaValidatorOptions + Options *SchemaValidatorOptions } func (s *schemaPropsValidator) SetPath(path string) { s.Path = path } -func newSchemaPropsValidator(path string, in string, allOf, oneOf, anyOf []spec.Schema, not *spec.Schema, deps spec.Dependencies, root interface{}, formats strfmt.Registry, options ...Option) *schemaPropsValidator { - anyValidators := make([]SchemaValidator, 0, len(anyOf)) - for _, v := range anyOf { - v := v - anyValidators = append(anyValidators, *NewSchemaValidator(&v, root, path, formats, options...)) +func newSchemaPropsValidator( + path string, in string, allOf, oneOf, anyOf []spec.Schema, not *spec.Schema, deps spec.Dependencies, root interface{}, formats strfmt.Registry, + opts *SchemaValidatorOptions) *schemaPropsValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) } - allValidators := make([]SchemaValidator, 0, len(allOf)) - for _, v := range allOf { - v := v - allValidators = append(allValidators, *NewSchemaValidator(&v, root, path, formats, options...)) + + anyValidators := make([]*SchemaValidator, 0, len(anyOf)) + for i := range anyOf { + anyValidators = append(anyValidators, newSchemaValidator(&anyOf[i], root, path, formats, opts)) + } + allValidators := make([]*SchemaValidator, 0, len(allOf)) + for i := range allOf { + allValidators = append(allValidators, newSchemaValidator(&allOf[i], root, path, formats, opts)) } - oneValidators := make([]SchemaValidator, 0, len(oneOf)) - for _, v := range oneOf { - v := v - oneValidators = append(oneValidators, *NewSchemaValidator(&v, root, path, formats, options...)) + oneValidators := make([]*SchemaValidator, 0, len(oneOf)) + for i := range oneOf { + oneValidators = append(oneValidators, newSchemaValidator(&oneOf[i], root, path, formats, opts)) } var notValidator *SchemaValidator if not != nil { - notValidator = NewSchemaValidator(not, root, path, formats, options...) - } - - schOptions := &SchemaValidatorOptions{} - for _, o := range options { - o(schOptions) - } - return &schemaPropsValidator{ - Path: path, - In: in, - AllOf: allOf, - OneOf: oneOf, - AnyOf: anyOf, - Not: not, - Dependencies: deps, - anyOfValidators: anyValidators, - allOfValidators: allValidators, - oneOfValidators: oneValidators, - notValidator: notValidator, - Root: root, - KnownFormats: formats, - Options: *schOptions, + notValidator = newSchemaValidator(not, root, path, formats, opts) + } + + var s *schemaPropsValidator + if opts.recycleValidators { + s = pools.poolOfSchemaPropsValidators.BorrowValidator() + } else { + s = new(schemaPropsValidator) } + + s.Path = path + s.In = in + s.AllOf = allOf + s.OneOf = oneOf + s.AnyOf = anyOf + s.Not = not + s.Dependencies = deps + s.anyOfValidators = anyValidators + s.allOfValidators = allValidators + s.oneOfValidators = oneValidators + s.notValidator = notValidator + s.Root = root + s.KnownFormats = formats + s.Options = opts + + return s } -func (s *schemaPropsValidator) Applies(source interface{}, kind reflect.Kind) bool { - r := reflect.TypeOf(source) == specSchemaType - debugLog("schema props validator for %q applies %t for %T (kind: %v)\n", s.Path, r, source, kind) - return r +func (s *schemaPropsValidator) Applies(source interface{}, _ reflect.Kind) bool { + _, isSchema := source.(*spec.Schema) + return isSchema } func (s *schemaPropsValidator) Validate(data interface{}) *Result { - mainResult := new(Result) + var mainResult *Result + if s.Options.recycleResult { + mainResult = pools.poolOfResults.BorrowResult() + } else { + mainResult = new(Result) + } // Intermediary error results // IMPORTANT! messages from underlying validators - keepResultAnyOf := new(Result) - keepResultOneOf := new(Result) - keepResultAllOf := new(Result) + var keepResultAnyOf, keepResultOneOf, keepResultAllOf *Result + + if s.Options.recycleValidators { + defer func() { + s.redeemChildren() + s.redeem() + + // results are redeemed when merged + }() + } - // Validates at least one in anyOf schemas - var firstSuccess *Result if len(s.anyOfValidators) > 0 { - var bestFailures *Result - succeededOnce := false - for _, anyOfSchema := range s.anyOfValidators { - result := anyOfSchema.Validate(data) - // We keep inner IMPORTANT! errors no matter what MatchCount tells us - keepResultAnyOf.Merge(result.keepRelevantErrors()) - if result.IsValid() { - bestFailures = nil - succeededOnce = true - if firstSuccess == nil { - firstSuccess = result - } - keepResultAnyOf = new(Result) - break - } - // MatchCount is used to select errors from the schema with most positive checks - if bestFailures == nil || result.MatchCount > bestFailures.MatchCount { - bestFailures = result + keepResultAnyOf = pools.poolOfResults.BorrowResult() + s.validateAnyOf(data, mainResult, keepResultAnyOf) + } + + if len(s.oneOfValidators) > 0 { + keepResultOneOf = pools.poolOfResults.BorrowResult() + s.validateOneOf(data, mainResult, keepResultOneOf) + } + + if len(s.allOfValidators) > 0 { + keepResultAllOf = pools.poolOfResults.BorrowResult() + s.validateAllOf(data, mainResult, keepResultAllOf) + } + + if s.notValidator != nil { + s.validateNot(data, mainResult) + } + + if s.Dependencies != nil && len(s.Dependencies) > 0 && reflect.TypeOf(data).Kind() == reflect.Map { + s.validateDependencies(data, mainResult) + } + + mainResult.Inc() + + // In the end we retain best failures for schema validation + // plus, if any, composite errors which may explain special cases (tagged as IMPORTANT!). + return mainResult.Merge(keepResultAllOf, keepResultOneOf, keepResultAnyOf) +} + +func (s *schemaPropsValidator) validateAnyOf(data interface{}, mainResult, keepResultAnyOf *Result) { + // Validates at least one in anyOf schemas + var bestFailures *Result + + for i, anyOfSchema := range s.anyOfValidators { + result := anyOfSchema.Validate(data) + if s.Options.recycleValidators { + s.anyOfValidators[i] = nil + } + // We keep inner IMPORTANT! errors no matter what MatchCount tells us + keepResultAnyOf.Merge(result.keepRelevantErrors()) // merges (and redeems) a new instance of Result + + if result.IsValid() { + if bestFailures != nil && bestFailures.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(bestFailures) } + + _ = keepResultAnyOf.cleared() + mainResult.Merge(result) + + return } - if !succeededOnce { - mainResult.AddErrors(mustValidateAtLeastOneSchemaMsg(s.Path)) + // MatchCount is used to select errors from the schema with most positive checks + if bestFailures == nil || result.MatchCount > bestFailures.MatchCount { + if bestFailures != nil && bestFailures.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(bestFailures) + } + bestFailures = result + + continue } - if bestFailures != nil { - mainResult.Merge(bestFailures) - } else if firstSuccess != nil { - mainResult.Merge(firstSuccess) + + if result.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(result) // this result is ditched } } + mainResult.AddErrors(mustValidateAtLeastOneSchemaMsg(s.Path)) + mainResult.Merge(bestFailures) +} + +func (s *schemaPropsValidator) validateOneOf(data interface{}, mainResult, keepResultOneOf *Result) { // Validates exactly one in oneOf schemas - if len(s.oneOfValidators) > 0 { - var bestFailures *Result - var firstSuccess *Result - validated := 0 - - for _, oneOfSchema := range s.oneOfValidators { - result := oneOfSchema.Validate(data) - // We keep inner IMPORTANT! errors no matter what MatchCount tells us - keepResultOneOf.Merge(result.keepRelevantErrors()) - if result.IsValid() { - validated++ - bestFailures = nil - if firstSuccess == nil { - firstSuccess = result - } - keepResultOneOf = new(Result) - continue - } - // MatchCount is used to select errors from the schema with most positive checks - if validated == 0 && (bestFailures == nil || result.MatchCount > bestFailures.MatchCount) { - bestFailures = result - } + var ( + firstSuccess, bestFailures *Result + validated int + ) + + for i, oneOfSchema := range s.oneOfValidators { + result := oneOfSchema.Validate(data) + if s.Options.recycleValidators { + s.oneOfValidators[i] = nil } - if validated != 1 { - var additionalMsg string - if validated == 0 { - additionalMsg = "Found none valid" - } else { - additionalMsg = fmt.Sprintf("Found %d valid alternatives", validated) - } + // We keep inner IMPORTANT! errors no matter what MatchCount tells us + keepResultOneOf.Merge(result.keepRelevantErrors()) // merges (and redeems) a new instance of Result - mainResult.AddErrors(mustValidateOnlyOneSchemaMsg(s.Path, additionalMsg)) - if bestFailures != nil { - mainResult.Merge(bestFailures) - } - } else if firstSuccess != nil { - mainResult.Merge(firstSuccess) - } - } + if result.IsValid() { + validated++ + _ = keepResultOneOf.cleared() - // Validates all of allOf schemas - if len(s.allOfValidators) > 0 { - validated := 0 - - for _, allOfSchema := range s.allOfValidators { - result := allOfSchema.Validate(data) - // We keep inner IMPORTANT! errors no matter what MatchCount tells us - keepResultAllOf.Merge(result.keepRelevantErrors()) - // keepResultAllOf.Merge(result) - if result.IsValid() { - validated++ + if firstSuccess == nil { + firstSuccess = result + } else if result.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(result) // this result is ditched } - mainResult.Merge(result) + + continue } - if validated != len(s.allOfValidators) { - additionalMsg := "" - if validated == 0 { - additionalMsg = ". None validated" + // MatchCount is used to select errors from the schema with most positive checks + if validated == 0 && (bestFailures == nil || result.MatchCount > bestFailures.MatchCount) { + if bestFailures != nil && bestFailures.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(bestFailures) } + bestFailures = result + } else if result.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(result) // this result is ditched + } + } - mainResult.AddErrors(mustValidateAllSchemasMsg(s.Path, additionalMsg)) + switch validated { + case 0: + mainResult.AddErrors(mustValidateOnlyOneSchemaMsg(s.Path, "Found none valid")) + mainResult.Merge(bestFailures) + // firstSucess necessarily nil + case 1: + mainResult.Merge(firstSuccess) + if bestFailures != nil && bestFailures.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(bestFailures) + } + default: + mainResult.AddErrors(mustValidateOnlyOneSchemaMsg(s.Path, fmt.Sprintf("Found %d valid alternatives", validated))) + mainResult.Merge(bestFailures) + if firstSuccess != nil && firstSuccess.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(firstSuccess) } } +} - if s.notValidator != nil { - result := s.notValidator.Validate(data) +func (s *schemaPropsValidator) validateAllOf(data interface{}, mainResult, keepResultAllOf *Result) { + // Validates all of allOf schemas + var validated int + + for i, allOfSchema := range s.allOfValidators { + result := allOfSchema.Validate(data) + if s.Options.recycleValidators { + s.allOfValidators[i] = nil + } // We keep inner IMPORTANT! errors no matter what MatchCount tells us + keepResultAllOf.Merge(result.keepRelevantErrors()) if result.IsValid() { - mainResult.AddErrors(mustNotValidatechemaMsg(s.Path)) + validated++ } + mainResult.Merge(result) } - if s.Dependencies != nil && len(s.Dependencies) > 0 && reflect.TypeOf(data).Kind() == reflect.Map { - val := data.(map[string]interface{}) - for key := range val { - if dep, ok := s.Dependencies[key]; ok { + switch validated { + case 0: + mainResult.AddErrors(mustValidateAllSchemasMsg(s.Path, ". None validated")) + case len(s.allOfValidators): + default: + mainResult.AddErrors(mustValidateAllSchemasMsg(s.Path, "")) + } +} - if dep.Schema != nil { - mainResult.Merge(NewSchemaValidator(dep.Schema, s.Root, s.Path+"."+key, s.KnownFormats, s.Options.Options()...).Validate(data)) - continue - } +func (s *schemaPropsValidator) validateNot(data interface{}, mainResult *Result) { + result := s.notValidator.Validate(data) + if s.Options.recycleValidators { + s.notValidator = nil + } + // We keep inner IMPORTANT! errors no matter what MatchCount tells us + if result.IsValid() { + mainResult.AddErrors(mustNotValidatechemaMsg(s.Path)) + } + if result.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(result) // this result is ditched + } +} + +func (s *schemaPropsValidator) validateDependencies(data interface{}, mainResult *Result) { + val := data.(map[string]interface{}) + for key := range val { + dep, ok := s.Dependencies[key] + if !ok { + continue + } + + if dep.Schema != nil { + mainResult.Merge( + newSchemaValidator(dep.Schema, s.Root, s.Path+"."+key, s.KnownFormats, s.Options).Validate(data), + ) + continue + } - if len(dep.Property) > 0 { - for _, depKey := range dep.Property { - if _, ok := val[depKey]; !ok { - mainResult.AddErrors(hasADependencyMsg(s.Path, depKey)) - } - } + if len(dep.Property) > 0 { + for _, depKey := range dep.Property { + if _, ok := val[depKey]; !ok { + mainResult.AddErrors(hasADependencyMsg(s.Path, depKey)) } } } } +} - mainResult.Inc() - // In the end we retain best failures for schema validation - // plus, if any, composite errors which may explain special cases (tagged as IMPORTANT!). - return mainResult.Merge(keepResultAllOf, keepResultOneOf, keepResultAnyOf) +func (s *schemaPropsValidator) redeem() { + pools.poolOfSchemaPropsValidators.RedeemValidator(s) +} + +func (s *schemaPropsValidator) redeemChildren() { + for _, v := range s.anyOfValidators { + if v == nil { + continue + } + v.redeemChildren() + v.redeem() + } + s.anyOfValidators = nil + + for _, v := range s.allOfValidators { + if v == nil { + continue + } + v.redeemChildren() + v.redeem() + } + s.allOfValidators = nil + + for _, v := range s.oneOfValidators { + if v == nil { + continue + } + v.redeemChildren() + v.redeem() + } + s.oneOfValidators = nil + + if s.notValidator != nil { + s.notValidator.redeemChildren() + s.notValidator.redeem() + s.notValidator = nil + } } diff --git a/vendor/github.com/go-openapi/validate/slice_validator.go b/vendor/github.com/go-openapi/validate/slice_validator.go index aa429f5184e6..13bb02087d91 100644 --- a/vendor/github.com/go-openapi/validate/slice_validator.go +++ b/vendor/github.com/go-openapi/validate/slice_validator.go @@ -32,7 +32,36 @@ type schemaSliceValidator struct { Items *spec.SchemaOrArray Root interface{} KnownFormats strfmt.Registry - Options SchemaValidatorOptions + Options *SchemaValidatorOptions +} + +func newSliceValidator(path, in string, + maxItems, minItems *int64, uniqueItems bool, + additionalItems *spec.SchemaOrBool, items *spec.SchemaOrArray, + root interface{}, formats strfmt.Registry, opts *SchemaValidatorOptions) *schemaSliceValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var v *schemaSliceValidator + if opts.recycleValidators { + v = pools.poolOfSliceValidators.BorrowValidator() + } else { + v = new(schemaSliceValidator) + } + + v.Path = path + v.In = in + v.MaxItems = maxItems + v.MinItems = minItems + v.UniqueItems = uniqueItems + v.AdditionalItems = additionalItems + v.Items = items + v.Root = root + v.KnownFormats = formats + v.Options = opts + + return v } func (s *schemaSliceValidator) SetPath(path string) { @@ -46,7 +75,18 @@ func (s *schemaSliceValidator) Applies(source interface{}, kind reflect.Kind) bo } func (s *schemaSliceValidator) Validate(data interface{}) *Result { - result := new(Result) + if s.Options.recycleValidators { + defer func() { + s.redeem() + }() + } + + var result *Result + if s.Options.recycleResult { + result = pools.poolOfResults.BorrowResult() + } else { + result = new(Result) + } if data == nil { return result } @@ -54,8 +94,8 @@ func (s *schemaSliceValidator) Validate(data interface{}) *Result { size := val.Len() if s.Items != nil && s.Items.Schema != nil { - validator := NewSchemaValidator(s.Items.Schema, s.Root, s.Path, s.KnownFormats, s.Options.Options()...) for i := 0; i < size; i++ { + validator := newSchemaValidator(s.Items.Schema, s.Root, s.Path, s.KnownFormats, s.Options) validator.SetPath(fmt.Sprintf("%s.%d", s.Path, i)) value := val.Index(i) result.mergeForSlice(val, i, validator.Validate(value.Interface())) @@ -66,10 +106,11 @@ func (s *schemaSliceValidator) Validate(data interface{}) *Result { if s.Items != nil && len(s.Items.Schemas) > 0 { itemsSize = len(s.Items.Schemas) for i := 0; i < itemsSize; i++ { - validator := NewSchemaValidator(&s.Items.Schemas[i], s.Root, fmt.Sprintf("%s.%d", s.Path, i), s.KnownFormats, s.Options.Options()...) - if val.Len() <= i { + if size <= i { break } + + validator := newSchemaValidator(&s.Items.Schemas[i], s.Root, fmt.Sprintf("%s.%d", s.Path, i), s.KnownFormats, s.Options) result.mergeForSlice(val, i, validator.Validate(val.Index(i).Interface())) } } @@ -79,7 +120,7 @@ func (s *schemaSliceValidator) Validate(data interface{}) *Result { } if s.AdditionalItems.Schema != nil { for i := itemsSize; i < size-itemsSize+1; i++ { - validator := NewSchemaValidator(s.AdditionalItems.Schema, s.Root, fmt.Sprintf("%s.%d", s.Path, i), s.KnownFormats, s.Options.Options()...) + validator := newSchemaValidator(s.AdditionalItems.Schema, s.Root, fmt.Sprintf("%s.%d", s.Path, i), s.KnownFormats, s.Options) result.mergeForSlice(val, i, validator.Validate(val.Index(i).Interface())) } } @@ -103,3 +144,7 @@ func (s *schemaSliceValidator) Validate(data interface{}) *Result { result.Inc() return result } + +func (s *schemaSliceValidator) redeem() { + pools.poolOfSliceValidators.RedeemValidator(s) +} diff --git a/vendor/github.com/go-openapi/validate/spec.go b/vendor/github.com/go-openapi/validate/spec.go index 71a7bac8c8ac..965452566e1e 100644 --- a/vendor/github.com/go-openapi/validate/spec.go +++ b/vendor/github.com/go-openapi/validate/spec.go @@ -15,6 +15,8 @@ package validate import ( + "bytes" + "encoding/gob" "encoding/json" "fmt" "sort" @@ -26,6 +28,7 @@ import ( "github.com/go-openapi/loads" "github.com/go-openapi/spec" "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" ) // Spec validates an OpenAPI 2.0 specification document. @@ -52,25 +55,38 @@ func Spec(doc *loads.Document, formats strfmt.Registry) error { // SpecValidator validates a swagger 2.0 spec type SpecValidator struct { - schema *spec.Schema // swagger 2.0 schema - spec *loads.Document - analyzer *analysis.Spec - expanded *loads.Document - KnownFormats strfmt.Registry - Options Opts // validation options + schema *spec.Schema // swagger 2.0 schema + spec *loads.Document + analyzer *analysis.Spec + expanded *loads.Document + KnownFormats strfmt.Registry + Options Opts // validation options + schemaOptions *SchemaValidatorOptions } // NewSpecValidator creates a new swagger spec validator instance func NewSpecValidator(schema *spec.Schema, formats strfmt.Registry) *SpecValidator { + // schema options that apply to all called validators + schemaOptions := new(SchemaValidatorOptions) + for _, o := range []Option{ + SwaggerSchema(true), + WithRecycleValidators(true), + // withRecycleResults(true), + } { + o(schemaOptions) + } + return &SpecValidator{ - schema: schema, - KnownFormats: formats, - Options: defaultOpts, + schema: schema, + KnownFormats: formats, + Options: defaultOpts, + schemaOptions: schemaOptions, } } // Validate validates the swagger spec func (s *SpecValidator) Validate(data interface{}) (*Result, *Result) { + s.schemaOptions.skipSchemataResult = s.Options.SkipSchemataResult var sd *loads.Document errs, warnings := new(Result), new(Result) @@ -84,11 +100,8 @@ func (s *SpecValidator) Validate(data interface{}) (*Result, *Result) { s.spec = sd s.analyzer = analysis.New(sd.Spec()) - // Swagger schema validator - schv := NewSchemaValidator(s.schema, nil, "", s.KnownFormats, SwaggerSchema(true)) - var obj interface{} - // Raw spec unmarshalling errors + var obj interface{} if err := json.Unmarshal(sd.Raw(), &obj); err != nil { // NOTE: under normal conditions, the *load.Document has been already unmarshalled // So this one is just a paranoid check on the behavior of the spec package @@ -102,6 +115,8 @@ func (s *SpecValidator) Validate(data interface{}) (*Result, *Result) { warnings.AddErrors(errs.Warnings...) }() + // Swagger schema validator + schv := newSchemaValidator(s.schema, nil, "", s.KnownFormats, s.schemaOptions) errs.Merge(schv.Validate(obj)) // error - // There may be a point in continuing to try and determine more accurate errors if !s.Options.ContinueOnErrors && errs.HasErrors() { @@ -129,13 +144,13 @@ func (s *SpecValidator) Validate(data interface{}) (*Result, *Result) { } // Values provided as default MUST validate their schema - df := &defaultValidator{SpecValidator: s} + df := &defaultValidator{SpecValidator: s, schemaOptions: s.schemaOptions} errs.Merge(df.Validate()) // Values provided as examples MUST validate their schema // Value provided as examples in a response without schema generate a warning // Known limitations: examples in responses for mime type not application/json are ignored (warning) - ex := &exampleValidator{SpecValidator: s} + ex := &exampleValidator{SpecValidator: s, schemaOptions: s.schemaOptions} errs.Merge(ex.Validate()) errs.Merge(s.validateNonEmptyPathParamNames()) @@ -147,22 +162,27 @@ func (s *SpecValidator) Validate(data interface{}) (*Result, *Result) { } func (s *SpecValidator) validateNonEmptyPathParamNames() *Result { - res := new(Result) + res := pools.poolOfResults.BorrowResult() if s.spec.Spec().Paths == nil { // There is no Paths object: error res.AddErrors(noValidPathMsg()) - } else { - if s.spec.Spec().Paths.Paths == nil { - // Paths may be empty: warning - res.AddWarnings(noValidPathMsg()) - } else { - for k := range s.spec.Spec().Paths.Paths { - if strings.Contains(k, "{}") { - res.AddErrors(emptyPathParameterMsg(k)) - } - } + + return res + } + + if s.spec.Spec().Paths.Paths == nil { + // Paths may be empty: warning + res.AddWarnings(noValidPathMsg()) + + return res + } + + for k := range s.spec.Spec().Paths.Paths { + if strings.Contains(k, "{}") { + res.AddErrors(emptyPathParameterMsg(k)) } } + return res } @@ -176,7 +196,7 @@ func (s *SpecValidator) validateDuplicateOperationIDs() *Result { // fallback on possible incomplete picture because of previous errors analyzer = s.analyzer } - res := new(Result) + res := pools.poolOfResults.BorrowResult() known := make(map[string]int) for _, v := range analyzer.OperationIDs() { if v != "" { @@ -198,7 +218,7 @@ type dupProp struct { func (s *SpecValidator) validateDuplicatePropertyNames() *Result { // definition can't declare a property that's already defined by one of its ancestors - res := new(Result) + res := pools.poolOfResults.BorrowResult() for k, sch := range s.spec.Spec().Definitions { if len(sch.AllOf) == 0 { continue @@ -247,7 +267,7 @@ func (s *SpecValidator) validateSchemaPropertyNames(nm string, sch spec.Schema, schn := nm schc := &sch - res := new(Result) + res := pools.poolOfResults.BorrowResult() for schc.Ref.String() != "" { // gather property names @@ -284,7 +304,7 @@ func (s *SpecValidator) validateSchemaPropertyNames(nm string, sch spec.Schema, } func (s *SpecValidator) validateCircularAncestry(nm string, sch spec.Schema, knowns map[string]struct{}) ([]string, *Result) { - res := new(Result) + res := pools.poolOfResults.BorrowResult() if sch.Ref.String() == "" && len(sch.AllOf) == 0 { // Safeguard. We should not be able to actually get there return nil, res @@ -334,7 +354,7 @@ func (s *SpecValidator) validateCircularAncestry(nm string, sch spec.Schema, kno func (s *SpecValidator) validateItems() *Result { // validate parameter, items, schema and response objects for presence of item if type is array - res := new(Result) + res := pools.poolOfResults.BorrowResult() for method, pi := range s.analyzer.Operations() { for path, op := range pi { @@ -393,7 +413,7 @@ func (s *SpecValidator) validateItems() *Result { // Verifies constraints on array type func (s *SpecValidator) validateSchemaItems(schema spec.Schema, prefix, opID string) *Result { - res := new(Result) + res := pools.poolOfResults.BorrowResult() if !schema.Type.Contains(arrayType) { return res } @@ -417,7 +437,7 @@ func (s *SpecValidator) validateSchemaItems(schema spec.Schema, prefix, opID str func (s *SpecValidator) validatePathParamPresence(path string, fromPath, fromOperation []string) *Result { // Each defined operation path parameters must correspond to a named element in the API's path pattern. // (For example, you cannot have a path parameter named id for the following path /pets/{petId} but you must have a path parameter named petId.) - res := new(Result) + res := pools.poolOfResults.BorrowResult() for _, l := range fromPath { var matched bool for _, r := range fromOperation { @@ -473,7 +493,7 @@ func (s *SpecValidator) validateReferencedParameters() *Result { if len(expected) == 0 { return nil } - result := new(Result) + result := pools.poolOfResults.BorrowResult() for k := range expected { result.AddWarnings(unusedParamMsg(k)) } @@ -498,7 +518,7 @@ func (s *SpecValidator) validateReferencedResponses() *Result { if len(expected) == 0 { return nil } - result := new(Result) + result := pools.poolOfResults.BorrowResult() for k := range expected { result.AddWarnings(unusedResponseMsg(k)) } @@ -533,7 +553,7 @@ func (s *SpecValidator) validateReferencedDefinitions() *Result { func (s *SpecValidator) validateRequiredDefinitions() *Result { // Each property listed in the required array must be defined in the properties of the model - res := new(Result) + res := pools.poolOfResults.BorrowResult() DEFINITIONS: for d, schema := range s.spec.Spec().Definitions { @@ -552,7 +572,7 @@ DEFINITIONS: func (s *SpecValidator) validateRequiredProperties(path, in string, v *spec.Schema) *Result { // Takes care of recursive property definitions, which may be nested in additionalProperties schemas - res := new(Result) + res := pools.poolOfResults.BorrowResult() propertyMatch := false patternMatch := false additionalPropertiesMatch := false @@ -618,7 +638,7 @@ func (s *SpecValidator) validateParameters() *Result { // - parameters with pattern property must specify valid patterns // - $ref in parameters must resolve // - path param must be required - res := new(Result) + res := pools.poolOfResults.BorrowResult() rexGarbledPathSegment := mustCompileRegexp(`.*[{}\s]+.*`) for method, pi := range s.expandedAnalyzer().Operations() { methodPaths := make(map[string]map[string]string) @@ -657,7 +677,23 @@ func (s *SpecValidator) validateParameters() *Result { // TODO: should be done after param expansion res.Merge(s.checkUniqueParams(path, method, op)) + // pick the root schema from the swagger specification which describes a parameter + origSchema, ok := s.schema.Definitions["parameter"] + if !ok { + panic("unexpected swagger schema: missing #/definitions/parameter") + } + // clone it once to avoid expanding a global schema (e.g. swagger spec) + paramSchema, err := deepCloneSchema(origSchema) + if err != nil { + panic(fmt.Errorf("can't clone schema: %v", err)) + } + for _, pr := range paramHelp.safeExpandedParamsFor(path, method, op.ID, res, s) { + // An expanded parameter must validate the Parameter schema (an unexpanded $ref always passes high-level schema validation) + schv := newSchemaValidator(¶mSchema, s.schema, fmt.Sprintf("%s.%s.parameters.%s", path, method, pr.Name), s.KnownFormats, s.schemaOptions) + obj := swag.ToDynamicJSON(pr) + res.Merge(schv.Validate(obj)) + // Validate pattern regexp for parameters with a Pattern property if _, err := compileRegexp(pr.Pattern); err != nil { res.AddErrors(invalidPatternInParamMsg(op.ID, pr.Name, pr.Pattern)) @@ -739,7 +775,7 @@ func (s *SpecValidator) validateParameters() *Result { func (s *SpecValidator) validateReferencesValid() *Result { // each reference must point to a valid object - res := new(Result) + res := pools.poolOfResults.BorrowResult() for _, r := range s.analyzer.AllRefs() { if !r.IsValidURI(s.spec.SpecFilePath()) { // Safeguard - spec should always yield a valid URI res.AddErrors(invalidRefMsg(r.String())) @@ -765,7 +801,7 @@ func (s *SpecValidator) checkUniqueParams(path, method string, op *spec.Operatio // However, there are some issues with such a factorization: // - analysis does not seem to fully expand params // - param keys may be altered by x-go-name - res := new(Result) + res := pools.poolOfResults.BorrowResult() pnames := make(map[string]struct{}) if op.Parameters != nil { // Safeguard @@ -800,3 +836,17 @@ func (s *SpecValidator) expandedAnalyzer() *analysis.Spec { } return s.analyzer } + +func deepCloneSchema(src spec.Schema) (spec.Schema, error) { + var b bytes.Buffer + if err := gob.NewEncoder(&b).Encode(src); err != nil { + return spec.Schema{}, err + } + + var dst spec.Schema + if err := gob.NewDecoder(&b).Decode(&dst); err != nil { + return spec.Schema{}, err + } + + return dst, nil +} diff --git a/vendor/github.com/go-openapi/validate/spec_messages.go b/vendor/github.com/go-openapi/validate/spec_messages.go index 5398679bffef..6d1f0f819cb4 100644 --- a/vendor/github.com/go-openapi/validate/spec_messages.go +++ b/vendor/github.com/go-openapi/validate/spec_messages.go @@ -187,6 +187,8 @@ const ( // UnusedResponseWarning ... UnusedResponseWarning = "response %q is not used anywhere" + + InvalidObject = "expected an object in %q.%s" ) // Additional error codes @@ -347,6 +349,9 @@ func invalidParameterDefinitionAsSchemaMsg(path, method, operationID string) err func parameterValidationTypeMismatchMsg(param, path, typ string) errors.Error { return errors.New(errors.CompositeErrorCode, ParamValidationTypeMismatch, param, path, typ) } +func invalidObjectMsg(path, in string) errors.Error { + return errors.New(errors.CompositeErrorCode, InvalidObject, path, in) +} // disabled // diff --git a/vendor/github.com/go-openapi/validate/type.go b/vendor/github.com/go-openapi/validate/type.go index c7abf380b9c8..f87abb3d5607 100644 --- a/vendor/github.com/go-openapi/validate/type.go +++ b/vendor/github.com/go-openapi/validate/type.go @@ -25,11 +25,34 @@ import ( ) type typeValidator struct { + Path string + In string Type spec.StringOrArray Nullable bool Format string - In string - Path string + Options *SchemaValidatorOptions +} + +func newTypeValidator(path, in string, typ spec.StringOrArray, nullable bool, format string, opts *SchemaValidatorOptions) *typeValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var t *typeValidator + if opts.recycleValidators { + t = pools.poolOfTypeValidators.BorrowValidator() + } else { + t = new(typeValidator) + } + + t.Path = path + t.In = in + t.Type = typ + t.Nullable = nullable + t.Format = format + t.Options = opts + + return t } func (t *typeValidator) schemaInfoForType(data interface{}) (string, string) { @@ -125,23 +148,33 @@ func (t *typeValidator) SetPath(path string) { t.Path = path } -func (t *typeValidator) Applies(source interface{}, kind reflect.Kind) bool { +func (t *typeValidator) Applies(source interface{}, _ reflect.Kind) bool { // typeValidator applies to Schema, Parameter and Header objects - stpe := reflect.TypeOf(source) - r := (len(t.Type) > 0 || t.Format != "") && (stpe == specSchemaType || stpe == specParameterType || stpe == specHeaderType) - debugLog("type validator for %q applies %t for %T (kind: %v)\n", t.Path, r, source, kind) - return r + switch source.(type) { + case *spec.Schema: + case *spec.Parameter: + case *spec.Header: + default: + return false + } + + return (len(t.Type) > 0 || t.Format != "") } func (t *typeValidator) Validate(data interface{}) *Result { - result := new(Result) - result.Inc() + if t.Options.recycleValidators { + defer func() { + t.redeem() + }() + } + if data == nil { // nil or zero value for the passed structure require Type: null if len(t.Type) > 0 && !t.Type.Contains(nullType) && !t.Nullable { // TODO: if a property is not required it also passes this - return errorHelp.sErr(errors.InvalidType(t.Path, t.In, strings.Join(t.Type, ","), nullType)) + return errorHelp.sErr(errors.InvalidType(t.Path, t.In, strings.Join(t.Type, ","), nullType), t.Options.recycleResult) } - return result + + return emptyResult } // check if the type matches, should be used in every validator chain as first item @@ -151,8 +184,6 @@ func (t *typeValidator) Validate(data interface{}) *Result { // infer schema type (JSON) and format from passed data type schType, format := t.schemaInfoForType(data) - debugLog("path: %s, schType: %s, format: %s, expType: %s, expFmt: %s, kind: %s", t.Path, schType, format, t.Type, t.Format, val.Kind().String()) - // check numerical types // TODO: check unsigned ints // TODO: check json.Number (see schema.go) @@ -163,15 +194,20 @@ func (t *typeValidator) Validate(data interface{}) *Result { if kind != reflect.String && kind != reflect.Slice && t.Format != "" && !(t.Type.Contains(schType) || format == t.Format || isFloatInt || isIntFloat || isLowerInt || isLowerFloat) { // TODO: test case - return errorHelp.sErr(errors.InvalidType(t.Path, t.In, t.Format, format)) + return errorHelp.sErr(errors.InvalidType(t.Path, t.In, t.Format, format), t.Options.recycleResult) } if !(t.Type.Contains(numberType) || t.Type.Contains(integerType)) && t.Format != "" && (kind == reflect.String || kind == reflect.Slice) { - return result + return emptyResult } if !(t.Type.Contains(schType) || isFloatInt || isIntFloat) { - return errorHelp.sErr(errors.InvalidType(t.Path, t.In, strings.Join(t.Type, ","), schType)) + return errorHelp.sErr(errors.InvalidType(t.Path, t.In, strings.Join(t.Type, ","), schType), t.Options.recycleResult) } - return result + + return emptyResult +} + +func (t *typeValidator) redeem() { + pools.poolOfTypeValidators.RedeemValidator(t) } diff --git a/vendor/github.com/go-openapi/validate/validator.go b/vendor/github.com/go-openapi/validate/validator.go index ab4f718b5b25..c083aecc9da9 100644 --- a/vendor/github.com/go-openapi/validate/validator.go +++ b/vendor/github.com/go-openapi/validate/validator.go @@ -39,20 +39,31 @@ type itemsValidator struct { root interface{} path string in string - validators []valueValidator + validators [6]valueValidator KnownFormats strfmt.Registry + Options *SchemaValidatorOptions } -func newItemsValidator(path, in string, items *spec.Items, root interface{}, formats strfmt.Registry) *itemsValidator { - iv := &itemsValidator{path: path, in: in, items: items, root: root, KnownFormats: formats} - iv.validators = []valueValidator{ - &typeValidator{ - Type: spec.StringOrArray([]string{items.Type}), - Nullable: items.Nullable, - Format: items.Format, - In: in, - Path: path, - }, +func newItemsValidator(path, in string, items *spec.Items, root interface{}, formats strfmt.Registry, opts *SchemaValidatorOptions) *itemsValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var iv *itemsValidator + if opts.recycleValidators { + iv = pools.poolOfItemsValidators.BorrowValidator() + } else { + iv = new(itemsValidator) + } + + iv.path = path + iv.in = in + iv.items = items + iv.root = root + iv.KnownFormats = formats + iv.Options = opts + iv.validators = [6]valueValidator{ + iv.typeValidator(), iv.stringValidator(), iv.formatValidator(), iv.numberValidator(), @@ -63,77 +74,152 @@ func newItemsValidator(path, in string, items *spec.Items, root interface{}, for } func (i *itemsValidator) Validate(index int, data interface{}) *Result { + if i.Options.recycleValidators { + defer func() { + i.redeemChildren() + i.redeem() + }() + } + tpe := reflect.TypeOf(data) kind := tpe.Kind() - mainResult := new(Result) + var result *Result + if i.Options.recycleResult { + result = pools.poolOfResults.BorrowResult() + } else { + result = new(Result) + } + path := fmt.Sprintf("%s.%d", i.path, index) - for _, validator := range i.validators { + for idx, validator := range i.validators { + if !validator.Applies(i.root, kind) { + if i.Options.recycleValidators { + // Validate won't be called, so relinquish this validator + if redeemableChildren, ok := validator.(interface{ redeemChildren() }); ok { + redeemableChildren.redeemChildren() + } + if redeemable, ok := validator.(interface{ redeem() }); ok { + redeemable.redeem() + } + i.validators[idx] = nil // prevents further (unsafe) usage + } + + continue + } + validator.SetPath(path) - if validator.Applies(i.root, kind) { - result := validator.Validate(data) - mainResult.Merge(result) - mainResult.Inc() - if result != nil && result.HasErrors() { - return mainResult + err := validator.Validate(data) + if i.Options.recycleValidators { + i.validators[idx] = nil // prevents further (unsafe) usage + } + if err != nil { + result.Inc() + if err.HasErrors() { + result.Merge(err) + + break } + + result.Merge(err) } } - return mainResult + + return result +} + +func (i *itemsValidator) typeValidator() valueValidator { + return newTypeValidator( + i.path, + i.in, + spec.StringOrArray([]string{i.items.Type}), + i.items.Nullable, + i.items.Format, + i.Options, + ) } func (i *itemsValidator) commonValidator() valueValidator { - return &basicCommonValidator{ - In: i.in, - Default: i.items.Default, - Enum: i.items.Enum, - } + return newBasicCommonValidator( + "", + i.in, + i.items.Default, + i.items.Enum, + i.Options, + ) } func (i *itemsValidator) sliceValidator() valueValidator { - return &basicSliceValidator{ - In: i.in, - Default: i.items.Default, - MaxItems: i.items.MaxItems, - MinItems: i.items.MinItems, - UniqueItems: i.items.UniqueItems, - Source: i.root, - Items: i.items.Items, - KnownFormats: i.KnownFormats, - } + return newBasicSliceValidator( + "", + i.in, + i.items.Default, + i.items.MaxItems, + i.items.MinItems, + i.items.UniqueItems, + i.items.Items, + i.root, + i.KnownFormats, + i.Options, + ) } func (i *itemsValidator) numberValidator() valueValidator { - return &numberValidator{ - In: i.in, - Default: i.items.Default, - MultipleOf: i.items.MultipleOf, - Maximum: i.items.Maximum, - ExclusiveMaximum: i.items.ExclusiveMaximum, - Minimum: i.items.Minimum, - ExclusiveMinimum: i.items.ExclusiveMinimum, - Type: i.items.Type, - Format: i.items.Format, - } + return newNumberValidator( + "", + i.in, + i.items.Default, + i.items.MultipleOf, + i.items.Maximum, + i.items.ExclusiveMaximum, + i.items.Minimum, + i.items.ExclusiveMinimum, + i.items.Type, + i.items.Format, + i.Options, + ) } func (i *itemsValidator) stringValidator() valueValidator { - return &stringValidator{ - In: i.in, - Default: i.items.Default, - MaxLength: i.items.MaxLength, - MinLength: i.items.MinLength, - Pattern: i.items.Pattern, - AllowEmptyValue: false, - } + return newStringValidator( + "", + i.in, + i.items.Default, + false, // Required + false, // AllowEmpty + i.items.MaxLength, + i.items.MinLength, + i.items.Pattern, + i.Options, + ) } func (i *itemsValidator) formatValidator() valueValidator { - return &formatValidator{ - In: i.in, - //Default: i.items.Default, - Format: i.items.Format, - KnownFormats: i.KnownFormats, + return newFormatValidator( + "", + i.in, + i.items.Format, + i.KnownFormats, + i.Options, + ) +} + +func (i *itemsValidator) redeem() { + pools.poolOfItemsValidators.RedeemValidator(i) +} + +func (i *itemsValidator) redeemChildren() { + for idx, validator := range i.validators { + if validator == nil { + continue + } + if redeemableChildren, ok := validator.(interface{ redeemChildren() }); ok { + redeemableChildren.redeemChildren() + } + if redeemable, ok := validator.(interface{ redeem() }); ok { + redeemable.redeem() + } + i.validators[idx] = nil // free up allocated children if not in pool } } @@ -142,6 +228,28 @@ type basicCommonValidator struct { In string Default interface{} Enum []interface{} + Options *SchemaValidatorOptions +} + +func newBasicCommonValidator(path, in string, def interface{}, enum []interface{}, opts *SchemaValidatorOptions) *basicCommonValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var b *basicCommonValidator + if opts.recycleValidators { + b = pools.poolOfBasicCommonValidators.BorrowValidator() + } else { + b = new(basicCommonValidator) + } + + b.Path = path + b.In = in + b.Default = def + b.Enum = enum + b.Options = opts + + return b } func (b *basicCommonValidator) SetPath(path string) { @@ -152,255 +260,469 @@ func (b *basicCommonValidator) Applies(source interface{}, _ reflect.Kind) bool switch source.(type) { case *spec.Parameter, *spec.Schema, *spec.Header: return true + default: + return false } - return false } func (b *basicCommonValidator) Validate(data interface{}) (res *Result) { - if len(b.Enum) > 0 { - for _, enumValue := range b.Enum { - actualType := reflect.TypeOf(enumValue) - if actualType != nil { // Safeguard - expectedValue := reflect.ValueOf(data) - if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { - if reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), enumValue) { - return nil - } - } - } + if b.Options.recycleValidators { + defer func() { + b.redeem() + }() + } + + if len(b.Enum) == 0 { + return nil + } + + for _, enumValue := range b.Enum { + actualType := reflect.TypeOf(enumValue) + if actualType == nil { // Safeguard + continue + } + + expectedValue := reflect.ValueOf(data) + if expectedValue.IsValid() && + expectedValue.Type().ConvertibleTo(actualType) && + reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), enumValue) { + return nil } - return errorHelp.sErr(errors.EnumFail(b.Path, b.In, data, b.Enum)) } - return nil + + return errorHelp.sErr(errors.EnumFail(b.Path, b.In, data, b.Enum), b.Options.recycleResult) +} + +func (b *basicCommonValidator) redeem() { + pools.poolOfBasicCommonValidators.RedeemValidator(b) } // A HeaderValidator has very limited subset of validations to apply type HeaderValidator struct { name string header *spec.Header - validators []valueValidator + validators [6]valueValidator KnownFormats strfmt.Registry + Options *SchemaValidatorOptions } // NewHeaderValidator creates a new header validator object -func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry) *HeaderValidator { - p := &HeaderValidator{name: name, header: header, KnownFormats: formats} - p.validators = []valueValidator{ - &typeValidator{ - Type: spec.StringOrArray([]string{header.Type}), - Nullable: header.Nullable, - Format: header.Format, - In: "header", - Path: name, - }, +func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry, options ...Option) *HeaderValidator { + opts := new(SchemaValidatorOptions) + for _, o := range options { + o(opts) + } + + return newHeaderValidator(name, header, formats, opts) +} + +func newHeaderValidator(name string, header *spec.Header, formats strfmt.Registry, opts *SchemaValidatorOptions) *HeaderValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var p *HeaderValidator + if opts.recycleValidators { + p = pools.poolOfHeaderValidators.BorrowValidator() + } else { + p = new(HeaderValidator) + } + + p.name = name + p.header = header + p.KnownFormats = formats + p.Options = opts + p.validators = [6]valueValidator{ + newTypeValidator( + name, + "header", + spec.StringOrArray([]string{header.Type}), + header.Nullable, + header.Format, + p.Options, + ), p.stringValidator(), p.formatValidator(), p.numberValidator(), p.sliceValidator(), p.commonValidator(), } + return p } // Validate the value of the header against its schema func (p *HeaderValidator) Validate(data interface{}) *Result { - result := new(Result) + if p.Options.recycleValidators { + defer func() { + p.redeemChildren() + p.redeem() + }() + } + + if data == nil { + return nil + } + + var result *Result + if p.Options.recycleResult { + result = pools.poolOfResults.BorrowResult() + } else { + result = new(Result) + } + tpe := reflect.TypeOf(data) kind := tpe.Kind() - for _, validator := range p.validators { - if validator.Applies(p.header, kind) { - if err := validator.Validate(data); err != nil { - result.Merge(err) - if err.HasErrors() { - return result + for idx, validator := range p.validators { + if !validator.Applies(p.header, kind) { + if p.Options.recycleValidators { + // Validate won't be called, so relinquish this validator + if redeemableChildren, ok := validator.(interface{ redeemChildren() }); ok { + redeemableChildren.redeemChildren() + } + if redeemable, ok := validator.(interface{ redeem() }); ok { + redeemable.redeem() } + p.validators[idx] = nil // prevents further (unsafe) usage } + + continue + } + + err := validator.Validate(data) + if p.Options.recycleValidators { + p.validators[idx] = nil // prevents further (unsafe) usage + } + if err != nil { + if err.HasErrors() { + result.Merge(err) + break + } + result.Merge(err) } } - return nil + + return result } func (p *HeaderValidator) commonValidator() valueValidator { - return &basicCommonValidator{ - Path: p.name, - In: "response", - Default: p.header.Default, - Enum: p.header.Enum, - } + return newBasicCommonValidator( + p.name, + "response", + p.header.Default, + p.header.Enum, + p.Options, + ) } func (p *HeaderValidator) sliceValidator() valueValidator { - return &basicSliceValidator{ - Path: p.name, - In: "response", - Default: p.header.Default, - MaxItems: p.header.MaxItems, - MinItems: p.header.MinItems, - UniqueItems: p.header.UniqueItems, - Items: p.header.Items, - Source: p.header, - KnownFormats: p.KnownFormats, - } + return newBasicSliceValidator( + p.name, + "response", + p.header.Default, + p.header.MaxItems, + p.header.MinItems, + p.header.UniqueItems, + p.header.Items, + p.header, + p.KnownFormats, + p.Options, + ) } func (p *HeaderValidator) numberValidator() valueValidator { - return &numberValidator{ - Path: p.name, - In: "response", - Default: p.header.Default, - MultipleOf: p.header.MultipleOf, - Maximum: p.header.Maximum, - ExclusiveMaximum: p.header.ExclusiveMaximum, - Minimum: p.header.Minimum, - ExclusiveMinimum: p.header.ExclusiveMinimum, - Type: p.header.Type, - Format: p.header.Format, - } + return newNumberValidator( + p.name, + "response", + p.header.Default, + p.header.MultipleOf, + p.header.Maximum, + p.header.ExclusiveMaximum, + p.header.Minimum, + p.header.ExclusiveMinimum, + p.header.Type, + p.header.Format, + p.Options, + ) } func (p *HeaderValidator) stringValidator() valueValidator { - return &stringValidator{ - Path: p.name, - In: "response", - Default: p.header.Default, - Required: true, - MaxLength: p.header.MaxLength, - MinLength: p.header.MinLength, - Pattern: p.header.Pattern, - AllowEmptyValue: false, - } + return newStringValidator( + p.name, + "response", + p.header.Default, + true, + false, + p.header.MaxLength, + p.header.MinLength, + p.header.Pattern, + p.Options, + ) } func (p *HeaderValidator) formatValidator() valueValidator { - return &formatValidator{ - Path: p.name, - In: "response", - //Default: p.header.Default, - Format: p.header.Format, - KnownFormats: p.KnownFormats, + return newFormatValidator( + p.name, + "response", + p.header.Format, + p.KnownFormats, + p.Options, + ) +} + +func (p *HeaderValidator) redeem() { + pools.poolOfHeaderValidators.RedeemValidator(p) +} + +func (p *HeaderValidator) redeemChildren() { + for idx, validator := range p.validators { + if validator == nil { + continue + } + if redeemableChildren, ok := validator.(interface{ redeemChildren() }); ok { + redeemableChildren.redeemChildren() + } + if redeemable, ok := validator.(interface{ redeem() }); ok { + redeemable.redeem() + } + p.validators[idx] = nil // free up allocated children if not in pool } } // A ParamValidator has very limited subset of validations to apply type ParamValidator struct { param *spec.Parameter - validators []valueValidator + validators [6]valueValidator KnownFormats strfmt.Registry + Options *SchemaValidatorOptions } // NewParamValidator creates a new param validator object -func NewParamValidator(param *spec.Parameter, formats strfmt.Registry) *ParamValidator { - p := &ParamValidator{param: param, KnownFormats: formats} - p.validators = []valueValidator{ - &typeValidator{ - Type: spec.StringOrArray([]string{param.Type}), - Nullable: param.Nullable, - Format: param.Format, - In: param.In, - Path: param.Name, - }, +func NewParamValidator(param *spec.Parameter, formats strfmt.Registry, options ...Option) *ParamValidator { + opts := new(SchemaValidatorOptions) + for _, o := range options { + o(opts) + } + + return newParamValidator(param, formats, opts) +} + +func newParamValidator(param *spec.Parameter, formats strfmt.Registry, opts *SchemaValidatorOptions) *ParamValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var p *ParamValidator + if opts.recycleValidators { + p = pools.poolOfParamValidators.BorrowValidator() + } else { + p = new(ParamValidator) + } + + p.param = param + p.KnownFormats = formats + p.Options = opts + p.validators = [6]valueValidator{ + newTypeValidator( + param.Name, + param.In, + spec.StringOrArray([]string{param.Type}), + param.Nullable, + param.Format, + p.Options, + ), p.stringValidator(), p.formatValidator(), p.numberValidator(), p.sliceValidator(), p.commonValidator(), } + return p } // Validate the data against the description of the parameter func (p *ParamValidator) Validate(data interface{}) *Result { - result := new(Result) + if data == nil { + return nil + } + + var result *Result + if p.Options.recycleResult { + result = pools.poolOfResults.BorrowResult() + } else { + result = new(Result) + } + tpe := reflect.TypeOf(data) kind := tpe.Kind() + if p.Options.recycleValidators { + defer func() { + p.redeemChildren() + p.redeem() + }() + } + // TODO: validate type - for _, validator := range p.validators { - if validator.Applies(p.param, kind) { - if err := validator.Validate(data); err != nil { - result.Merge(err) - if err.HasErrors() { - return result + for idx, validator := range p.validators { + if !validator.Applies(p.param, kind) { + if p.Options.recycleValidators { + // Validate won't be called, so relinquish this validator + if redeemableChildren, ok := validator.(interface{ redeemChildren() }); ok { + redeemableChildren.redeemChildren() + } + if redeemable, ok := validator.(interface{ redeem() }); ok { + redeemable.redeem() } + p.validators[idx] = nil // prevents further (unsafe) usage } + + continue + } + + err := validator.Validate(data) + if p.Options.recycleValidators { + p.validators[idx] = nil // prevents further (unsafe) usage + } + if err != nil { + if err.HasErrors() { + result.Merge(err) + break + } + result.Merge(err) } } - return nil + + return result } func (p *ParamValidator) commonValidator() valueValidator { - return &basicCommonValidator{ - Path: p.param.Name, - In: p.param.In, - Default: p.param.Default, - Enum: p.param.Enum, - } + return newBasicCommonValidator( + p.param.Name, + p.param.In, + p.param.Default, + p.param.Enum, + p.Options, + ) } func (p *ParamValidator) sliceValidator() valueValidator { - return &basicSliceValidator{ - Path: p.param.Name, - In: p.param.In, - Default: p.param.Default, - MaxItems: p.param.MaxItems, - MinItems: p.param.MinItems, - UniqueItems: p.param.UniqueItems, - Items: p.param.Items, - Source: p.param, - KnownFormats: p.KnownFormats, - } + return newBasicSliceValidator( + p.param.Name, + p.param.In, + p.param.Default, + p.param.MaxItems, + p.param.MinItems, + p.param.UniqueItems, + p.param.Items, + p.param, + p.KnownFormats, + p.Options, + ) } func (p *ParamValidator) numberValidator() valueValidator { - return &numberValidator{ - Path: p.param.Name, - In: p.param.In, - Default: p.param.Default, - MultipleOf: p.param.MultipleOf, - Maximum: p.param.Maximum, - ExclusiveMaximum: p.param.ExclusiveMaximum, - Minimum: p.param.Minimum, - ExclusiveMinimum: p.param.ExclusiveMinimum, - Type: p.param.Type, - Format: p.param.Format, - } + return newNumberValidator( + p.param.Name, + p.param.In, + p.param.Default, + p.param.MultipleOf, + p.param.Maximum, + p.param.ExclusiveMaximum, + p.param.Minimum, + p.param.ExclusiveMinimum, + p.param.Type, + p.param.Format, + p.Options, + ) } func (p *ParamValidator) stringValidator() valueValidator { - return &stringValidator{ - Path: p.param.Name, - In: p.param.In, - Default: p.param.Default, - AllowEmptyValue: p.param.AllowEmptyValue, - Required: p.param.Required, - MaxLength: p.param.MaxLength, - MinLength: p.param.MinLength, - Pattern: p.param.Pattern, - } + return newStringValidator( + p.param.Name, + p.param.In, + p.param.Default, + p.param.Required, + p.param.AllowEmptyValue, + p.param.MaxLength, + p.param.MinLength, + p.param.Pattern, + p.Options, + ) } func (p *ParamValidator) formatValidator() valueValidator { - return &formatValidator{ - Path: p.param.Name, - In: p.param.In, - //Default: p.param.Default, - Format: p.param.Format, - KnownFormats: p.KnownFormats, + return newFormatValidator( + p.param.Name, + p.param.In, + p.param.Format, + p.KnownFormats, + p.Options, + ) +} + +func (p *ParamValidator) redeem() { + pools.poolOfParamValidators.RedeemValidator(p) +} + +func (p *ParamValidator) redeemChildren() { + for idx, validator := range p.validators { + if validator == nil { + continue + } + if redeemableChildren, ok := validator.(interface{ redeemChildren() }); ok { + redeemableChildren.redeemChildren() + } + if redeemable, ok := validator.(interface{ redeem() }); ok { + redeemable.redeem() + } + p.validators[idx] = nil // free up allocated children if not in pool } } type basicSliceValidator struct { - Path string - In string - Default interface{} - MaxItems *int64 - MinItems *int64 - UniqueItems bool - Items *spec.Items - Source interface{} - itemsValidator *itemsValidator - KnownFormats strfmt.Registry + Path string + In string + Default interface{} + MaxItems *int64 + MinItems *int64 + UniqueItems bool + Items *spec.Items + Source interface{} + KnownFormats strfmt.Registry + Options *SchemaValidatorOptions +} + +func newBasicSliceValidator( + path, in string, + def interface{}, maxItems, minItems *int64, uniqueItems bool, items *spec.Items, + source interface{}, formats strfmt.Registry, + opts *SchemaValidatorOptions) *basicSliceValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var s *basicSliceValidator + if opts.recycleValidators { + s = pools.poolOfBasicSliceValidators.BorrowValidator() + } else { + s = new(basicSliceValidator) + } + + s.Path = path + s.In = in + s.Default = def + s.MaxItems = maxItems + s.MinItems = minItems + s.UniqueItems = uniqueItems + s.Items = items + s.Source = source + s.KnownFormats = formats + s.Options = opts + + return s } func (s *basicSliceValidator) SetPath(path string) { @@ -411,60 +733,61 @@ func (s *basicSliceValidator) Applies(source interface{}, kind reflect.Kind) boo switch source.(type) { case *spec.Parameter, *spec.Items, *spec.Header: return kind == reflect.Slice + default: + return false } - return false } func (s *basicSliceValidator) Validate(data interface{}) *Result { + if s.Options.recycleValidators { + defer func() { + s.redeem() + }() + } val := reflect.ValueOf(data) size := int64(val.Len()) if s.MinItems != nil { if err := MinItems(s.Path, s.In, size, *s.MinItems); err != nil { - return errorHelp.sErr(err) + return errorHelp.sErr(err, s.Options.recycleResult) } } if s.MaxItems != nil { if err := MaxItems(s.Path, s.In, size, *s.MaxItems); err != nil { - return errorHelp.sErr(err) + return errorHelp.sErr(err, s.Options.recycleResult) } } if s.UniqueItems { if err := UniqueItems(s.Path, s.In, data); err != nil { - return errorHelp.sErr(err) + return errorHelp.sErr(err, s.Options.recycleResult) } } - if s.itemsValidator == nil && s.Items != nil { - s.itemsValidator = newItemsValidator(s.Path, s.In, s.Items, s.Source, s.KnownFormats) + if s.Items == nil { + return nil } - if s.itemsValidator != nil { - for i := 0; i < int(size); i++ { - ele := val.Index(i) - if err := s.itemsValidator.Validate(i, ele.Interface()); err != nil && err.HasErrors() { + for i := 0; i < int(size); i++ { + itemsValidator := newItemsValidator(s.Path, s.In, s.Items, s.Source, s.KnownFormats, s.Options) + ele := val.Index(i) + if err := itemsValidator.Validate(i, ele.Interface()); err != nil { + if err.HasErrors() { return err } + if err.wantsRedeemOnMerge { + pools.poolOfResults.RedeemResult(err) + } } } + return nil } -/* unused -func (s *basicSliceValidator) hasDuplicates(value reflect.Value, size int) bool { - dict := make(map[interface{}]struct{}) - for i := 0; i < size; i++ { - ele := value.Index(i) - if _, ok := dict[ele.Interface()]; ok { - return true - } - dict[ele.Interface()] = struct{}{} - } - return false +func (s *basicSliceValidator) redeem() { + pools.poolOfBasicSliceValidators.RedeemValidator(s) } -*/ type numberValidator struct { Path string @@ -476,8 +799,40 @@ type numberValidator struct { Minimum *float64 ExclusiveMinimum bool // Allows for more accurate behavior regarding integers - Type string - Format string + Type string + Format string + Options *SchemaValidatorOptions +} + +func newNumberValidator( + path, in string, def interface{}, + multipleOf, maximum *float64, exclusiveMaximum bool, minimum *float64, exclusiveMinimum bool, + typ, format string, + opts *SchemaValidatorOptions) *numberValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var n *numberValidator + if opts.recycleValidators { + n = pools.poolOfNumberValidators.BorrowValidator() + } else { + n = new(numberValidator) + } + + n.Path = path + n.In = in + n.Default = def + n.MultipleOf = multipleOf + n.Maximum = maximum + n.ExclusiveMaximum = exclusiveMaximum + n.Minimum = minimum + n.ExclusiveMinimum = exclusiveMinimum + n.Type = typ + n.Format = format + n.Options = opts + + return n } func (n *numberValidator) SetPath(path string) { @@ -489,12 +844,10 @@ func (n *numberValidator) Applies(source interface{}, kind reflect.Kind) bool { case *spec.Parameter, *spec.Schema, *spec.Items, *spec.Header: isInt := kind >= reflect.Int && kind <= reflect.Uint64 isFloat := kind == reflect.Float32 || kind == reflect.Float64 - r := isInt || isFloat - debugLog("schema props validator for %q applies %t for %T (kind: %v) isInt=%t, isFloat=%t\n", n.Path, r, source, kind, isInt, isFloat) - return r + return isInt || isFloat + default: + return false } - debugLog("schema props validator for %q applies %t for %T (kind: %v)\n", n.Path, false, source, kind) - return false } // Validate provides a validator for generic JSON numbers, @@ -519,11 +872,18 @@ func (n *numberValidator) Applies(source interface{}, kind reflect.Kind) bool { // // TODO: default boundaries with MAX_SAFE_INTEGER are not checked (specific to json.Number?) func (n *numberValidator) Validate(val interface{}) *Result { - res := new(Result) + if n.Options.recycleValidators { + defer func() { + n.redeem() + }() + } - resMultiple := new(Result) - resMinimum := new(Result) - resMaximum := new(Result) + var res, resMultiple, resMinimum, resMaximum *Result + if n.Options.recycleResult { + res = pools.poolOfResults.BorrowResult() + } else { + res = new(Result) + } // Used only to attempt to validate constraint on value, // even though value or constraint specified do not match type and format @@ -533,66 +893,106 @@ func (n *numberValidator) Validate(val interface{}) *Result { res.AddErrors(IsValueValidAgainstRange(val, n.Type, n.Format, "Checked", n.Path)) if n.MultipleOf != nil { + resMultiple = pools.poolOfResults.BorrowResult() + // Is the constraint specifier within the range of the specific numeric type and format? resMultiple.AddErrors(IsValueValidAgainstRange(*n.MultipleOf, n.Type, n.Format, "MultipleOf", n.Path)) if resMultiple.IsValid() { // Constraint validated with compatible types if err := MultipleOfNativeType(n.Path, n.In, val, *n.MultipleOf); err != nil { - resMultiple.Merge(errorHelp.sErr(err)) + resMultiple.Merge(errorHelp.sErr(err, n.Options.recycleResult)) } } else { // Constraint nevertheless validated, converted as general number if err := MultipleOf(n.Path, n.In, data, *n.MultipleOf); err != nil { - resMultiple.Merge(errorHelp.sErr(err)) + resMultiple.Merge(errorHelp.sErr(err, n.Options.recycleResult)) } } } if n.Maximum != nil { + resMaximum = pools.poolOfResults.BorrowResult() + // Is the constraint specifier within the range of the specific numeric type and format? resMaximum.AddErrors(IsValueValidAgainstRange(*n.Maximum, n.Type, n.Format, "Maximum boundary", n.Path)) if resMaximum.IsValid() { // Constraint validated with compatible types if err := MaximumNativeType(n.Path, n.In, val, *n.Maximum, n.ExclusiveMaximum); err != nil { - resMaximum.Merge(errorHelp.sErr(err)) + resMaximum.Merge(errorHelp.sErr(err, n.Options.recycleResult)) } } else { // Constraint nevertheless validated, converted as general number if err := Maximum(n.Path, n.In, data, *n.Maximum, n.ExclusiveMaximum); err != nil { - resMaximum.Merge(errorHelp.sErr(err)) + resMaximum.Merge(errorHelp.sErr(err, n.Options.recycleResult)) } } } if n.Minimum != nil { + resMinimum = pools.poolOfResults.BorrowResult() + // Is the constraint specifier within the range of the specific numeric type and format? resMinimum.AddErrors(IsValueValidAgainstRange(*n.Minimum, n.Type, n.Format, "Minimum boundary", n.Path)) if resMinimum.IsValid() { // Constraint validated with compatible types if err := MinimumNativeType(n.Path, n.In, val, *n.Minimum, n.ExclusiveMinimum); err != nil { - resMinimum.Merge(errorHelp.sErr(err)) + resMinimum.Merge(errorHelp.sErr(err, n.Options.recycleResult)) } } else { // Constraint nevertheless validated, converted as general number if err := Minimum(n.Path, n.In, data, *n.Minimum, n.ExclusiveMinimum); err != nil { - resMinimum.Merge(errorHelp.sErr(err)) + resMinimum.Merge(errorHelp.sErr(err, n.Options.recycleResult)) } } } res.Merge(resMultiple, resMinimum, resMaximum) res.Inc() + return res } +func (n *numberValidator) redeem() { + pools.poolOfNumberValidators.RedeemValidator(n) +} + type stringValidator struct { + Path string + In string Default interface{} Required bool AllowEmptyValue bool MaxLength *int64 MinLength *int64 Pattern string - Path string - In string + Options *SchemaValidatorOptions +} + +func newStringValidator( + path, in string, + def interface{}, required, allowEmpty bool, maxLength, minLength *int64, pattern string, + opts *SchemaValidatorOptions) *stringValidator { + if opts == nil { + opts = new(SchemaValidatorOptions) + } + + var s *stringValidator + if opts.recycleValidators { + s = pools.poolOfStringValidators.BorrowValidator() + } else { + s = new(stringValidator) + } + + s.Path = path + s.In = in + s.Default = def + s.Required = required + s.AllowEmptyValue = allowEmpty + s.MaxLength = maxLength + s.MinLength = minLength + s.Pattern = pattern + s.Options = opts + + return s } func (s *stringValidator) SetPath(path string) { @@ -602,42 +1002,50 @@ func (s *stringValidator) SetPath(path string) { func (s *stringValidator) Applies(source interface{}, kind reflect.Kind) bool { switch source.(type) { case *spec.Parameter, *spec.Schema, *spec.Items, *spec.Header: - r := kind == reflect.String - debugLog("string validator for %q applies %t for %T (kind: %v)\n", s.Path, r, source, kind) - return r + return kind == reflect.String + default: + return false } - debugLog("string validator for %q applies %t for %T (kind: %v)\n", s.Path, false, source, kind) - return false } func (s *stringValidator) Validate(val interface{}) *Result { + if s.Options.recycleValidators { + defer func() { + s.redeem() + }() + } + data, ok := val.(string) if !ok { - return errorHelp.sErr(errors.InvalidType(s.Path, s.In, stringType, val)) + return errorHelp.sErr(errors.InvalidType(s.Path, s.In, stringType, val), s.Options.recycleResult) } if s.Required && !s.AllowEmptyValue && (s.Default == nil || s.Default == "") { if err := RequiredString(s.Path, s.In, data); err != nil { - return errorHelp.sErr(err) + return errorHelp.sErr(err, s.Options.recycleResult) } } if s.MaxLength != nil { if err := MaxLength(s.Path, s.In, data, *s.MaxLength); err != nil { - return errorHelp.sErr(err) + return errorHelp.sErr(err, s.Options.recycleResult) } } if s.MinLength != nil { if err := MinLength(s.Path, s.In, data, *s.MinLength); err != nil { - return errorHelp.sErr(err) + return errorHelp.sErr(err, s.Options.recycleResult) } } if s.Pattern != "" { if err := Pattern(s.Path, s.In, data, s.Pattern); err != nil { - return errorHelp.sErr(err) + return errorHelp.sErr(err, s.Options.recycleResult) } } return nil } + +func (s *stringValidator) redeem() { + pools.poolOfStringValidators.RedeemValidator(s) +} diff --git a/vendor/github.com/google/gnostic-models/extensions/extension.proto b/vendor/github.com/google/gnostic-models/extensions/extension.proto index 875137c1a860..a600429890c5 100644 --- a/vendor/github.com/google/gnostic-models/extensions/extension.proto +++ b/vendor/github.com/google/gnostic-models/extensions/extension.proto @@ -42,7 +42,7 @@ option java_package = "org.gnostic.v1"; option objc_class_prefix = "GNX"; // The Go package name. -option go_package = "./extensions;gnostic_extension_v1"; +option go_package = "github.com/google/gnostic-models/extensions;gnostic_extension_v1"; // The version number of Gnostic. message Version { diff --git a/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto index 1c59b2f4ae13..49adafcc8e2b 100644 --- a/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto +++ b/vendor/github.com/google/gnostic-models/openapiv2/OpenAPIv2.proto @@ -42,7 +42,7 @@ option java_package = "org.openapi_v2"; option objc_class_prefix = "OAS"; // The Go package name. -option go_package = "./openapiv2;openapi_v2"; +option go_package = "github.com/google/gnostic-models/openapiv2;openapi_v2"; message AdditionalPropertiesItem { oneof oneof { diff --git a/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.proto b/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.proto index 1be335b89ba0..af4b6254bc97 100644 --- a/vendor/github.com/google/gnostic-models/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 = "./openapiv3;openapi_v3"; +option go_package = "github.com/google/gnostic-models/openapiv3;openapi_v3"; message AdditionalPropertiesItem { oneof oneof { diff --git a/vendor/github.com/google/gnostic-models/openapiv3/annotations.proto b/vendor/github.com/google/gnostic-models/openapiv3/annotations.proto index 09ee0aac51b4..895b4567cd69 100644 --- a/vendor/github.com/google/gnostic-models/openapiv3/annotations.proto +++ b/vendor/github.com/google/gnostic-models/openapiv3/annotations.proto @@ -20,7 +20,7 @@ import "google/protobuf/descriptor.proto"; import "openapiv3/OpenAPIv3.proto"; // The Go package name. -option go_package = "./openapiv3;openapi_v3"; +option go_package = "github.com/google/gnostic-models/openapiv3;openapi_v3"; // 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 diff --git a/vendor/github.com/gophercloud/gophercloud/v2/CHANGELOG.md b/vendor/github.com/gophercloud/gophercloud/v2/CHANGELOG.md index 859a95086752..d53f641b8ad8 100644 --- a/vendor/github.com/gophercloud/gophercloud/v2/CHANGELOG.md +++ b/vendor/github.com/gophercloud/gophercloud/v2/CHANGELOG.md @@ -1,3 +1,110 @@ +## v2.10.0 (2026-01-05) + +* [GH-3569](https://github.com/gophercloud/gophercloud/pull/3569) identity/role: restore backward compatibility for description +* [GH-3570](https://github.com/gophercloud/gophercloud/pull/3570) [v2] identityv3/service: add `name` and `description` fields +* [GH-3577](https://github.com/gophercloud/gophercloud/pull/3577) [v2] add: description field to identity.v3.Endpoint +* [GH-3580](https://github.com/gophercloud/gophercloud/pull/3580) [v2] keystone: add support for per page limit +* [GH-3582](https://github.com/gophercloud/gophercloud/pull/3582) [v2] network.v2.Port: add support for update mac_address +* [GH-3585](https://github.com/gophercloud/gophercloud/pull/3585) [v2] identity.v3.Endpoint: add enabled field on creation and on update +* [GH-3590](https://github.com/gophercloud/gophercloud/pull/3590) [v2] fix (image/v2/images): image v2 unmarshal issue +* [GH-3594](https://github.com/gophercloud/gophercloud/pull/3594) [v2] Add new fields for ListOpts volumetypes +* [GH-3595](https://github.com/gophercloud/gophercloud/pull/3595) [v2] identity.v3.Endpoint: make name as optional on creation + +## v2.9.0 (2025-11-17) + +* [GH-3508](https://github.com/gophercloud/gophercloud/pull/3508) [v2] Trigger "hold" workflow on merge groups +* [GH-3511](https://github.com/gophercloud/gophercloud/pull/3511) [v2] Closes #2321 - Fix TestRolesCRUD by including DomainID to TestRolesCRUD +* [GH-3513](https://github.com/gophercloud/gophercloud/pull/3513) [v2] build(deps): bump actions/labeler from 5 to 6 +* [GH-3516](https://github.com/gophercloud/gophercloud/pull/3516) [v2] refactor: Trivial fixes +* [GH-3524](https://github.com/gophercloud/gophercloud/pull/3524) [v2] [glance]: Add 'uploading' status +* [GH-3525](https://github.com/gophercloud/gophercloud/pull/3525) [v2] compute: Add host aggregate uuid field +* [GH-3526](https://github.com/gophercloud/gophercloud/pull/3526) [v2] Enable deletion for network and loadbalancer quotas +* [GH-3541](https://github.com/gophercloud/gophercloud/pull/3541) [v2] docs: Document tested releases for acceptance tests +* [GH-3544](https://github.com/gophercloud/gophercloud/pull/3544) [v2] Identity V3: Add Options field to roles. +* [GH-3547](https://github.com/gophercloud/gophercloud/pull/3547) [v2] Add config_drive to server struct +* [GH-3548](https://github.com/gophercloud/gophercloud/pull/3548) [v2] Identity: Add description field to roles +* [GH-3549](https://github.com/gophercloud/gophercloud/pull/3549) [v2] compute: add cpu info topology cells entry +* [GH-3550](https://github.com/gophercloud/gophercloud/pull/3550) [v2] Migrate epoxy jobs to Ubuntu 24.04 (Noble), drop caracal jobs +* [GH-3551](https://github.com/gophercloud/gophercloud/pull/3551) [v2] build(deps): bump github/codeql-action from 3 to 4 +* [GH-3557](https://github.com/gophercloud/gophercloud/pull/3557) [v2] Fix EC2 authentication to work with new Keystone auth requirement +* [GH-3558](https://github.com/gophercloud/gophercloud/pull/3558) [v2] identity/services: add omitempty to the `type` field +* [GH-3559](https://github.com/gophercloud/gophercloud/pull/3559) [v2] fix: handle Nova create image response for microversion 2.45 and above + +## v2.8.0 (2025-08-18) + +* [GH-3348](https://github.com/gophercloud/gophercloud/pull/3348) [v2] [networking] add ExtractRoutersInto func helper to routers +* [GH-3354](https://github.com/gophercloud/gophercloud/pull/3354) [v2] Fix a small typo +* [GH-3358](https://github.com/gophercloud/gophercloud/pull/3358) [v2] tests: fix devstack master branch tests +* [GH-3361](https://github.com/gophercloud/gophercloud/pull/3361) [v2] octavia: fix http_version type to float +* [GH-3362](https://github.com/gophercloud/gophercloud/pull/3362) [v2] tests: fix containerinfra template creation +* [GH-3367](https://github.com/gophercloud/gophercloud/pull/3367) [v2] Use Makefile for CI jobs +* [GH-3375](https://github.com/gophercloud/gophercloud/pull/3375) [v2] core: add missing Builder interfaces +* [GH-3378](https://github.com/gophercloud/gophercloud/pull/3378) [v2] tests: fix failing rabbitmq service +* [GH-3379](https://github.com/gophercloud/gophercloud/pull/3379) [v2] CI: Remove Bobcat +* [GH-3384](https://github.com/gophercloud/gophercloud/pull/3384) [v2] Move master CI jobs to Ubuntu 24.04 +* [GH-3386](https://github.com/gophercloud/gophercloud/pull/3386) [v2] tests: Fix TestBGPAgentCRUD +* [GH-3387](https://github.com/gophercloud/gophercloud/pull/3387) [v2] Update the doc of openstack.AuthOptionsFromEnv function +* [GH-3389](https://github.com/gophercloud/gophercloud/pull/3389) [v2] networking: add constants for statuses +* [GH-3391](https://github.com/gophercloud/gophercloud/pull/3391) [v2] CI: Add Epoxy +* [GH-3393](https://github.com/gophercloud/gophercloud/pull/3393) [v2] dns: implement shared zones list +* [GH-3394](https://github.com/gophercloud/gophercloud/pull/3394) [v2] acceptance: Prevent 409 when bulk-creating secgroup rules +* [GH-3396](https://github.com/gophercloud/gophercloud/pull/3396) [v2] identity: add support for string boolean in users' enabled member +* [GH-3397](https://github.com/gophercloud/gophercloud/pull/3397) [v2] Adjust List func to accept a Builder in tenants, routers and security groups packages +* [GH-3399](https://github.com/gophercloud/gophercloud/pull/3399) [v2] blockstorage: add manage-existing and unmanage api call +* [GH-3401](https://github.com/gophercloud/gophercloud/pull/3401) [v2] Added address groups to Networking extensions, with tests. +* [GH-3407](https://github.com/gophercloud/gophercloud/pull/3407) [v2] neutron: add segment_id support to subnets +* [GH-3413](https://github.com/gophercloud/gophercloud/pull/3413) [v2] build(deps): bump joelanford/go-apidiff from 0.8.2 to 0.8.3 +* [GH-3416](https://github.com/gophercloud/gophercloud/pull/3416) [v2] tests: bump devstack-action +* [GH-3422](https://github.com/gophercloud/gophercloud/pull/3422) [v2] Fix documentation for gateway_ip in subnet update +* [GH-3431](https://github.com/gophercloud/gophercloud/pull/3431) [v2] Use container-infra for OpenStack-API-Version +* [GH-3433](https://github.com/gophercloud/gophercloud/pull/3433) [v2] make: Use fixed version of gotestsum +* [GH-3434](https://github.com/gophercloud/gophercloud/pull/3434) [v2] Randomize test order for unit tests +* [GH-3435](https://github.com/gophercloud/gophercloud/pull/3435) [v2] Add versioned endpoint discovery +* [GH-3438](https://github.com/gophercloud/gophercloud/pull/3438) [v2] dns: add support for /v2/quotas +* [GH-3439](https://github.com/gophercloud/gophercloud/pull/3439) [v2] neutron: add segments extension package +* [GH-3446](https://github.com/gophercloud/gophercloud/pull/3446) nova: add support for hostname updates +* [GH-3452](https://github.com/gophercloud/gophercloud/pull/3452) [v2] neutron: allow omission of subnet_id for IP address +* [GH-3454](https://github.com/gophercloud/gophercloud/pull/3454) [v2] blockstorage: add isPublic query option for volume types +* [GH-3458](https://github.com/gophercloud/gophercloud/pull/3458) [v2] Fix pagination for messaging client +* [GH-3465](https://github.com/gophercloud/gophercloud/pull/3465) [v2] tests: Fix TestVLANTransparentCRUD test +* [GH-3466](https://github.com/gophercloud/gophercloud/pull/3466) [v2] tests: fix tests for recent PR backports +* [GH-3469](https://github.com/gophercloud/gophercloud/pull/3469) [v2] tests: shorten GH-A job names +* [GH-3473](https://github.com/gophercloud/gophercloud/pull/3473) [v2] core: clone service type aliases instead of referencing global slice +* [GH-3475](https://github.com/gophercloud/gophercloud/pull/3475) [v2] Implement update & delete traits on resource provider +* [GH-3476](https://github.com/gophercloud/gophercloud/pull/3476) [v2] tests: fix volumetypes unit tests +* [GH-3477](https://github.com/gophercloud/gophercloud/pull/3477) [v2] script: Improve getenvvar helper +* [GH-3481](https://github.com/gophercloud/gophercloud/pull/3481) [v2] Implement hypervisors.GetExt: Get with Query parameter +* [GH-3487](https://github.com/gophercloud/gophercloud/pull/3487) [v2] Add networking taas tapmirror suite +* [GH-3489](https://github.com/gophercloud/gophercloud/pull/3489) [v2] Fix incorrect ICMP field description in PortRangeMax comment +* [GH-3494](https://github.com/gophercloud/gophercloud/pull/3494) [v2] Networking v2: Support two time formats for subnet, router, SG rule (#3492) +* [GH-3495](https://github.com/gophercloud/gophercloud/pull/3495) [v2] build(deps): bump actions/checkout from 4 to 5 + +## v2.7.0 (2025-04-03) + +* [GH-3306](https://github.com/gophercloud/gophercloud/pull/3306) [v2] identity: Add Get endpoint by ID +* [GH-3325](https://github.com/gophercloud/gophercloud/pull/3325) [v2] Switch to a version of gocovmerge compatible with go 1.22 +* [GH-3327](https://github.com/gophercloud/gophercloud/pull/3327) Merge pull request #3209 from shiftstack/proper-service-discovery +* [GH-3328](https://github.com/gophercloud/gophercloud/pull/3328) [v2] Improve support for `network standard-attr-*` extensions +* [GH-3330](https://github.com/gophercloud/gophercloud/pull/3330) [v2] Enhance Snapshot struct and add ListDetail function in V3 blockstorage +* [GH-3333](https://github.com/gophercloud/gophercloud/pull/3333) [v2] vpnaas: add support for more ciphers (auth, encryption, pfs modes) +* [GH-3334](https://github.com/gophercloud/gophercloud/pull/3334) [v2] Added support for VIF's in Baremetal +* [GH-3335](https://github.com/gophercloud/gophercloud/pull/3335) [v2] Baremetal virtual media Get API + +## v2.6.0 (2025-03-03) + +* [GH-3309](https://github.com/gophercloud/gophercloud/pull/3309) Backport: Added support for hypervisor_hostname to v2 + +## v2.5.0 (2025-02-11) + +* [GH-3278](https://github.com/gophercloud/gophercloud/pull/3278) [v2] test: Ensure that randomly created secgroup rules don't conflict +* [GH-3287](https://github.com/gophercloud/gophercloud/pull/3287) [v2] Fix panic in ExtractIntoStructPtr +* [GH-3288](https://github.com/gophercloud/gophercloud/pull/3288) [v2] Fix JSON field name hints in APIVersion structs +* [GH-3292](https://github.com/gophercloud/gophercloud/pull/3292) [v2] Add permissions to the label-issue workflow +* [GH-3294](https://github.com/gophercloud/gophercloud/pull/3294) [v2] Add support for zone sharing in DNS v2 +* [GH-3296](https://github.com/gophercloud/gophercloud/pull/3296) build(deps): bump golang.org/x/crypto from 0.30.0 to 0.31.0 +* [GH-3297](https://github.com/gophercloud/gophercloud/pull/3297) [v2] build(deps): bump golang.org/x/crypto from 0.31.0 to 0.32.0 +* [GH-3298](https://github.com/gophercloud/gophercloud/pull/3298) [v2] build(deps): bump golang.org/x/crypto from 0.32.0 to 0.33.0 + ## v2.4.0 (2024-12-18) * [GH-3270](https://github.com/gophercloud/gophercloud/pull/3270) [v2] SG rules: implement bulk create diff --git a/vendor/github.com/gophercloud/gophercloud/v2/Makefile b/vendor/github.com/gophercloud/gophercloud/v2/Makefile index 2a0618a6b6ea..c63adb8d0319 100644 --- a/vendor/github.com/gophercloud/gophercloud/v2/Makefile +++ b/vendor/github.com/gophercloud/gophercloud/v2/Makefile @@ -1,7 +1,9 @@ undefine GOFLAGS GOLANGCI_LINT_VERSION?=v1.62.2 -GO_TEST?=go run gotest.tools/gotestsum@latest --format testname -- +GOTESTSUM_VERSION?=v1.12.2 +GO_TEST?=go run gotest.tools/gotestsum@$(GOTESTSUM_VERSION) --format testname -- +TIMEOUT := "60m" ifeq ($(shell command -v podman 2> /dev/null),) RUNNER=docker @@ -9,15 +11,18 @@ else RUNNER=podman endif -# if the golangci-lint steps fails with the following error message: +# if the golangci-lint steps fails with one of the following error messages: # # directory prefix . does not contain main module or its selected dependencies # +# failed to initialize build cache at /root/.cache/golangci-lint: mkdir /root/.cache/golangci-lint: permission denied +# # you probably have to fix the SELinux security context for root directory plus your cache # # chcon -Rt svirt_sandbox_file_t . # chcon -Rt svirt_sandbox_file_t ~/.cache/golangci-lint lint: + mkdir -p ~/.cache/golangci-lint/$(GOLANGCI_LINT_VERSION) $(RUNNER) run -t --rm \ -v $(shell pwd):/app \ -v ~/.cache/golangci-lint/$(GOLANGCI_LINT_VERSION):/root/.cache \ @@ -31,84 +36,88 @@ format: .PHONY: format unit: - $(GO_TEST) ./... + $(GO_TEST) -shuffle on ./... .PHONY: unit coverage: - $(GO_TEST) -covermode count -coverprofile cover.out -coverpkg=./... ./... + $(GO_TEST) -shuffle on -covermode count -coverprofile cover.out -coverpkg=./... ./... .PHONY: coverage -acceptance: acceptance-baremetal acceptance-blockstorage acceptance-compute acceptance-container acceptance-containerinfra acceptance-db acceptance-dns acceptance-identity acceptance-imageservice acceptance-keymanager acceptance-loadbalancer acceptance-messaging acceptance-networking acceptance-objectstorage acceptance-orchestration acceptance-placement acceptance-sharedfilesystems acceptance-workflow +acceptance: acceptance-basic acceptance-baremetal acceptance-blockstorage acceptance-compute acceptance-container acceptance-containerinfra acceptance-db acceptance-dns acceptance-identity acceptance-image acceptance-keymanager acceptance-loadbalancer acceptance-messaging acceptance-networking acceptance-objectstorage acceptance-orchestration acceptance-placement acceptance-sharedfilesystems acceptance-workflow .PHONY: acceptance +acceptance-basic: + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack +.PHONY: acceptance-basic + acceptance-baremetal: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/baremetal/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/baremetal/... .PHONY: acceptance-baremetal acceptance-blockstorage: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/blockstorage/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/blockstorage/... .PHONY: acceptance-blockstorage acceptance-compute: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/compute/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/compute/... .PHONY: acceptance-compute acceptance-container: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/container/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/container/... .PHONY: acceptance-container acceptance-containerinfra: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/containerinfra/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/containerinfra/... .PHONY: acceptance-containerinfra acceptance-db: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/db/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/db/... .PHONY: acceptance-db acceptance-dns: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/dns/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/dns/... .PHONY: acceptance-dns acceptance-identity: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/identity/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/identity/... .PHONY: acceptance-identity acceptance-image: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/imageservice/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/image/... .PHONY: acceptance-image acceptance-keymanager: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/keymanager/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/keymanager/... .PHONY: acceptance-keymanager acceptance-loadbalancer: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/loadbalancer/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/loadbalancer/... .PHONY: acceptance-loadbalancer acceptance-messaging: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/messaging/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/messaging/... .PHONY: acceptance-messaging acceptance-networking: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/networking/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/networking/... .PHONY: acceptance-networking acceptance-objectstorage: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/objectstorage/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/objectstorage/... .PHONY: acceptance-objectstorage acceptance-orchestration: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/orchestration/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/orchestration/... .PHONY: acceptance-orchestration acceptance-placement: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/placement/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/placement/... .PHONY: acceptance-placement acceptance-sharedfilesystems: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/sharedfilesystems/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/sharedfilesystems/... .PHONY: acceptance-sharefilesystems acceptance-workflow: - $(GO_TEST) -tags "fixtures acceptance" ./internal/acceptance/openstack/workflow/... + $(GO_TEST) -timeout $(TIMEOUT) -tags "fixtures acceptance" ./internal/acceptance/openstack/workflow/... .PHONY: acceptance-workflow diff --git a/vendor/github.com/gophercloud/gophercloud/v2/endpoint_search.go b/vendor/github.com/gophercloud/gophercloud/v2/endpoint_search.go index 2fbc3c97f14f..34d76a1b8da4 100644 --- a/vendor/github.com/gophercloud/gophercloud/v2/endpoint_search.go +++ b/vendor/github.com/gophercloud/gophercloud/v2/endpoint_search.go @@ -1,5 +1,7 @@ package gophercloud +import "slices" + // Availability indicates to whom a specific service endpoint is accessible: // the internet at large, internal networks only, or only to administrators. // Different identity services use different terminology for these. Identity v2 @@ -22,6 +24,31 @@ const ( AvailabilityInternal Availability = "internal" ) +// ServiceTypeAliases contains a mapping of service types to any aliases, as +// defined by the OpenStack Service Types Authority. Only service types that +// we support are included. +var ServiceTypeAliases = map[string][]string{ + "application-container": {"container"}, + "baremetal": {"bare-metal"}, + "baremetal-introspection": {}, + "block-storage": {"block-store", "volume", "volumev2", "volumev3"}, + "compute": {}, + "container-infrastructure-management": {"container-infrastructure", "container-infra"}, + "database": {}, + "dns": {}, + "identity": {}, + "image": {}, + "key-manager": {}, + "load-balancer": {}, + "message": {"messaging"}, + "networking": {}, + "object-store": {}, + "orchestration": {}, + "placement": {}, + "shared-file-system": {"sharev2", "share"}, + "workflow": {"workflowv2"}, +} + // EndpointOpts specifies search criteria used by queries against an // OpenStack service catalog. The options must contain enough information to // unambiguously identify one, and only one, endpoint within the catalog. @@ -30,8 +57,9 @@ const ( // package, like "openstack.NewComputeV2()". type EndpointOpts struct { // Type [required] is the service type for the client (e.g., "compute", - // "object-store"). Generally, this will be supplied by the service client - // function, but a user-given value will be honored if provided. + // "object-store"), as defined by the OpenStack Service Types Authority. + // This will generally be supplied by the service client function, but a + // user-given value will be honored if provided. Type string // Name [optional] is the service name for the client (e.g., "nova") as it @@ -39,11 +67,23 @@ type EndpointOpts struct { // different Name, which is why both Type and Name are sometimes needed. Name string + // Aliases [optional] is the set of aliases of the service type (e.g. + // "volumev2"/"volumev3", "volume" and "block-store" for the + // "block-storage" service type), as defined by the OpenStack Service Types + // Authority. As with Type, this will generally be supplied by the service + // client function, but a user-given value will be honored if provided. + Aliases []string + // Region [required] is the geographic region in which the endpoint resides, // generally specifying which datacenter should house your resources. // Required only for services that span multiple regions. Region string + // Version [optional] is the major version of the service required. It it not + // a microversion. Use this to ensure the correct endpoint is selected when + // multiple API versions are available. + Version int + // Availability [optional] is the visibility of the endpoint to be returned. // Valid types include the constants AvailabilityPublic, AvailabilityInternal, // or AvailabilityAdmin from this package. @@ -73,4 +113,26 @@ func (eo *EndpointOpts) ApplyDefaults(t string) { if eo.Availability == "" { eo.Availability = AvailabilityPublic } + if len(eo.Aliases) == 0 { + if aliases, ok := ServiceTypeAliases[eo.Type]; ok { + // happy path: user requested a service type by its official name + eo.Aliases = slices.Clone(aliases) + } else { + // unhappy path: user requested a service type by its alias or an + // invalid/unsupported service type + // TODO(stephenfin): This should probably be an error in v3 + for t, aliases := range ServiceTypeAliases { + if slices.Contains(aliases, eo.Type) { + // we intentionally override the service type, even if it + // was explicitly requested by the user + eo.Type = t + eo.Aliases = slices.Clone(aliases) + } + } + } + } +} + +func (eo *EndpointOpts) Types() []string { + return append([]string{eo.Type}, eo.Aliases...) } diff --git a/vendor/github.com/gophercloud/gophercloud/v2/provider_client.go b/vendor/github.com/gophercloud/gophercloud/v2/provider_client.go index ad3edc92d607..a9bde9457c01 100644 --- a/vendor/github.com/gophercloud/gophercloud/v2/provider_client.go +++ b/vendor/github.com/gophercloud/gophercloud/v2/provider_client.go @@ -7,13 +7,14 @@ import ( "errors" "io" "net/http" + "slices" "strings" "sync" ) // DefaultUserAgent is the default User-Agent string set in the request header. const ( - DefaultUserAgent = "gophercloud/v2.4.0" + DefaultUserAgent = "gophercloud/v2.10.0" DefaultMaxBackoffRetries = 60 ) @@ -437,16 +438,8 @@ func (client *ProviderClient) doRequest(ctx context.Context, method, url string, okc = defaultOkCodes(method) } - // Validate the HTTP response status. - var ok bool - for _, code := range okc { - if resp.StatusCode == code { - ok = true - break - } - } - - if !ok { + // Check the response code against the acceptable codes + if !slices.Contains(okc, resp.StatusCode) { body, _ := io.ReadAll(resp.Body) resp.Body.Close() respErr := ErrUnexpectedResponseCode{ diff --git a/vendor/github.com/gophercloud/gophercloud/v2/results.go b/vendor/github.com/gophercloud/gophercloud/v2/results.go index 9e6f630abb42..b12c15a02661 100644 --- a/vendor/github.com/gophercloud/gophercloud/v2/results.go +++ b/vendor/github.com/gophercloud/gophercloud/v2/results.go @@ -184,10 +184,19 @@ func (r Result) ExtractIntoStructPtr(to any, label string) error { return r.Err } + if to == nil { + return fmt.Errorf("Expected pointer, got %T", to) + } + t := reflect.TypeOf(to) if k := t.Kind(); k != reflect.Ptr { return fmt.Errorf("Expected pointer, got %v", k) } + + if reflect.ValueOf(to).IsNil() { + return fmt.Errorf("Expected pointer, got %T", to) + } + switch t.Elem().Kind() { case reflect.Struct: return r.extractIntoPtr(to, label) @@ -210,10 +219,19 @@ func (r Result) ExtractIntoSlicePtr(to any, label string) error { return r.Err } + if to == nil { + return fmt.Errorf("Expected pointer, got %T", to) + } + t := reflect.TypeOf(to) if k := t.Kind(); k != reflect.Ptr { return fmt.Errorf("Expected pointer, got %v", k) } + + if reflect.ValueOf(to).IsNil() { + return fmt.Errorf("Expected pointer, got %T", to) + } + switch t.Elem().Kind() { case reflect.Slice: return r.extractIntoPtr(to, label) diff --git a/vendor/github.com/gophercloud/gophercloud/v2/service_client.go b/vendor/github.com/gophercloud/gophercloud/v2/service_client.go index 11b80108c3a2..015c3f233942 100644 --- a/vendor/github.com/gophercloud/gophercloud/v2/service_client.go +++ b/vendor/github.com/gophercloud/gophercloud/v2/service_client.go @@ -115,21 +115,28 @@ func (client *ServiceClient) Head(ctx context.Context, url string, opts *Request } func (client *ServiceClient) setMicroversionHeader(opts *RequestOpts) { + serviceType := client.Type + switch client.Type { case "compute": opts.MoreHeaders["X-OpenStack-Nova-API-Version"] = client.Microversion - case "sharev2": + case "shared-file-system", "sharev2", "share": opts.MoreHeaders["X-OpenStack-Manila-API-Version"] = client.Microversion - case "volume": + case "block-storage", "block-store", "volume", "volumev3": opts.MoreHeaders["X-OpenStack-Volume-API-Version"] = client.Microversion + // cinder should accept block-storage but (as of Dalmatian) does not + serviceType = "volume" case "baremetal": opts.MoreHeaders["X-OpenStack-Ironic-API-Version"] = client.Microversion case "baremetal-introspection": opts.MoreHeaders["X-OpenStack-Ironic-Inspector-API-Version"] = client.Microversion + case "container-infrastructure-management", "container-infrastructure", "container-infra": + // magnum should accept container-infrastructure-management but (as of Epoxy) does not + serviceType = "container-infra" } if client.Type != "" { - opts.MoreHeaders["OpenStack-API-Version"] = client.Type + " " + client.Microversion + opts.MoreHeaders["OpenStack-API-Version"] = serviceType + " " + client.Microversion } } diff --git a/vendor/github.com/gophercloud/gophercloud/v2/util.go b/vendor/github.com/gophercloud/gophercloud/v2/util.go index ad8a7dfaaa5c..d11a723b1b3f 100644 --- a/vendor/github.com/gophercloud/gophercloud/v2/util.go +++ b/vendor/github.com/gophercloud/gophercloud/v2/util.go @@ -37,9 +37,6 @@ func NormalizePathURL(basePath, rawPath string) (string, error) { absPathSys = filepath.Join(basePath, rawPath) u.Path = filepath.ToSlash(absPathSys) - if err != nil { - return "", err - } u.Scheme = "file" return u.String(), nil } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel index a65d88eb8658..04b4bebf3d55 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel @@ -27,6 +27,7 @@ go_library( "//internal/httprule", "//utilities", "@org_golang_google_genproto_googleapis_api//httpbody", + "@org_golang_google_grpc//:grpc", "@org_golang_google_grpc//codes", "@org_golang_google_grpc//grpclog", "@org_golang_google_grpc//health/grpc_health_v1", diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go index 2f2b342431d6..00b2228a1de5 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go @@ -201,13 +201,13 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM if timeout != 0 { ctx, _ = context.WithTimeout(ctx, timeout) } - if len(pairs) == 0 { - return ctx, nil, nil - } md := metadata.Pairs(pairs...) for _, mda := range mux.metadataAnnotators { md = metadata.Join(md, mda(ctx, req)) } + if len(md) == 0 { + return ctx, nil, nil + } return ctx, md, nil } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go index 8376d1e0efd5..3d07063007d5 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go @@ -66,7 +66,7 @@ func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error { var ( // protoMessageType is stored to prevent constant lookup of the same type at runtime. - protoMessageType = reflect.TypeOf((*proto.Message)(nil)).Elem() + protoMessageType = reflect.TypeFor[proto.Message]() ) // marshalNonProto marshals a non-message field of a protobuf message. @@ -325,9 +325,9 @@ type protoEnum interface { EnumDescriptor() ([]byte, []int) } -var typeProtoEnum = reflect.TypeOf((*protoEnum)(nil)).Elem() +var typeProtoEnum = reflect.TypeFor[protoEnum]() -var typeProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem() +var typeProtoMessage = reflect.TypeFor[proto.Message]() // Delimiter for newline encoded JSON streams. func (j *JSONPb) Delimiter() []byte { diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go index 19255ec441e6..3eb161671732 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule" + "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/health/grpc_health_v1" @@ -281,12 +282,19 @@ func WithHealthEndpointAt(healthCheckClient grpc_health_v1.HealthClient, endpoin http.MethodGet, endpointPath, func(w http.ResponseWriter, r *http.Request, _ map[string]string, ) { _, outboundMarshaler := MarshalerForRequest(s, r) + annotatedContext, err := AnnotateContext(r.Context(), s, r, grpc_health_v1.Health_Check_FullMethodName, WithHTTPPathPattern(endpointPath)) + if err != nil { + s.errorHandler(r.Context(), s, outboundMarshaler, w, r, err) + return + } - resp, err := healthCheckClient.Check(r.Context(), &grpc_health_v1.HealthCheckRequest{ + var md ServerMetadata + resp, err := healthCheckClient.Check(annotatedContext, &grpc_health_v1.HealthCheckRequest{ Service: r.URL.Query().Get("service"), - }) + }, grpc.Header(&md.HeaderMD), grpc.Trailer(&md.TrailerMD)) + annotatedContext = NewServerMetadataContext(annotatedContext, md) if err != nil { - s.errorHandler(r.Context(), s, outboundMarshaler, w, r, err) + s.errorHandler(annotatedContext, s, outboundMarshaler, w, r, err) return } @@ -300,7 +308,7 @@ func WithHealthEndpointAt(healthCheckClient grpc_health_v1.HealthClient, endpoin err = status.Error(codes.NotFound, resp.String()) } - s.errorHandler(r.Context(), s, outboundMarshaler, w, r, err) + s.errorHandler(annotatedContext, s, outboundMarshaler, w, r, err) return } diff --git a/vendor/github.com/josharian/intern/README.md b/vendor/github.com/josharian/intern/README.md deleted file mode 100644 index ffc44b219b2f..000000000000 --- a/vendor/github.com/josharian/intern/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Docs: https://godoc.org/github.com/josharian/intern - -See also [Go issue 5160](https://golang.org/issue/5160). - -License: MIT diff --git a/vendor/github.com/josharian/intern/intern.go b/vendor/github.com/josharian/intern/intern.go deleted file mode 100644 index 7acb1fe90a11..000000000000 --- a/vendor/github.com/josharian/intern/intern.go +++ /dev/null @@ -1,44 +0,0 @@ -// Package intern interns strings. -// Interning is best effort only. -// Interned strings may be removed automatically -// at any time without notification. -// All functions may be called concurrently -// with themselves and each other. -package intern - -import "sync" - -var ( - pool sync.Pool = sync.Pool{ - New: func() interface{} { - return make(map[string]string) - }, - } -) - -// String returns s, interned. -func String(s string) string { - m := pool.Get().(map[string]string) - c, ok := m[s] - if ok { - pool.Put(m) - return c - } - m[s] = s - pool.Put(m) - return s -} - -// Bytes returns b converted to a string, interned. -func Bytes(b []byte) string { - m := pool.Get().(map[string]string) - c, ok := m[string(b)] - if ok { - pool.Put(m) - return c - } - s := string(b) - m[s] = s - pool.Put(m) - return s -} diff --git a/vendor/github.com/josharian/intern/license.md b/vendor/github.com/josharian/intern/license.md deleted file mode 100644 index 353d3055f0b4..000000000000 --- a/vendor/github.com/josharian/intern/license.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Josh Bleecher Snyder - -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/mailru/easyjson/LICENSE b/vendor/github.com/mailru/easyjson/LICENSE deleted file mode 100644 index fbff658f70d9..000000000000 --- a/vendor/github.com/mailru/easyjson/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2016 Mail.Ru Group - -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/mailru/easyjson/buffer/pool.go b/vendor/github.com/mailru/easyjson/buffer/pool.go deleted file mode 100644 index 598a54af9dbf..000000000000 --- a/vendor/github.com/mailru/easyjson/buffer/pool.go +++ /dev/null @@ -1,278 +0,0 @@ -// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to -// reduce copying and to allow reuse of individual chunks. -package buffer - -import ( - "io" - "net" - "sync" -) - -// PoolConfig contains configuration for the allocation and reuse strategy. -type PoolConfig struct { - StartSize int // Minimum chunk size that is allocated. - PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. - MaxSize int // Maximum chunk size that will be allocated. -} - -var config = PoolConfig{ - StartSize: 128, - PooledSize: 512, - MaxSize: 32768, -} - -// Reuse pool: chunk size -> pool. -var buffers = map[int]*sync.Pool{} - -func initBuffers() { - for l := config.PooledSize; l <= config.MaxSize; l *= 2 { - buffers[l] = new(sync.Pool) - } -} - -func init() { - initBuffers() -} - -// Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. -func Init(cfg PoolConfig) { - config = cfg - initBuffers() -} - -// putBuf puts a chunk to reuse pool if it can be reused. -func putBuf(buf []byte) { - size := cap(buf) - if size < config.PooledSize { - return - } - if c := buffers[size]; c != nil { - c.Put(buf[:0]) - } -} - -// getBuf gets a chunk from reuse pool or creates a new one if reuse failed. -func getBuf(size int) []byte { - if size >= config.PooledSize { - if c := buffers[size]; c != nil { - v := c.Get() - if v != nil { - return v.([]byte) - } - } - } - return make([]byte, 0, size) -} - -// Buffer is a buffer optimized for serialization without extra copying. -type Buffer struct { - - // Buf is the current chunk that can be used for serialization. - Buf []byte - - toPool []byte - bufs [][]byte -} - -// EnsureSpace makes sure that the current chunk contains at least s free bytes, -// possibly creating a new chunk. -func (b *Buffer) EnsureSpace(s int) { - if cap(b.Buf)-len(b.Buf) < s { - b.ensureSpaceSlow(s) - } -} - -func (b *Buffer) ensureSpaceSlow(s int) { - l := len(b.Buf) - if l > 0 { - if cap(b.toPool) != cap(b.Buf) { - // Chunk was reallocated, toPool can be pooled. - putBuf(b.toPool) - } - if cap(b.bufs) == 0 { - b.bufs = make([][]byte, 0, 8) - } - b.bufs = append(b.bufs, b.Buf) - l = cap(b.toPool) * 2 - } else { - l = config.StartSize - } - - if l > config.MaxSize { - l = config.MaxSize - } - b.Buf = getBuf(l) - b.toPool = b.Buf -} - -// AppendByte appends a single byte to buffer. -func (b *Buffer) AppendByte(data byte) { - b.EnsureSpace(1) - b.Buf = append(b.Buf, data) -} - -// AppendBytes appends a byte slice to buffer. -func (b *Buffer) AppendBytes(data []byte) { - if len(data) <= cap(b.Buf)-len(b.Buf) { - b.Buf = append(b.Buf, data...) // fast path - } else { - b.appendBytesSlow(data) - } -} - -func (b *Buffer) appendBytesSlow(data []byte) { - for len(data) > 0 { - b.EnsureSpace(1) - - sz := cap(b.Buf) - len(b.Buf) - if sz > len(data) { - sz = len(data) - } - - b.Buf = append(b.Buf, data[:sz]...) - data = data[sz:] - } -} - -// AppendString appends a string to buffer. -func (b *Buffer) AppendString(data string) { - if len(data) <= cap(b.Buf)-len(b.Buf) { - b.Buf = append(b.Buf, data...) // fast path - } else { - b.appendStringSlow(data) - } -} - -func (b *Buffer) appendStringSlow(data string) { - for len(data) > 0 { - b.EnsureSpace(1) - - sz := cap(b.Buf) - len(b.Buf) - if sz > len(data) { - sz = len(data) - } - - b.Buf = append(b.Buf, data[:sz]...) - data = data[sz:] - } -} - -// Size computes the size of a buffer by adding sizes of every chunk. -func (b *Buffer) Size() int { - size := len(b.Buf) - for _, buf := range b.bufs { - size += len(buf) - } - return size -} - -// DumpTo outputs the contents of a buffer to a writer and resets the buffer. -func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { - bufs := net.Buffers(b.bufs) - if len(b.Buf) > 0 { - bufs = append(bufs, b.Buf) - } - n, err := bufs.WriteTo(w) - - for _, buf := range b.bufs { - putBuf(buf) - } - putBuf(b.toPool) - - b.bufs = nil - b.Buf = nil - b.toPool = nil - - return int(n), err -} - -// BuildBytes creates a single byte slice with all the contents of the buffer. Data is -// copied if it does not fit in a single chunk. You can optionally provide one byte -// slice as argument that it will try to reuse. -func (b *Buffer) BuildBytes(reuse ...[]byte) []byte { - if len(b.bufs) == 0 { - ret := b.Buf - b.toPool = nil - b.Buf = nil - return ret - } - - var ret []byte - size := b.Size() - - // If we got a buffer as argument and it is big enough, reuse it. - if len(reuse) == 1 && cap(reuse[0]) >= size { - ret = reuse[0][:0] - } else { - ret = make([]byte, 0, size) - } - for _, buf := range b.bufs { - ret = append(ret, buf...) - putBuf(buf) - } - - ret = append(ret, b.Buf...) - putBuf(b.toPool) - - b.bufs = nil - b.toPool = nil - b.Buf = nil - - return ret -} - -type readCloser struct { - offset int - bufs [][]byte -} - -func (r *readCloser) Read(p []byte) (n int, err error) { - for _, buf := range r.bufs { - // Copy as much as we can. - x := copy(p[n:], buf[r.offset:]) - n += x // Increment how much we filled. - - // Did we empty the whole buffer? - if r.offset+x == len(buf) { - // On to the next buffer. - r.offset = 0 - r.bufs = r.bufs[1:] - - // We can release this buffer. - putBuf(buf) - } else { - r.offset += x - } - - if n == len(p) { - break - } - } - // No buffers left or nothing read? - if len(r.bufs) == 0 { - err = io.EOF - } - return -} - -func (r *readCloser) Close() error { - // Release all remaining buffers. - for _, buf := range r.bufs { - putBuf(buf) - } - // In case Close gets called multiple times. - r.bufs = nil - - return nil -} - -// ReadCloser creates an io.ReadCloser with all the contents of the buffer. -func (b *Buffer) ReadCloser() io.ReadCloser { - ret := &readCloser{0, append(b.bufs, b.Buf)} - - b.bufs = nil - b.toPool = nil - b.Buf = nil - - return ret -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go deleted file mode 100644 index e68108f86876..000000000000 --- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go +++ /dev/null @@ -1,21 +0,0 @@ -// This file will only be included to the build if neither -// easyjson_nounsafe nor appengine build tag is set. See README notes -// for more details. - -//+build !easyjson_nounsafe -//+build !appengine - -package jlexer - -import ( - "unsafe" -) - -// bytesToStr creates a string pointing at the slice to avoid copying. -// -// Warning: the string returned by the function should be used with care, as the whole input data -// chunk may be either blocked from being freed by GC because of a single string or the buffer.Data -// may be garbage-collected even when the string exists. -func bytesToStr(data []byte) string { - return *(*string)(unsafe.Pointer(&data)) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go deleted file mode 100644 index 864d1be67638..000000000000 --- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go +++ /dev/null @@ -1,13 +0,0 @@ -// This file is included to the build if any of the buildtags below -// are defined. Refer to README notes for more details. - -//+build easyjson_nounsafe appengine - -package jlexer - -// bytesToStr creates a string normally from []byte -// -// Note that this method is roughly 1.5x slower than using the 'unsafe' method. -func bytesToStr(data []byte) string { - return string(data) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/error.go b/vendor/github.com/mailru/easyjson/jlexer/error.go deleted file mode 100644 index e90ec40d05f5..000000000000 --- a/vendor/github.com/mailru/easyjson/jlexer/error.go +++ /dev/null @@ -1,15 +0,0 @@ -package jlexer - -import "fmt" - -// LexerError implements the error interface and represents all possible errors that can be -// generated during parsing the JSON data. -type LexerError struct { - Reason string - Offset int - Data string -} - -func (l *LexerError) Error() string { - return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/vendor/github.com/mailru/easyjson/jlexer/lexer.go deleted file mode 100644 index a27705b12b54..000000000000 --- a/vendor/github.com/mailru/easyjson/jlexer/lexer.go +++ /dev/null @@ -1,1257 +0,0 @@ -// Package jlexer contains a JSON lexer implementation. -// -// It is expected that it is mostly used with generated parser code, so the interface is tuned -// for a parser that knows what kind of data is expected. -package jlexer - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "strconv" - "unicode" - "unicode/utf16" - "unicode/utf8" - - "github.com/josharian/intern" -) - -// TokenKind determines type of a token. -type TokenKind byte - -const ( - TokenUndef TokenKind = iota // No token. - TokenDelim // Delimiter: one of '{', '}', '[' or ']'. - TokenString // A string literal, e.g. "abc\u1234" - TokenNumber // Number literal, e.g. 1.5e5 - TokenBool // Boolean literal: true or false. - TokenNull // null keyword. -) - -// token describes a single token: type, position in the input and value. -type token struct { - kind TokenKind // Type of a token. - - boolValue bool // Value if a boolean literal token. - byteValueCloned bool // true if byteValue was allocated and does not refer to original json body - byteValue []byte // Raw value of a token. - delimValue byte -} - -// Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice. -type Lexer struct { - Data []byte // Input data given to the lexer. - - start int // Start of the current token. - pos int // Current unscanned position in the input stream. - token token // Last scanned token, if token.kind != TokenUndef. - - firstElement bool // Whether current element is the first in array or an object. - wantSep byte // A comma or a colon character, which need to occur before a token. - - UseMultipleErrors bool // If we want to use multiple errors. - fatalError error // Fatal error occurred during lexing. It is usually a syntax error. - multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors. -} - -// FetchToken scans the input for the next token. -func (r *Lexer) FetchToken() { - r.token.kind = TokenUndef - r.start = r.pos - - // Check if r.Data has r.pos element - // If it doesn't, it mean corrupted input data - if len(r.Data) < r.pos { - r.errParse("Unexpected end of data") - return - } - // Determine the type of a token by skipping whitespace and reading the - // first character. - for _, c := range r.Data[r.pos:] { - switch c { - case ':', ',': - if r.wantSep == c { - r.pos++ - r.start++ - r.wantSep = 0 - } else { - r.errSyntax() - } - - case ' ', '\t', '\r', '\n': - r.pos++ - r.start++ - - case '"': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = TokenString - r.fetchString() - return - - case '{', '[': - if r.wantSep != 0 { - r.errSyntax() - } - r.firstElement = true - r.token.kind = TokenDelim - r.token.delimValue = r.Data[r.pos] - r.pos++ - return - - case '}', ']': - if !r.firstElement && (r.wantSep != ',') { - r.errSyntax() - } - r.wantSep = 0 - r.token.kind = TokenDelim - r.token.delimValue = r.Data[r.pos] - r.pos++ - return - - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': - if r.wantSep != 0 { - r.errSyntax() - } - r.token.kind = TokenNumber - r.fetchNumber() - return - - case 'n': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = TokenNull - r.fetchNull() - return - - case 't': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = TokenBool - r.token.boolValue = true - r.fetchTrue() - return - - case 'f': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = TokenBool - r.token.boolValue = false - r.fetchFalse() - return - - default: - r.errSyntax() - return - } - } - r.fatalError = io.EOF - return -} - -// isTokenEnd returns true if the char can follow a non-delimiter token -func isTokenEnd(c byte) bool { - return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' -} - -// fetchNull fetches and checks remaining bytes of null keyword. -func (r *Lexer) fetchNull() { - r.pos += 4 - if r.pos > len(r.Data) || - r.Data[r.pos-3] != 'u' || - r.Data[r.pos-2] != 'l' || - r.Data[r.pos-1] != 'l' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 4 - r.errSyntax() - } -} - -// fetchTrue fetches and checks remaining bytes of true keyword. -func (r *Lexer) fetchTrue() { - r.pos += 4 - if r.pos > len(r.Data) || - r.Data[r.pos-3] != 'r' || - r.Data[r.pos-2] != 'u' || - r.Data[r.pos-1] != 'e' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 4 - r.errSyntax() - } -} - -// fetchFalse fetches and checks remaining bytes of false keyword. -func (r *Lexer) fetchFalse() { - r.pos += 5 - if r.pos > len(r.Data) || - r.Data[r.pos-4] != 'a' || - r.Data[r.pos-3] != 'l' || - r.Data[r.pos-2] != 's' || - r.Data[r.pos-1] != 'e' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 5 - r.errSyntax() - } -} - -// fetchNumber scans a number literal token. -func (r *Lexer) fetchNumber() { - hasE := false - afterE := false - hasDot := false - - r.pos++ - for i, c := range r.Data[r.pos:] { - switch { - case c >= '0' && c <= '9': - afterE = false - case c == '.' && !hasDot: - hasDot = true - case (c == 'e' || c == 'E') && !hasE: - hasE = true - hasDot = true - afterE = true - case (c == '+' || c == '-') && afterE: - afterE = false - default: - r.pos += i - if !isTokenEnd(c) { - r.errSyntax() - } else { - r.token.byteValue = r.Data[r.start:r.pos] - } - return - } - } - - r.pos = len(r.Data) - r.token.byteValue = r.Data[r.start:] -} - -// findStringLen tries to scan into the string literal for ending quote char to determine required size. -// The size will be exact if no escapes are present and may be inexact if there are escaped chars. -func findStringLen(data []byte) (isValid bool, length int) { - for { - idx := bytes.IndexByte(data, '"') - if idx == -1 { - return false, len(data) - } - if idx == 0 || (idx > 0 && data[idx-1] != '\\') { - return true, length + idx - } - - // count \\\\\\\ sequences. even number of slashes means quote is not really escaped - cnt := 1 - for idx-cnt-1 >= 0 && data[idx-cnt-1] == '\\' { - cnt++ - } - if cnt%2 == 0 { - return true, length + idx - } - - length += idx + 1 - data = data[idx+1:] - } -} - -// unescapeStringToken performs unescaping of string token. -// if no escaping is needed, original string is returned, otherwise - a new one allocated -func (r *Lexer) unescapeStringToken() (err error) { - data := r.token.byteValue - var unescapedData []byte - - for { - i := bytes.IndexByte(data, '\\') - if i == -1 { - break - } - - escapedRune, escapedBytes, err := decodeEscape(data[i:]) - if err != nil { - r.errParse(err.Error()) - return err - } - - if unescapedData == nil { - unescapedData = make([]byte, 0, len(r.token.byteValue)) - } - - var d [4]byte - s := utf8.EncodeRune(d[:], escapedRune) - unescapedData = append(unescapedData, data[:i]...) - unescapedData = append(unescapedData, d[:s]...) - - data = data[i+escapedBytes:] - } - - if unescapedData != nil { - r.token.byteValue = append(unescapedData, data...) - r.token.byteValueCloned = true - } - return -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - var val rune - for i := 2; i < len(s) && i < 6; i++ { - var v byte - c := s[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - v = c - '0' - case 'a', 'b', 'c', 'd', 'e', 'f': - v = c - 'a' + 10 - case 'A', 'B', 'C', 'D', 'E', 'F': - v = c - 'A' + 10 - default: - return -1 - } - - val <<= 4 - val |= rune(v) - } - return val -} - -// decodeEscape processes a single escape sequence and returns number of bytes processed. -func decodeEscape(data []byte) (decoded rune, bytesProcessed int, err error) { - if len(data) < 2 { - return 0, 0, errors.New("incorrect escape symbol \\ at the end of token") - } - - c := data[1] - switch c { - case '"', '/', '\\': - return rune(c), 2, nil - case 'b': - return '\b', 2, nil - case 'f': - return '\f', 2, nil - case 'n': - return '\n', 2, nil - case 'r': - return '\r', 2, nil - case 't': - return '\t', 2, nil - case 'u': - rr := getu4(data) - if rr < 0 { - return 0, 0, errors.New("incorrectly escaped \\uXXXX sequence") - } - - read := 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(data[read:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - read += 6 - rr = dec - } else { - rr = unicode.ReplacementChar - } - } - return rr, read, nil - } - - return 0, 0, errors.New("incorrectly escaped bytes") -} - -// fetchString scans a string literal token. -func (r *Lexer) fetchString() { - r.pos++ - data := r.Data[r.pos:] - - isValid, length := findStringLen(data) - if !isValid { - r.pos += length - r.errParse("unterminated string literal") - return - } - r.token.byteValue = data[:length] - r.pos += length + 1 // skip closing '"' as well -} - -// scanToken scans the next token if no token is currently available in the lexer. -func (r *Lexer) scanToken() { - if r.token.kind != TokenUndef || r.fatalError != nil { - return - } - - r.FetchToken() -} - -// consume resets the current token to allow scanning the next one. -func (r *Lexer) consume() { - r.token.kind = TokenUndef - r.token.byteValueCloned = false - r.token.delimValue = 0 -} - -// Ok returns true if no error (including io.EOF) was encountered during scanning. -func (r *Lexer) Ok() bool { - return r.fatalError == nil -} - -const maxErrorContextLen = 13 - -func (r *Lexer) errParse(what string) { - if r.fatalError == nil { - var str string - if len(r.Data)-r.pos <= maxErrorContextLen { - str = string(r.Data) - } else { - str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..." - } - r.fatalError = &LexerError{ - Reason: what, - Offset: r.pos, - Data: str, - } - } -} - -func (r *Lexer) errSyntax() { - r.errParse("syntax error") -} - -func (r *Lexer) errInvalidToken(expected string) { - if r.fatalError != nil { - return - } - if r.UseMultipleErrors { - r.pos = r.start - r.consume() - r.SkipRecursive() - switch expected { - case "[": - r.token.delimValue = ']' - r.token.kind = TokenDelim - case "{": - r.token.delimValue = '}' - r.token.kind = TokenDelim - } - r.addNonfatalError(&LexerError{ - Reason: fmt.Sprintf("expected %s", expected), - Offset: r.start, - Data: string(r.Data[r.start:r.pos]), - }) - return - } - - var str string - if len(r.token.byteValue) <= maxErrorContextLen { - str = string(r.token.byteValue) - } else { - str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..." - } - r.fatalError = &LexerError{ - Reason: fmt.Sprintf("expected %s", expected), - Offset: r.pos, - Data: str, - } -} - -func (r *Lexer) GetPos() int { - return r.pos -} - -// Delim consumes a token and verifies that it is the given delimiter. -func (r *Lexer) Delim(c byte) { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() || r.token.delimValue != c { - r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled. - r.errInvalidToken(string([]byte{c})) - } else { - r.consume() - } -} - -// IsDelim returns true if there was no scanning error and next token is the given delimiter. -func (r *Lexer) IsDelim(c byte) bool { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - return !r.Ok() || r.token.delimValue == c -} - -// Null verifies that the next token is null and consumes it. -func (r *Lexer) Null() { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenNull { - r.errInvalidToken("null") - } - r.consume() -} - -// IsNull returns true if the next token is a null keyword. -func (r *Lexer) IsNull() bool { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - return r.Ok() && r.token.kind == TokenNull -} - -// Skip skips a single token. -func (r *Lexer) Skip() { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - r.consume() -} - -// SkipRecursive skips next array or object completely, or just skips a single token if not -// an array/object. -// -// Note: no syntax validation is performed on the skipped data. -func (r *Lexer) SkipRecursive() { - r.scanToken() - var start, end byte - startPos := r.start - - switch r.token.delimValue { - case '{': - start, end = '{', '}' - case '[': - start, end = '[', ']' - default: - r.consume() - return - } - - r.consume() - - level := 1 - inQuotes := false - wasEscape := false - - for i, c := range r.Data[r.pos:] { - switch { - case c == start && !inQuotes: - level++ - case c == end && !inQuotes: - level-- - if level == 0 { - r.pos += i + 1 - if !json.Valid(r.Data[startPos:r.pos]) { - r.pos = len(r.Data) - r.fatalError = &LexerError{ - Reason: "skipped array/object json value is invalid", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - } - } - return - } - case c == '\\' && inQuotes: - wasEscape = !wasEscape - continue - case c == '"' && inQuotes: - inQuotes = wasEscape - case c == '"': - inQuotes = true - } - wasEscape = false - } - r.pos = len(r.Data) - r.fatalError = &LexerError{ - Reason: "EOF reached while skipping array/object or token", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - } -} - -// Raw fetches the next item recursively as a data slice -func (r *Lexer) Raw() []byte { - r.SkipRecursive() - if !r.Ok() { - return nil - } - return r.Data[r.start:r.pos] -} - -// IsStart returns whether the lexer is positioned at the start -// of an input string. -func (r *Lexer) IsStart() bool { - return r.pos == 0 -} - -// Consumed reads all remaining bytes from the input, publishing an error if -// there is anything but whitespace remaining. -func (r *Lexer) Consumed() { - if r.pos > len(r.Data) || !r.Ok() { - return - } - - for _, c := range r.Data[r.pos:] { - if c != ' ' && c != '\t' && c != '\r' && c != '\n' { - r.AddError(&LexerError{ - Reason: "invalid character '" + string(c) + "' after top-level value", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - }) - return - } - - r.pos++ - r.start++ - } -} - -func (r *Lexer) unsafeString(skipUnescape bool) (string, []byte) { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenString { - r.errInvalidToken("string") - return "", nil - } - if !skipUnescape { - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "", nil - } - } - - bytes := r.token.byteValue - ret := bytesToStr(r.token.byteValue) - r.consume() - return ret, bytes -} - -// UnsafeString returns the string value if the token is a string literal. -// -// Warning: returned string may point to the input buffer, so the string should not outlive -// the input buffer. Intended pattern of usage is as an argument to a switch statement. -func (r *Lexer) UnsafeString() string { - ret, _ := r.unsafeString(false) - return ret -} - -// UnsafeBytes returns the byte slice if the token is a string literal. -func (r *Lexer) UnsafeBytes() []byte { - _, ret := r.unsafeString(false) - return ret -} - -// UnsafeFieldName returns current member name string token -func (r *Lexer) UnsafeFieldName(skipUnescape bool) string { - ret, _ := r.unsafeString(skipUnescape) - return ret -} - -// String reads a string literal. -func (r *Lexer) String() string { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenString { - r.errInvalidToken("string") - return "" - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "" - } - var ret string - if r.token.byteValueCloned { - ret = bytesToStr(r.token.byteValue) - } else { - ret = string(r.token.byteValue) - } - r.consume() - return ret -} - -// StringIntern reads a string literal, and performs string interning on it. -func (r *Lexer) StringIntern() string { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenString { - r.errInvalidToken("string") - return "" - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return "" - } - ret := intern.Bytes(r.token.byteValue) - r.consume() - return ret -} - -// Bytes reads a string literal and base64 decodes it into a byte slice. -func (r *Lexer) Bytes() []byte { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenString { - r.errInvalidToken("string") - return nil - } - if err := r.unescapeStringToken(); err != nil { - r.errInvalidToken("string") - return nil - } - ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue))) - n, err := base64.StdEncoding.Decode(ret, r.token.byteValue) - if err != nil { - r.fatalError = &LexerError{ - Reason: err.Error(), - } - return nil - } - - r.consume() - return ret[:n] -} - -// Bool reads a true or false boolean keyword. -func (r *Lexer) Bool() bool { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenBool { - r.errInvalidToken("bool") - return false - } - ret := r.token.boolValue - r.consume() - return ret -} - -func (r *Lexer) number() string { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != TokenNumber { - r.errInvalidToken("number") - return "" - } - ret := bytesToStr(r.token.byteValue) - r.consume() - return ret -} - -func (r *Lexer) Uint8() uint8 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint8(n) -} - -func (r *Lexer) Uint16() uint16 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint16(n) -} - -func (r *Lexer) Uint32() uint32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint32(n) -} - -func (r *Lexer) Uint64() uint64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Uint() uint { - return uint(r.Uint64()) -} - -func (r *Lexer) Int8() int8 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int8(n) -} - -func (r *Lexer) Int16() int16 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int16(n) -} - -func (r *Lexer) Int32() int32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int32(n) -} - -func (r *Lexer) Int64() int64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Int() int { - return int(r.Int64()) -} - -func (r *Lexer) Uint8Str() uint8 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint8(n) -} - -func (r *Lexer) Uint16Str() uint16 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint16(n) -} - -func (r *Lexer) Uint32Str() uint32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint32(n) -} - -func (r *Lexer) Uint64Str() uint64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) UintStr() uint { - return uint(r.Uint64Str()) -} - -func (r *Lexer) UintptrStr() uintptr { - return uintptr(r.Uint64Str()) -} - -func (r *Lexer) Int8Str() int8 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int8(n) -} - -func (r *Lexer) Int16Str() int16 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int16(n) -} - -func (r *Lexer) Int32Str() int32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int32(n) -} - -func (r *Lexer) Int64Str() int64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) IntStr() int { - return int(r.Int64Str()) -} - -func (r *Lexer) Float32() float32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseFloat(s, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return float32(n) -} - -func (r *Lexer) Float32Str() float32 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - n, err := strconv.ParseFloat(s, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return float32(n) -} - -func (r *Lexer) Float64() float64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseFloat(s, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Float64Str() float64 { - s, b := r.unsafeString(false) - if !r.Ok() { - return 0 - } - n, err := strconv.ParseFloat(s, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) Error() error { - return r.fatalError -} - -func (r *Lexer) AddError(e error) { - if r.fatalError == nil { - r.fatalError = e - } -} - -func (r *Lexer) AddNonFatalError(e error) { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Data: string(r.Data[r.start:r.pos]), - Reason: e.Error(), - }) -} - -func (r *Lexer) addNonfatalError(err *LexerError) { - if r.UseMultipleErrors { - // We don't want to add errors with the same offset. - if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset { - return - } - r.multipleErrors = append(r.multipleErrors, err) - return - } - r.fatalError = err -} - -func (r *Lexer) GetNonFatalErrors() []*LexerError { - return r.multipleErrors -} - -// JsonNumber fetches and json.Number from 'encoding/json' package. -// Both int, float or string, contains them are valid values -func (r *Lexer) JsonNumber() json.Number { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() { - r.errInvalidToken("json.Number") - return json.Number("") - } - - switch r.token.kind { - case TokenString: - return json.Number(r.String()) - case TokenNumber: - return json.Number(r.Raw()) - case TokenNull: - r.Null() - return json.Number("") - default: - r.errSyntax() - return json.Number("") - } -} - -// Interface fetches an interface{} analogous to the 'encoding/json' package. -func (r *Lexer) Interface() interface{} { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() { - return nil - } - switch r.token.kind { - case TokenString: - return r.String() - case TokenNumber: - return r.Float64() - case TokenBool: - return r.Bool() - case TokenNull: - r.Null() - return nil - } - - if r.token.delimValue == '{' { - r.consume() - - ret := map[string]interface{}{} - for !r.IsDelim('}') { - key := r.String() - r.WantColon() - ret[key] = r.Interface() - r.WantComma() - } - r.Delim('}') - - if r.Ok() { - return ret - } else { - return nil - } - } else if r.token.delimValue == '[' { - r.consume() - - ret := []interface{}{} - for !r.IsDelim(']') { - ret = append(ret, r.Interface()) - r.WantComma() - } - r.Delim(']') - - if r.Ok() { - return ret - } else { - return nil - } - } - r.errSyntax() - return nil -} - -// WantComma requires a comma to be present before fetching next token. -func (r *Lexer) WantComma() { - r.wantSep = ',' - r.firstElement = false -} - -// WantColon requires a colon to be present before fetching next token. -func (r *Lexer) WantColon() { - r.wantSep = ':' - r.firstElement = false -} - -// CurrentToken returns current token kind if there were no errors and TokenUndef otherwise -func (r *Lexer) CurrentToken() TokenKind { - if r.token.kind == TokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() { - return TokenUndef - } - - return r.token.kind -} diff --git a/vendor/github.com/mailru/easyjson/jwriter/writer.go b/vendor/github.com/mailru/easyjson/jwriter/writer.go deleted file mode 100644 index 34b0ade46852..000000000000 --- a/vendor/github.com/mailru/easyjson/jwriter/writer.go +++ /dev/null @@ -1,417 +0,0 @@ -// Package jwriter contains a JSON writer. -package jwriter - -import ( - "io" - "strconv" - "unicode/utf8" - - "github.com/mailru/easyjson/buffer" -) - -// Flags describe various encoding options. The behavior may be actually implemented in the encoder, but -// Flags field in Writer is used to set and pass them around. -type Flags int - -const ( - NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. - NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. -) - -// Writer is a JSON writer. -type Writer struct { - Flags Flags - - Error error - Buffer buffer.Buffer - NoEscapeHTML bool -} - -// Size returns the size of the data that was written out. -func (w *Writer) Size() int { - return w.Buffer.Size() -} - -// DumpTo outputs the data to given io.Writer, resetting the buffer. -func (w *Writer) DumpTo(out io.Writer) (written int, err error) { - return w.Buffer.DumpTo(out) -} - -// BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice -// as argument that it will try to reuse. -func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { - if w.Error != nil { - return nil, w.Error - } - - return w.Buffer.BuildBytes(reuse...), nil -} - -// ReadCloser returns an io.ReadCloser that can be used to read the data. -// ReadCloser also resets the buffer. -func (w *Writer) ReadCloser() (io.ReadCloser, error) { - if w.Error != nil { - return nil, w.Error - } - - return w.Buffer.ReadCloser(), nil -} - -// RawByte appends raw binary data to the buffer. -func (w *Writer) RawByte(c byte) { - w.Buffer.AppendByte(c) -} - -// RawByte appends raw binary data to the buffer. -func (w *Writer) RawString(s string) { - w.Buffer.AppendString(s) -} - -// RawBytesString appends string from bytes to the buffer. -func (w *Writer) RawBytesString(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - default: - w.String(string(data)) - } -} - -// Raw appends raw binary data to the buffer or sets the error if it is given. Useful for -// calling with results of MarshalJSON-like functions. -func (w *Writer) Raw(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - case len(data) > 0: - w.Buffer.AppendBytes(data) - default: - w.RawString("null") - } -} - -// RawText encloses raw binary data in quotes and appends in to the buffer. -// Useful for calling with results of MarshalText-like functions. -func (w *Writer) RawText(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - case len(data) > 0: - w.String(string(data)) - default: - w.RawString("null") - } -} - -// Base64Bytes appends data to the buffer after base64 encoding it -func (w *Writer) Base64Bytes(data []byte) { - if data == nil { - w.Buffer.AppendString("null") - return - } - w.Buffer.AppendByte('"') - w.base64(data) - w.Buffer.AppendByte('"') -} - -func (w *Writer) Uint8(n uint8) { - w.Buffer.EnsureSpace(3) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint16(n uint16) { - w.Buffer.EnsureSpace(5) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint32(n uint32) { - w.Buffer.EnsureSpace(10) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint(n uint) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint64(n uint64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) -} - -func (w *Writer) Int8(n int8) { - w.Buffer.EnsureSpace(4) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int16(n int16) { - w.Buffer.EnsureSpace(6) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int32(n int32) { - w.Buffer.EnsureSpace(11) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int(n int) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int64(n int64) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) -} - -func (w *Writer) Uint8Str(n uint8) { - w.Buffer.EnsureSpace(3) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint16Str(n uint16) { - w.Buffer.EnsureSpace(5) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint32Str(n uint32) { - w.Buffer.EnsureSpace(10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) UintStr(n uint) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint64Str(n uint64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) UintptrStr(n uintptr) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int8Str(n int8) { - w.Buffer.EnsureSpace(4) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int16Str(n int16) { - w.Buffer.EnsureSpace(6) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int32Str(n int32) { - w.Buffer.EnsureSpace(11) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) IntStr(n int) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int64Str(n int64) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Float32(n float32) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) -} - -func (w *Writer) Float32Str(n float32) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Float64(n float64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) -} - -func (w *Writer) Float64Str(n float64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 64) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Bool(v bool) { - w.Buffer.EnsureSpace(5) - if v { - w.Buffer.Buf = append(w.Buffer.Buf, "true"...) - } else { - w.Buffer.Buf = append(w.Buffer.Buf, "false"...) - } -} - -const chars = "0123456789abcdef" - -func getTable(falseValues ...int) [128]bool { - table := [128]bool{} - - for i := 0; i < 128; i++ { - table[i] = true - } - - for _, v := range falseValues { - table[v] = false - } - - return table -} - -var ( - htmlEscapeTable = getTable(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, '"', '&', '<', '>', '\\') - htmlNoEscapeTable = getTable(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, '"', '\\') -) - -func (w *Writer) String(s string) { - w.Buffer.AppendByte('"') - - // Portions of the string that contain no escapes are appended as - // byte slices. - - p := 0 // last non-escape symbol - - escapeTable := &htmlEscapeTable - if w.NoEscapeHTML { - escapeTable = &htmlNoEscapeTable - } - - for i := 0; i < len(s); { - c := s[i] - - if c < utf8.RuneSelf { - if escapeTable[c] { - // single-width character, no escaping is required - i++ - continue - } - - w.Buffer.AppendString(s[p:i]) - switch c { - case '\t': - w.Buffer.AppendString(`\t`) - case '\r': - w.Buffer.AppendString(`\r`) - case '\n': - w.Buffer.AppendString(`\n`) - case '\\': - w.Buffer.AppendString(`\\`) - case '"': - w.Buffer.AppendString(`\"`) - default: - w.Buffer.AppendString(`\u00`) - w.Buffer.AppendByte(chars[c>>4]) - w.Buffer.AppendByte(chars[c&0xf]) - } - - i++ - p = i - continue - } - - // broken utf - runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) - if runeValue == utf8.RuneError && runeWidth == 1 { - w.Buffer.AppendString(s[p:i]) - w.Buffer.AppendString(`\ufffd`) - i++ - p = i - continue - } - - // jsonp stuff - tab separator and line separator - if runeValue == '\u2028' || runeValue == '\u2029' { - w.Buffer.AppendString(s[p:i]) - w.Buffer.AppendString(`\u202`) - w.Buffer.AppendByte(chars[runeValue&0xf]) - i += runeWidth - p = i - continue - } - i += runeWidth - } - w.Buffer.AppendString(s[p:]) - w.Buffer.AppendByte('"') -} - -const encode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -const padChar = '=' - -func (w *Writer) base64(in []byte) { - - if len(in) == 0 { - return - } - - w.Buffer.EnsureSpace(((len(in)-1)/3 + 1) * 4) - - si := 0 - n := (len(in) / 3) * 3 - - for si < n { - // Convert 3x 8bit source bytes into 4 bytes - val := uint(in[si+0])<<16 | uint(in[si+1])<<8 | uint(in[si+2]) - - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F], encode[val>>6&0x3F], encode[val&0x3F]) - - si += 3 - } - - remain := len(in) - si - if remain == 0 { - return - } - - // Add the remaining small block - val := uint(in[si+0]) << 16 - if remain == 2 { - val |= uint(in[si+1]) << 8 - } - - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F]) - - switch remain { - case 2: - w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>6&0x3F], byte(padChar)) - case 1: - w.Buffer.Buf = append(w.Buffer.Buf, byte(padChar), byte(padChar)) - } -} diff --git a/vendor/github.com/moby/term/term_unix.go b/vendor/github.com/moby/term/term_unix.go index 2ec7706a16a3..579ce5530a7e 100644 --- a/vendor/github.com/moby/term/term_unix.go +++ b/vendor/github.com/moby/term/term_unix.go @@ -81,7 +81,7 @@ func setRawTerminal(fd uintptr) (*State, error) { return makeRaw(fd) } -func setRawTerminalOutput(fd uintptr) (*State, error) { +func setRawTerminalOutput(uintptr) (*State, error) { return nil, nil } diff --git a/vendor/github.com/openshift-online/ocm-common/pkg/resource/validations/kms_arn_regex_validation.go b/vendor/github.com/openshift-online/ocm-common/pkg/resource/validations/kms_arn_regex_validation.go new file mode 100644 index 000000000000..8830dda6d54e --- /dev/null +++ b/vendor/github.com/openshift-online/ocm-common/pkg/resource/validations/kms_arn_regex_validation.go @@ -0,0 +1,21 @@ +package validations + +import ( + "fmt" + "regexp" +) + +var KmsArnRE = regexp.MustCompile( + `^arn:aws[\w-]*:kms:[\w-]+:\d{12}:key\/(mrk-[0-9a-f]{32}$|[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$)`, +) + +func ValidateKMSKeyARN(kmsKeyARN *string) error { + if kmsKeyARN == nil || *kmsKeyARN == "" { + return nil + } + + if !KmsArnRE.MatchString(*kmsKeyARN) { + return fmt.Errorf("expected the kms-key-arn: %s to match %s", *kmsKeyARN, KmsArnRE) + } + return nil +} diff --git a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/agentcluster_types.go b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/agentcluster_types.go index 349ec0296f11..d57a807ddec3 100644 --- a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/agentcluster_types.go +++ b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/agentcluster_types.go @@ -18,7 +18,7 @@ package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) type ClusterDeploymentReference struct { diff --git a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/agentmachine_types.go b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/agentmachine_types.go index 1fd8c7e1d900..6ed3a6c14b9c 100644 --- a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/agentmachine_types.go +++ b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/agentmachine_types.go @@ -18,7 +18,7 @@ package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/cluster-api/errors" ) diff --git a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/zz_generated.deepcopy.go index 0fe09571b1fe..b521e0045d4d 100644 --- a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1alpha1/zz_generated.deepcopy.go @@ -23,7 +23,7 @@ package v1alpha1 import ( "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/cluster-api/api/v1beta1" + "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/cluster-api/errors" ) diff --git a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/agentcluster_types.go b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/agentcluster_types.go index 83fcc0394d71..5a0fcc8a84b8 100644 --- a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/agentcluster_types.go +++ b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/agentcluster_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) type ClusterDeploymentReference struct { diff --git a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/agentmachine_types.go b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/agentmachine_types.go index dc71aef9af9a..8169eb7aeed9 100644 --- a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/agentmachine_types.go +++ b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/agentmachine_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/cluster-api/errors" ) diff --git a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/zz_generated.deepcopy.go index f4b203c31c20..c6f41a3ec729 100644 --- a/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/github.com/openshift/cluster-api-provider-agent/api/v1beta1/zz_generated.deepcopy.go @@ -23,7 +23,7 @@ package v1beta1 import ( "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/cluster-api/errors" ) @@ -113,14 +113,14 @@ func (in *AgentClusterStatus) DeepCopyInto(out *AgentClusterStatus) { out.ClusterDeploymentRef = in.ClusterDeploymentRef if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.FailureDomains != nil { in, out := &in.FailureDomains, &out.FailureDomains - *out = make(apiv1beta1.FailureDomains, len(*in)) + *out = make(corev1beta1.FailureDomains, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -231,7 +231,7 @@ func (in *AgentMachineStatus) DeepCopyInto(out *AgentMachineStatus) { } if in.Addresses != nil { in, out := &in.Addresses, &out.Addresses - *out = make([]apiv1beta1.MachineAddress, len(*in)) + *out = make([]corev1beta1.MachineAddress, len(*in)) copy(*out, *in) } if in.FailureReason != nil { @@ -246,7 +246,7 @@ func (in *AgentMachineStatus) DeepCopyInto(out *AgentMachineStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/vendor/github.com/openshift/hypershift/api/hypershift/v1beta1/hosted_controlplane.go b/vendor/github.com/openshift/hypershift/api/hypershift/v1beta1/hosted_controlplane.go index 585a3b3d4193..a79f948481e4 100644 --- a/vendor/github.com/openshift/hypershift/api/hypershift/v1beta1/hosted_controlplane.go +++ b/vendor/github.com/openshift/hypershift/api/hypershift/v1beta1/hosted_controlplane.go @@ -332,6 +332,12 @@ type HostedControlPlaneStatus struct { // +kubebuilder:default=false Initialized bool `json:"initialized"` + // initialization contains observations of the HostedControlPlane initialization process. + // This satisfies the CAPI v1beta2 ControlPlane provider contract: + // https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + // +optional + Initialization HostedControlPlaneInitializationStatus `json:"initialization,omitzero,omitempty"` + // externalManagedControlPlane indicates to cluster-api that the control plane // is managed by an external service. // https://github.com/kubernetes-sigs/cluster-api/blob/65e5385bffd71bf4aad3cf34a537f11b217c7fab/controllers/machine_controller.go#L468 @@ -447,3 +453,17 @@ type HostedControlPlaneList struct { // +kubebuilder:validation:MaxItems=100 Items []HostedControlPlane `json:"items"` } + +// HostedControlPlaneInitializationStatus provides observations of the HostedControlPlane initialization process. +// This satisfies the CAPI v1beta2 ControlPlane provider contract: +// https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1361-L1379 +// +kubebuilder:validation:MinProperties=1 +type HostedControlPlaneInitializationStatus struct { + // controlPlaneInitialized is true when the control plane is functional enough to accept requests. + // Once this condition is marked true, its value is never changed. See the Ready condition for an + // indication of the current readiness of the cluster's control plane. + // This satisfies CAPI contract https://github.com/kubernetes-sigs/cluster-api/blob/v1.11.5/api/core/v1beta2/cluster_types.go#L1371-L1379 + // +optional + // +default=false + ControlPlaneInitialized *bool `json:"controlPlaneInitialized,omitempty"` +} diff --git a/vendor/github.com/openshift/hypershift/api/hypershift/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/openshift/hypershift/api/hypershift/v1beta1/zz_generated.deepcopy.go index 558be0746f8f..d10fca24596b 100644 --- a/vendor/github.com/openshift/hypershift/api/hypershift/v1beta1/zz_generated.deepcopy.go +++ b/vendor/github.com/openshift/hypershift/api/hypershift/v1beta1/zz_generated.deepcopy.go @@ -2482,6 +2482,26 @@ func (in *HostedControlPlane) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HostedControlPlaneInitializationStatus) DeepCopyInto(out *HostedControlPlaneInitializationStatus) { + *out = *in + if in.ControlPlaneInitialized != nil { + in, out := &in.ControlPlaneInitialized, &out.ControlPlaneInitialized + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HostedControlPlaneInitializationStatus. +func (in *HostedControlPlaneInitializationStatus) DeepCopy() *HostedControlPlaneInitializationStatus { + if in == nil { + return nil + } + out := new(HostedControlPlaneInitializationStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HostedControlPlaneList) DeepCopyInto(out *HostedControlPlaneList) { *out = *in @@ -2636,6 +2656,7 @@ func (in *HostedControlPlaneStatus) DeepCopyInto(out *HostedControlPlaneStatus) (*in)[i].DeepCopyInto(&(*out)[i]) } } + in.Initialization.DeepCopyInto(&out.Initialization) if in.ExternalManagedControlPlane != nil { in, out := &in.ExternalManagedControlPlane, &out.ExternalManagedControlPlane *out = new(bool) diff --git a/vendor/github.com/prometheus/procfs/.golangci.yml b/vendor/github.com/prometheus/procfs/.golangci.yml index 3c3bf910fdfb..23ecd4505b2a 100644 --- a/vendor/github.com/prometheus/procfs/.golangci.yml +++ b/vendor/github.com/prometheus/procfs/.golangci.yml @@ -1,7 +1,9 @@ version: "2" linters: enable: + - errorlint - forbidigo + - gocritic - godot - misspell - revive @@ -11,6 +13,20 @@ linters: forbid: - pattern: ^fmt\.Print.*$ msg: Do not commit print statements. + gocritic: + enable-all: true + disabled-checks: + - commentFormatting + - commentedOutCode + - deferInLoop + - filepathJoin + - hugeParam + - importShadow + - paramTypeCombine + - rangeValCopy + - tooManyResultsChecker + - unnamedResult + - whyNoLint godot: exclude: # Ignore "See: URL". @@ -19,16 +35,12 @@ linters: misspell: locale: US exclusions: - generated: lax presets: - comments - common-false-positives - legacy - std-error-handling - paths: - - third_party$ - - builtin$ - - examples$ + warn-unused: true formatters: enable: - gofmt @@ -37,9 +49,3 @@ formatters: goimports: local-prefixes: - github.com/prometheus/procfs - exclusions: - generated: lax - paths: - - third_party$ - - builtin$ - - examples$ diff --git a/vendor/github.com/prometheus/procfs/Makefile b/vendor/github.com/prometheus/procfs/Makefile index 7edfe4d09325..bce50a19c504 100644 --- a/vendor/github.com/prometheus/procfs/Makefile +++ b/vendor/github.com/prometheus/procfs/Makefile @@ -1,4 +1,4 @@ -# Copyright 2018 The Prometheus Authors +# Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/Makefile.common b/vendor/github.com/prometheus/procfs/Makefile.common index 0ed55c2ba21f..6f61bec48fdb 100644 --- a/vendor/github.com/prometheus/procfs/Makefile.common +++ b/vendor/github.com/prometheus/procfs/Makefile.common @@ -33,7 +33,7 @@ GOHOSTOS ?= $(shell $(GO) env GOHOSTOS) GOHOSTARCH ?= $(shell $(GO) env GOHOSTARCH) GO_VERSION ?= $(shell $(GO) version) -GO_VERSION_NUMBER ?= $(word 3, $(GO_VERSION))Error Parsing File +GO_VERSION_NUMBER ?= $(word 3, $(GO_VERSION)) PRE_GO_111 ?= $(shell echo $(GO_VERSION_NUMBER) | grep -E 'go1\.(10|[0-9])\.') PROMU := $(FIRST_GOPATH)/bin/promu @@ -61,7 +61,8 @@ PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_ SKIP_GOLANGCI_LINT := GOLANGCI_LINT := GOLANGCI_LINT_OPTS ?= -GOLANGCI_LINT_VERSION ?= v2.0.2 +GOLANGCI_LINT_VERSION ?= v2.1.5 +GOLANGCI_FMT_OPTS ?= # golangci-lint only supports linux, darwin and windows platforms on i386/amd64/arm64. # windows isn't included here because of the path separator being different. ifeq ($(GOHOSTOS),$(filter $(GOHOSTOS),linux darwin)) @@ -138,7 +139,7 @@ common-deps: update-go-deps: @echo ">> updating Go dependencies" @for m in $$($(GO) list -mod=readonly -m -f '{{ if and (not .Indirect) (not .Main)}}{{.Path}}{{end}}' all); do \ - $(GO) get -d $$m; \ + $(GO) get $$m; \ done $(GO) mod tidy @@ -156,9 +157,13 @@ $(GOTEST_DIR): @mkdir -p $@ .PHONY: common-format -common-format: +common-format: $(GOLANGCI_LINT) @echo ">> formatting code" $(GO) fmt $(pkgs) +ifdef GOLANGCI_LINT + @echo ">> formatting code with golangci-lint" + $(GOLANGCI_LINT) fmt $(GOLANGCI_FMT_OPTS) +endif .PHONY: common-vet common-vet: @@ -248,8 +253,8 @@ $(PROMU): cp $(PROMU_TMP)/promu-$(PROMU_VERSION).$(GO_BUILD_PLATFORM)/promu $(FIRST_GOPATH)/bin/promu rm -r $(PROMU_TMP) -.PHONY: proto -proto: +.PHONY: common-proto +common-proto: @echo ">> generating code from proto files" @./scripts/genproto.sh diff --git a/vendor/github.com/prometheus/procfs/arp.go b/vendor/github.com/prometheus/procfs/arp.go index 2e53344151f5..716bdef10909 100644 --- a/vendor/github.com/prometheus/procfs/arp.go +++ b/vendor/github.com/prometheus/procfs/arp.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -73,15 +73,16 @@ func parseARPEntries(data []byte) ([]ARPEntry, error) { columns := strings.Fields(line) width := len(columns) - if width == expectedHeaderWidth || width == 0 { + switch width { + case expectedHeaderWidth, 0: continue - } else if width == expectedDataWidth { + case expectedDataWidth: entry, err := parseARPEntry(columns) if err != nil { return []ARPEntry{}, fmt.Errorf("%w: Failed to parse ARP entry: %v: %w", ErrFileParse, entry, err) } entries = append(entries, entry) - } else { + default: return []ARPEntry{}, fmt.Errorf("%w: %d columns found, but expected %d: %w", ErrFileParse, width, expectedDataWidth, err) } diff --git a/vendor/github.com/prometheus/procfs/buddyinfo.go b/vendor/github.com/prometheus/procfs/buddyinfo.go index 83807500908f..53243e687583 100644 --- a/vendor/github.com/prometheus/procfs/buddyinfo.go +++ b/vendor/github.com/prometheus/procfs/buddyinfo.go @@ -1,4 +1,4 @@ -// Copyright 2017 The Prometheus Authors +// Copyright 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 @@ -64,14 +64,12 @@ func parseBuddyInfo(r io.Reader) ([]BuddyInfo, error) { if bucketCount == -1 { bucketCount = arraySize - } else { - if bucketCount != arraySize { - return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, bucketCount, arraySize) - } + } else if bucketCount != arraySize { + return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, bucketCount, arraySize) } sizes := make([]float64, arraySize) - for i := 0; i < arraySize; i++ { + for i := range arraySize { sizes[i], err = strconv.ParseFloat(parts[i+4], 64) if err != nil { return nil, fmt.Errorf("%w: Invalid valid in buddyinfo: %f: %w", ErrFileParse, sizes[i], err) diff --git a/vendor/github.com/prometheus/procfs/cmdline.go b/vendor/github.com/prometheus/procfs/cmdline.go index bf4f3b48c0e8..4f1cac1f0ac7 100644 --- a/vendor/github.com/prometheus/procfs/cmdline.go +++ b/vendor/github.com/prometheus/procfs/cmdline.go @@ -1,4 +1,4 @@ -// Copyright 2021 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo.go b/vendor/github.com/prometheus/procfs/cpuinfo.go index f0950bb49534..5fe6cecd3dd5 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_armx.go b/vendor/github.com/prometheus/procfs/cpuinfo_armx.go index 64cfd534c1f9..8f155551e527 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_armx.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_armx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go b/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go index d88442f0edfd..e81a5db94905 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go b/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go index c11207f3ab61..4be2b1cc549d 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_others.go b/vendor/github.com/prometheus/procfs/cpuinfo_others.go index a6b2b3127cb1..e713bae8dfe6 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_others.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_others.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go b/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go index 003bc2ad4a33..0825aa1a8308 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go b/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go index 1c9b7313b6cb..496770b05f6e 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go b/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go index fa3686bc0048..b3228ce3d861 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_x86.go b/vendor/github.com/prometheus/procfs/cpuinfo_x86.go index a0ef55562ebb..575eb022eb0a 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo_x86.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo_x86.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/crypto.go b/vendor/github.com/prometheus/procfs/crypto.go index 5f2a37a78b3f..e4a5876eafbc 100644 --- a/vendor/github.com/prometheus/procfs/crypto.go +++ b/vendor/github.com/prometheus/procfs/crypto.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/doc.go b/vendor/github.com/prometheus/procfs/doc.go index f9d961e44179..26bfea071bae 100644 --- a/vendor/github.com/prometheus/procfs/doc.go +++ b/vendor/github.com/prometheus/procfs/doc.go @@ -1,4 +1,4 @@ -// Copyright 2014 Prometheus Team +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/fs.go b/vendor/github.com/prometheus/procfs/fs.go index 9bdaccc7c8a4..8f27912a13a5 100644 --- a/vendor/github.com/prometheus/procfs/fs.go +++ b/vendor/github.com/prometheus/procfs/fs.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go index 1b5bdbdf84ac..3c53023c5440 100644 --- a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go +++ b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_type.go b/vendor/github.com/prometheus/procfs/fs_statfs_type.go index 80df79c31930..80fce484789e 100644 --- a/vendor/github.com/prometheus/procfs/fs_statfs_type.go +++ b/vendor/github.com/prometheus/procfs/fs_statfs_type.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/fscache.go b/vendor/github.com/prometheus/procfs/fscache.go index 7db863307793..9dde85707376 100644 --- a/vendor/github.com/prometheus/procfs/fscache.go +++ b/vendor/github.com/prometheus/procfs/fscache.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -388,20 +388,21 @@ func parseFscacheinfo(r io.Reader) (*Fscacheinfo, error) { } } case "CacheOp:": - if strings.Split(fields[1], "=")[0] == "alo" { + switch strings.Split(fields[1], "=")[0] { + case "alo": err := setFSCacheFields(fields[1:], &m.CacheopAllocationsinProgress, &m.CacheopLookupObjectInProgress, &m.CacheopLookupCompleteInPorgress, &m.CacheopGrabObjectInProgress) if err != nil { return &m, err } - } else if strings.Split(fields[1], "=")[0] == "inv" { + case "inv": err := setFSCacheFields(fields[1:], &m.CacheopInvalidations, &m.CacheopUpdateObjectInProgress, &m.CacheopDropObjectInProgress, &m.CacheopPutObjectInProgress, &m.CacheopAttributeChangeInProgress, &m.CacheopSyncCacheInProgress) if err != nil { return &m, err } - } else { + default: err := setFSCacheFields(fields[1:], &m.CacheopReadOrAllocPageInProgress, &m.CacheopReadOrAllocPagesInProgress, &m.CacheopAllocatePageInProgress, &m.CacheopAllocatePagesInProgress, &m.CacheopWritePagesInProgress, &m.CacheopUncachePagesInProgress, &m.CacheopDissociatePagesInProgress) diff --git a/vendor/github.com/prometheus/procfs/internal/fs/fs.go b/vendor/github.com/prometheus/procfs/internal/fs/fs.go index 3a43e83915f5..e7ccad66b2ed 100644 --- a/vendor/github.com/prometheus/procfs/internal/fs/fs.go +++ b/vendor/github.com/prometheus/procfs/internal/fs/fs.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/internal/util/parse.go b/vendor/github.com/prometheus/procfs/internal/util/parse.go index 5a7d2df06ae3..30c5872019a9 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/parse.go +++ b/vendor/github.com/prometheus/procfs/internal/util/parse.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/internal/util/readfile.go b/vendor/github.com/prometheus/procfs/internal/util/readfile.go index 71b7a70ebd68..0e41f71af189 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/readfile.go +++ b/vendor/github.com/prometheus/procfs/internal/util/readfile.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go index d5404a6d7284..8318d8dfd519 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go +++ b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go index 1d86f5e63f3c..15bb096ee20f 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go +++ b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go b/vendor/github.com/prometheus/procfs/internal/util/valueparser.go index fe2355d3c6ff..e0ed671ea076 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go +++ b/vendor/github.com/prometheus/procfs/internal/util/valueparser.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/ipvs.go b/vendor/github.com/prometheus/procfs/ipvs.go index bc3a20c932d1..5374da9fa891 100644 --- a/vendor/github.com/prometheus/procfs/ipvs.go +++ b/vendor/github.com/prometheus/procfs/ipvs.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/kernel_hung.go b/vendor/github.com/prometheus/procfs/kernel_hung.go new file mode 100644 index 000000000000..539c11151420 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/kernel_hung.go @@ -0,0 +1,45 @@ +// Copyright 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 !windows +// +build !windows + +package procfs + +import ( + "os" + "strconv" + "strings" +) + +// KernelHung contains information about to the kernel's hung_task_detect_count number. +type KernelHung struct { + // Indicates the total number of tasks that have been detected as hung since the system boot. + // This file shows up if `CONFIG_DETECT_HUNG_TASK` is enabled. + HungTaskDetectCount *uint64 +} + +// KernelHung returns values from /proc/sys/kernel/hung_task_detect_count. +func (fs FS) KernelHung() (KernelHung, error) { + data, err := os.ReadFile(fs.proc.Path("sys", "kernel", "hung_task_detect_count")) + if err != nil { + return KernelHung{}, err + } + val, err := strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) + if err != nil { + return KernelHung{}, err + } + return KernelHung{ + HungTaskDetectCount: &val, + }, nil +} diff --git a/vendor/github.com/prometheus/procfs/kernel_random.go b/vendor/github.com/prometheus/procfs/kernel_random.go index db88566bdf0a..b66565a1043d 100644 --- a/vendor/github.com/prometheus/procfs/kernel_random.go +++ b/vendor/github.com/prometheus/procfs/kernel_random.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/loadavg.go b/vendor/github.com/prometheus/procfs/loadavg.go index 332e76c17f5b..c8c78a65edc5 100644 --- a/vendor/github.com/prometheus/procfs/loadavg.go +++ b/vendor/github.com/prometheus/procfs/loadavg.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/mdstat.go b/vendor/github.com/prometheus/procfs/mdstat.go index 67a9d2b44867..d66eeda82a2f 100644 --- a/vendor/github.com/prometheus/procfs/mdstat.go +++ b/vendor/github.com/prometheus/procfs/mdstat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -27,13 +27,34 @@ var ( recoveryLinePctRE = regexp.MustCompile(`= (.+)%`) recoveryLineFinishRE = regexp.MustCompile(`finish=(.+)min`) recoveryLineSpeedRE = regexp.MustCompile(`speed=(.+)[A-Z]`) - componentDeviceRE = regexp.MustCompile(`(.*)\[\d+\]`) + componentDeviceRE = regexp.MustCompile(`(.*)\[(\d+)\](\([SF]+\))?`) + personalitiesPrefix = "Personalities : " ) +type MDStatComponent struct { + // Name of the component device. + Name string + // DescriptorIndex number of component device, e.g. the order in the superblock. + DescriptorIndex int32 + // Flags per Linux drivers/md/md.[ch] as of v6.12-rc1 + // Subset that are exposed in mdstat + WriteMostly bool + Journal bool + Faulty bool // "Faulty" is what kernel source uses for "(F)" + Spare bool + Replacement bool + // Some additional flags that are NOT exposed in procfs today; they may + // be available via sysfs. + // In_sync, Bitmap_sync, Blocked, WriteErrorSeen, FaultRecorded, + // BlockedBadBlocks, WantReplacement, Candidate, ... +} + // MDStat holds info parsed from /proc/mdstat. type MDStat struct { // Name of the device. Name string + // raid type of the device. + Type string // activity-state of the device. ActivityState string // Number of active disks. @@ -58,8 +79,8 @@ type MDStat struct { BlocksSyncedFinishTime float64 // current sync speed (in Kilobytes/sec) BlocksSyncedSpeed float64 - // Name of md component devices - Devices []string + // component devices + Devices []MDStatComponent } // MDStat parses an mdstat-file (/proc/mdstat) and returns a slice of @@ -80,28 +101,52 @@ func (fs FS) MDStat() ([]MDStat, error) { // parseMDStat parses data from mdstat file (/proc/mdstat) and returns a slice of // structs containing the relevant info. func parseMDStat(mdStatData []byte) ([]MDStat, error) { + // TODO: + // - parse global hotspares from the "unused devices" line. mdStats := []MDStat{} lines := strings.Split(string(mdStatData), "\n") + knownRaidTypes := make(map[string]bool) for i, line := range lines { if strings.TrimSpace(line) == "" || line[0] == ' ' || - strings.HasPrefix(line, "Personalities") || strings.HasPrefix(line, "unused") { continue } + // Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10] + if len(knownRaidTypes) == 0 && strings.HasPrefix(line, personalitiesPrefix) { + personalities := strings.Fields(line[len(personalitiesPrefix):]) + for _, word := range personalities { + word := word[1 : len(word)-1] + knownRaidTypes[word] = true + } + continue + } deviceFields := strings.Fields(line) if len(deviceFields) < 3 { return nil, fmt.Errorf("%w: Expected 3+ lines, got %q", ErrFileParse, line) } mdName := deviceFields[0] // mdx - state := deviceFields[2] // active or inactive + state := deviceFields[2] // active, inactive, broken + + mdType := "unknown" // raid1, raid5, etc. + var deviceStartIndex int + if len(deviceFields) > 3 { // mdType may be in the 3rd or 4th field + if isRaidType(deviceFields[3], knownRaidTypes) { + mdType = deviceFields[3] + deviceStartIndex = 4 + } else if len(deviceFields) > 4 && isRaidType(deviceFields[4], knownRaidTypes) { + // if the 3rd field is (...), the 4th field is the mdType + mdType = deviceFields[4] + deviceStartIndex = 5 + } + } if len(lines) <= i+3 { return nil, fmt.Errorf("%w: Too few lines for md device: %q", ErrFileParse, mdName) } - // Failed disks have the suffix (F) & Spare disks have the suffix (S). + // Failed (Faulty) disks have the suffix (F) & Spare disks have the suffix (S). fail := int64(strings.Count(line, "(F)")) spare := int64(strings.Count(line, "(S)")) active, total, down, size, err := evalStatusLine(lines[i], lines[i+1]) @@ -123,16 +168,20 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { finish := float64(0) pct := float64(0) recovering := strings.Contains(lines[syncLineIdx], "recovery") + reshaping := strings.Contains(lines[syncLineIdx], "reshape") resyncing := strings.Contains(lines[syncLineIdx], "resync") checking := strings.Contains(lines[syncLineIdx], "check") // Append recovery and resyncing state info. - if recovering || resyncing || checking { - if recovering { + if recovering || resyncing || checking || reshaping { + switch { + case recovering: state = "recovering" - } else if checking { + case reshaping: + state = "reshaping" + case checking: state = "checking" - } else { + default: state = "resyncing" } @@ -148,8 +197,14 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { } } + devices, err := evalComponentDevices(deviceFields[deviceStartIndex:]) + if err != nil { + return nil, fmt.Errorf("error parsing components in md device %q: %w", mdName, err) + } + mdStats = append(mdStats, MDStat{ Name: mdName, + Type: mdType, ActivityState: state, DisksActive: active, DisksFailed: fail, @@ -162,14 +217,24 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) { BlocksSyncedPct: pct, BlocksSyncedFinishTime: finish, BlocksSyncedSpeed: speed, - Devices: evalComponentDevices(deviceFields), + Devices: devices, }) } return mdStats, nil } +// check if a string's format is like the mdType +// Rule 1: mdType should not be like (...) +// Rule 2: mdType should not be like sda[0] +// . +func isRaidType(mdType string, knownRaidTypes map[string]bool) bool { + _, ok := knownRaidTypes[mdType] + return !strings.ContainsAny(mdType, "([") && ok +} + func evalStatusLine(deviceLine, statusLine string) (active, total, down, size int64, err error) { + // e.g. 523968 blocks super 1.2 [4/4] [UUUU] statusFields := strings.Fields(statusLine) if len(statusFields) < 1 { return 0, 0, 0, 0, fmt.Errorf("%w: Unexpected statusline %q: %w", ErrFileParse, statusLine, err) @@ -260,17 +325,29 @@ func evalRecoveryLine(recoveryLine string) (blocksSynced int64, blocksToBeSynced return blocksSynced, blocksToBeSynced, pct, finish, speed, nil } -func evalComponentDevices(deviceFields []string) []string { - mdComponentDevices := make([]string, 0) - if len(deviceFields) > 3 { - for _, field := range deviceFields[4:] { - match := componentDeviceRE.FindStringSubmatch(field) - if match == nil { - continue - } - mdComponentDevices = append(mdComponentDevices, match[1]) +func evalComponentDevices(deviceFields []string) ([]MDStatComponent, error) { + mdComponentDevices := make([]MDStatComponent, 0) + for _, field := range deviceFields { + match := componentDeviceRE.FindStringSubmatch(field) + if match == nil { + continue + } + descriptorIndex, err := strconv.ParseInt(match[2], 10, 32) + if err != nil { + return mdComponentDevices, fmt.Errorf("error parsing int from device %q: %w", match[2], err) } + mdComponentDevices = append(mdComponentDevices, MDStatComponent{ + Name: match[1], + DescriptorIndex: int32(descriptorIndex), + // match may contain one or more of these + // https://github.com/torvalds/linux/blob/7ec462100ef9142344ddbf86f2c3008b97acddbe/drivers/md/md.c#L8376-L8392 + Faulty: strings.Contains(match[3], "(F)"), + Spare: strings.Contains(match[3], "(S)"), + Journal: strings.Contains(match[3], "(J)"), + Replacement: strings.Contains(match[3], "(R)"), + WriteMostly: strings.Contains(match[3], "(W)"), + }) } - return mdComponentDevices + return mdComponentDevices, nil } diff --git a/vendor/github.com/prometheus/procfs/meminfo.go b/vendor/github.com/prometheus/procfs/meminfo.go index 4b2c4050a3df..34203831871e 100644 --- a/vendor/github.com/prometheus/procfs/meminfo.go +++ b/vendor/github.com/prometheus/procfs/meminfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -66,6 +66,10 @@ type Meminfo struct { // Memory which has been evicted from RAM, and is temporarily // on the disk SwapFree *uint64 + // Memory consumed by the zswap backend (compressed size) + Zswap *uint64 + // Amount of anonymous memory stored in zswap (original size) + Zswapped *uint64 // Memory which is waiting to get written back to the disk Dirty *uint64 // Memory which is actively being written back to the disk @@ -85,6 +89,8 @@ type Meminfo struct { // amount of memory dedicated to the lowest level of page // tables. PageTables *uint64 + // secondary page tables. + SecPageTables *uint64 // NFS pages sent to the server, but not yet committed to // stable storage NFSUnstable *uint64 @@ -129,15 +135,18 @@ type Meminfo struct { Percpu *uint64 HardwareCorrupted *uint64 AnonHugePages *uint64 + FileHugePages *uint64 ShmemHugePages *uint64 ShmemPmdMapped *uint64 CmaTotal *uint64 CmaFree *uint64 + Unaccepted *uint64 HugePagesTotal *uint64 HugePagesFree *uint64 HugePagesRsvd *uint64 HugePagesSurp *uint64 Hugepagesize *uint64 + Hugetlb *uint64 DirectMap4k *uint64 DirectMap2M *uint64 DirectMap1G *uint64 @@ -161,6 +170,8 @@ type Meminfo struct { MlockedBytes *uint64 SwapTotalBytes *uint64 SwapFreeBytes *uint64 + ZswapBytes *uint64 + ZswappedBytes *uint64 DirtyBytes *uint64 WritebackBytes *uint64 AnonPagesBytes *uint64 @@ -171,6 +182,7 @@ type Meminfo struct { SUnreclaimBytes *uint64 KernelStackBytes *uint64 PageTablesBytes *uint64 + SecPageTablesBytes *uint64 NFSUnstableBytes *uint64 BounceBytes *uint64 WritebackTmpBytes *uint64 @@ -182,11 +194,14 @@ type Meminfo struct { PercpuBytes *uint64 HardwareCorruptedBytes *uint64 AnonHugePagesBytes *uint64 + FileHugePagesBytes *uint64 ShmemHugePagesBytes *uint64 ShmemPmdMappedBytes *uint64 CmaTotalBytes *uint64 CmaFreeBytes *uint64 + UnacceptedBytes *uint64 HugepagesizeBytes *uint64 + HugetlbBytes *uint64 DirectMap4kBytes *uint64 DirectMap2MBytes *uint64 DirectMap1GBytes *uint64 @@ -287,6 +302,12 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "SwapFree:": m.SwapFree = &val m.SwapFreeBytes = &valBytes + case "Zswap:": + m.Zswap = &val + m.ZswapBytes = &valBytes + case "Zswapped:": + m.Zswapped = &val + m.ZswappedBytes = &valBytes case "Dirty:": m.Dirty = &val m.DirtyBytes = &valBytes @@ -317,6 +338,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "PageTables:": m.PageTables = &val m.PageTablesBytes = &valBytes + case "SecPageTables:": + m.SecPageTables = &val + m.SecPageTablesBytes = &valBytes case "NFS_Unstable:": m.NFSUnstable = &val m.NFSUnstableBytes = &valBytes @@ -350,6 +374,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "AnonHugePages:": m.AnonHugePages = &val m.AnonHugePagesBytes = &valBytes + case "FileHugePages:": + m.FileHugePages = &val + m.FileHugePagesBytes = &valBytes case "ShmemHugePages:": m.ShmemHugePages = &val m.ShmemHugePagesBytes = &valBytes @@ -362,6 +389,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "CmaFree:": m.CmaFree = &val m.CmaFreeBytes = &valBytes + case "Unaccepted:": + m.Unaccepted = &val + m.UnacceptedBytes = &valBytes case "HugePages_Total:": m.HugePagesTotal = &val case "HugePages_Free:": @@ -373,6 +403,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) { case "Hugepagesize:": m.Hugepagesize = &val m.HugepagesizeBytes = &valBytes + case "Hugetlb:": + m.Hugetlb = &val + m.HugetlbBytes = &valBytes case "DirectMap4k:": m.DirectMap4k = &val m.DirectMap4kBytes = &valBytes diff --git a/vendor/github.com/prometheus/procfs/mountinfo.go b/vendor/github.com/prometheus/procfs/mountinfo.go index a704c5e735f3..9414a12f42f0 100644 --- a/vendor/github.com/prometheus/procfs/mountinfo.go +++ b/vendor/github.com/prometheus/procfs/mountinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -147,8 +147,7 @@ func mountOptionsParseOptionalFields(o []string) (map[string]string, error) { // mountOptionsParser parses the mount options, superblock options. func mountOptionsParser(mountOptions string) map[string]string { opts := make(map[string]string) - options := strings.Split(mountOptions, ",") - for _, opt := range options { + for opt := range strings.SplitSeq(mountOptions, ",") { splitOption := strings.Split(opt, "=") if len(splitOption) < 2 { key := splitOption[0] @@ -178,3 +177,21 @@ func GetProcMounts(pid int) ([]*MountInfo, error) { } return parseMountInfo(data) } + +// GetMounts retrieves mountinfo information from `/proc/self/mountinfo`. +func (fs FS) GetMounts() ([]*MountInfo, error) { + data, err := util.ReadFileNoStat(fs.proc.Path("self/mountinfo")) + if err != nil { + return nil, err + } + return parseMountInfo(data) +} + +// GetProcMounts retrieves mountinfo information from a processes' `/proc//mountinfo`. +func (fs FS) GetProcMounts(pid int) ([]*MountInfo, error) { + data, err := util.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%d/mountinfo", pid))) + if err != nil { + return nil, err + } + return parseMountInfo(data) +} diff --git a/vendor/github.com/prometheus/procfs/mountstats.go b/vendor/github.com/prometheus/procfs/mountstats.go index 50caa73274eb..e503cb3a6c5d 100644 --- a/vendor/github.com/prometheus/procfs/mountstats.go +++ b/vendor/github.com/prometheus/procfs/mountstats.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -383,7 +383,7 @@ func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, e if stats.Opts == nil { stats.Opts = map[string]string{} } - for _, opt := range strings.Split(ss[1], ",") { + for opt := range strings.SplitSeq(ss[1], ",") { split := strings.Split(opt, "=") if len(split) == 2 { stats.Opts[split[0]] = split[1] diff --git a/vendor/github.com/prometheus/procfs/net_conntrackstat.go b/vendor/github.com/prometheus/procfs/net_conntrackstat.go index 316df5fbb74e..e9ca35707905 100644 --- a/vendor/github.com/prometheus/procfs/net_conntrackstat.go +++ b/vendor/github.com/prometheus/procfs/net_conntrackstat.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_dev.go b/vendor/github.com/prometheus/procfs/net_dev.go index e66208aa05fe..7b3e1d61c95e 100644 --- a/vendor/github.com/prometheus/procfs/net_dev.go +++ b/vendor/github.com/prometheus/procfs/net_dev.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_dev_snmp6.go b/vendor/github.com/prometheus/procfs/net_dev_snmp6.go index f50b38e35288..2a0f60f29fee 100644 --- a/vendor/github.com/prometheus/procfs/net_dev_snmp6.go +++ b/vendor/github.com/prometheus/procfs/net_dev_snmp6.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -18,6 +18,7 @@ import ( "errors" "io" "os" + "path/filepath" "strconv" "strings" ) @@ -56,7 +57,9 @@ func newNetDevSNMP6(dir string) (NetDevSNMP6, error) { } for _, iFaceFile := range ifaceFiles { - f, err := os.Open(dir + "/" + iFaceFile.Name()) + filePath := filepath.Join(dir, iFaceFile.Name()) + + f, err := os.Open(filePath) if err != nil { return netDevSNMP6, err } diff --git a/vendor/github.com/prometheus/procfs/net_ip_socket.go b/vendor/github.com/prometheus/procfs/net_ip_socket.go index 19e3378f72d7..9291f8cd4c80 100644 --- a/vendor/github.com/prometheus/procfs/net_ip_socket.go +++ b/vendor/github.com/prometheus/procfs/net_ip_socket.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_protocols.go b/vendor/github.com/prometheus/procfs/net_protocols.go index 8d4b1ac05b00..eaa996cbcf19 100644 --- a/vendor/github.com/prometheus/procfs/net_protocols.go +++ b/vendor/github.com/prometheus/procfs/net_protocols.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 @@ -169,7 +169,7 @@ func (pc *NetProtocolCapabilities) parseCapabilities(capabilities []string) erro &pc.EnterMemoryPressure, } - for i := 0; i < len(capabilities); i++ { + for i := range capabilities { switch capabilities[i] { case "y": *capabilityFields[i] = true diff --git a/vendor/github.com/prometheus/procfs/net_route.go b/vendor/github.com/prometheus/procfs/net_route.go index deb7029fe1ef..fa3812d9d00c 100644 --- a/vendor/github.com/prometheus/procfs/net_route.go +++ b/vendor/github.com/prometheus/procfs/net_route.go @@ -1,4 +1,4 @@ -// Copyright 2023 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_sockstat.go b/vendor/github.com/prometheus/procfs/net_sockstat.go index fae62b13d961..8b221ebfff75 100644 --- a/vendor/github.com/prometheus/procfs/net_sockstat.go +++ b/vendor/github.com/prometheus/procfs/net_sockstat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -139,9 +139,6 @@ func parseSockstatKVs(kvs []string) (map[string]int, error) { func parseSockstatProtocol(kvs map[string]int) NetSockstatProtocol { var nsp NetSockstatProtocol for k, v := range kvs { - // Capture the range variable to ensure we get unique pointers for - // each of the optional fields. - v := v switch k { case "inuse": nsp.InUse = v diff --git a/vendor/github.com/prometheus/procfs/net_softnet.go b/vendor/github.com/prometheus/procfs/net_softnet.go index 71c8059f4d77..4a2dfa18fd82 100644 --- a/vendor/github.com/prometheus/procfs/net_softnet.go +++ b/vendor/github.com/prometheus/procfs/net_softnet.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_tcp.go b/vendor/github.com/prometheus/procfs/net_tcp.go index 0396d72015c0..610ea78e5648 100644 --- a/vendor/github.com/prometheus/procfs/net_tcp.go +++ b/vendor/github.com/prometheus/procfs/net_tcp.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_tls_stat.go b/vendor/github.com/prometheus/procfs/net_tls_stat.go index 13994c1782f4..b1b3f6a6a2f5 100644 --- a/vendor/github.com/prometheus/procfs/net_tls_stat.go +++ b/vendor/github.com/prometheus/procfs/net_tls_stat.go @@ -1,4 +1,4 @@ -// Copyright 2023 Prometheus Team +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_udp.go b/vendor/github.com/prometheus/procfs/net_udp.go index 9ac3daf2d4c5..8a327791026a 100644 --- a/vendor/github.com/prometheus/procfs/net_udp.go +++ b/vendor/github.com/prometheus/procfs/net_udp.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_unix.go b/vendor/github.com/prometheus/procfs/net_unix.go index d7e0cacb4c67..e4d635923659 100644 --- a/vendor/github.com/prometheus/procfs/net_unix.go +++ b/vendor/github.com/prometheus/procfs/net_unix.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_wireless.go b/vendor/github.com/prometheus/procfs/net_wireless.go index 7c597bc87089..69d079445161 100644 --- a/vendor/github.com/prometheus/procfs/net_wireless.go +++ b/vendor/github.com/prometheus/procfs/net_wireless.go @@ -1,4 +1,4 @@ -// Copyright 2023 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/net_xfrm.go b/vendor/github.com/prometheus/procfs/net_xfrm.go index 932ef2046847..5a9f497d1903 100644 --- a/vendor/github.com/prometheus/procfs/net_xfrm.go +++ b/vendor/github.com/prometheus/procfs/net_xfrm.go @@ -1,4 +1,4 @@ -// Copyright 2017 Prometheus Team +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/netstat.go b/vendor/github.com/prometheus/procfs/netstat.go index 742dff453ba8..dbdae473924b 100644 --- a/vendor/github.com/prometheus/procfs/netstat.go +++ b/vendor/github.com/prometheus/procfs/netstat.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/nfnetlink_queue.go b/vendor/github.com/prometheus/procfs/nfnetlink_queue.go new file mode 100644 index 000000000000..b0a73b11e9e4 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/nfnetlink_queue.go @@ -0,0 +1,85 @@ +// Copyright 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 procfs + +import ( + "bufio" + "bytes" + "fmt" + + "github.com/prometheus/procfs/internal/util" +) + +const nfNetLinkQueueFormat = "%d %d %d %d %d %d %d %d %d" + +// NFNetLinkQueue contains general information about netfilter queues found in /proc/net/netfilter/nfnetlink_queue. +type NFNetLinkQueue struct { + // id of the queue + QueueID uint + // pid of process handling the queue + PeerPID uint + // number of packets waiting for a decision + QueueTotal uint + // indicate how userspace receive packets + CopyMode uint + // size of copy + CopyRange uint + // number of items dropped by the kernel because too many packets were waiting a decision. + // It queue_total is superior to queue_max_len (1024 per default) the packets are dropped. + QueueDropped uint + // number of packets dropped by userspace (due to kernel send failure on the netlink socket) + QueueUserDropped uint + // sequence number of packets queued. It gives a correct approximation of the number of queued packets. + SequenceID uint + // internal value (number of entity using the queue) + Use uint +} + +// NFNetLinkQueue returns information about current state of netfilter queues. +func (fs FS) NFNetLinkQueue() ([]NFNetLinkQueue, error) { + data, err := util.ReadFileNoStat(fs.proc.Path("net/netfilter/nfnetlink_queue")) + if err != nil { + return nil, err + } + + queue := []NFNetLinkQueue{} + if len(data) == 0 { + return queue, nil + } + + scanner := bufio.NewScanner(bytes.NewReader(data)) + for scanner.Scan() { + line := scanner.Text() + nFNetLinkQueue, err := parseNFNetLinkQueueLine(line) + if err != nil { + return nil, err + } + queue = append(queue, *nFNetLinkQueue) + } + return queue, nil +} + +// parseNFNetLinkQueueLine parses each line of the /proc/net/netfilter/nfnetlink_queue file. +func parseNFNetLinkQueueLine(line string) (*NFNetLinkQueue, error) { + nFNetLinkQueue := NFNetLinkQueue{} + _, err := fmt.Sscanf( + line, nfNetLinkQueueFormat, + &nFNetLinkQueue.QueueID, &nFNetLinkQueue.PeerPID, &nFNetLinkQueue.QueueTotal, &nFNetLinkQueue.CopyMode, + &nFNetLinkQueue.CopyRange, &nFNetLinkQueue.QueueDropped, &nFNetLinkQueue.QueueUserDropped, &nFNetLinkQueue.SequenceID, &nFNetLinkQueue.Use, + ) + if err != nil { + return nil, err + } + return &nFNetLinkQueue, nil +} diff --git a/vendor/github.com/prometheus/procfs/proc.go b/vendor/github.com/prometheus/procfs/proc.go index 368187fa884d..39c14aa55ebd 100644 --- a/vendor/github.com/prometheus/procfs/proc.go +++ b/vendor/github.com/prometheus/procfs/proc.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -49,7 +49,7 @@ func (p Procs) Less(i, j int) bool { return p[i].PID < p[j].PID } // Self returns a process for the current process read via /proc/self. func Self() (Proc, error) { fs, err := NewFS(DefaultMountPoint) - if err != nil || errors.Unwrap(err) == ErrMountPoint { + if err != nil || errors.Is(err, ErrMountPoint) { return Proc{}, err } return fs.Self() diff --git a/vendor/github.com/prometheus/procfs/proc_cgroup.go b/vendor/github.com/prometheus/procfs/proc_cgroup.go index 4a64347c03a2..535c08d6fc01 100644 --- a/vendor/github.com/prometheus/procfs/proc_cgroup.go +++ b/vendor/github.com/prometheus/procfs/proc_cgroup.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_cgroups.go b/vendor/github.com/prometheus/procfs/proc_cgroups.go index 5dd4938999ad..0b275c3b1f5c 100644 --- a/vendor/github.com/prometheus/procfs/proc_cgroups.go +++ b/vendor/github.com/prometheus/procfs/proc_cgroups.go @@ -1,4 +1,4 @@ -// Copyright 2021 The Prometheus Authors +// Copyright 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 @@ -40,13 +40,13 @@ type CgroupSummary struct { // parseCgroupSummary parses each line of the /proc/cgroup file // Line format is `subsys_name hierarchy num_cgroups enabled`. -func parseCgroupSummaryString(CgroupSummaryStr string) (*CgroupSummary, error) { +func parseCgroupSummaryString(cgroupSummaryStr string) (*CgroupSummary, error) { var err error - fields := strings.Fields(CgroupSummaryStr) + fields := strings.Fields(cgroupSummaryStr) // require at least 4 fields if len(fields) < 4 { - return nil, fmt.Errorf("%w: 4+ fields required, found %d fields in cgroup info string: %s", ErrFileParse, len(fields), CgroupSummaryStr) + return nil, fmt.Errorf("%w: 4+ fields required, found %d fields in cgroup info string: %s", ErrFileParse, len(fields), cgroupSummaryStr) } CgroupSummary := &CgroupSummary{ diff --git a/vendor/github.com/prometheus/procfs/proc_environ.go b/vendor/github.com/prometheus/procfs/proc_environ.go index 57a89895d66a..5b941de04779 100644 --- a/vendor/github.com/prometheus/procfs/proc_environ.go +++ b/vendor/github.com/prometheus/procfs/proc_environ.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_fdinfo.go b/vendor/github.com/prometheus/procfs/proc_fdinfo.go index fa761b35295e..fa57761dbe36 100644 --- a/vendor/github.com/prometheus/procfs/proc_fdinfo.go +++ b/vendor/github.com/prometheus/procfs/proc_fdinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -60,15 +60,16 @@ func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { scanner := bufio.NewScanner(bytes.NewReader(data)) for scanner.Scan() { text = scanner.Text() - if rPos.MatchString(text) { + switch { + case rPos.MatchString(text): pos = rPos.FindStringSubmatch(text)[1] - } else if rFlags.MatchString(text) { + case rFlags.MatchString(text): flags = rFlags.FindStringSubmatch(text)[1] - } else if rMntID.MatchString(text) { + case rMntID.MatchString(text): mntid = rMntID.FindStringSubmatch(text)[1] - } else if rIno.MatchString(text) { + case rIno.MatchString(text): ino = rIno.FindStringSubmatch(text)[1] - } else if rInotify.MatchString(text) { + case rInotify.MatchString(text): newInotify, err := parseInotifyInfo(text) if err != nil { return nil, err diff --git a/vendor/github.com/prometheus/procfs/proc_interrupts.go b/vendor/github.com/prometheus/procfs/proc_interrupts.go index 86b4b4524632..b942c50723ca 100644 --- a/vendor/github.com/prometheus/procfs/proc_interrupts.go +++ b/vendor/github.com/prometheus/procfs/proc_interrupts.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_io.go b/vendor/github.com/prometheus/procfs/proc_io.go index d15b66ddb64a..dd8086ba2e7c 100644 --- a/vendor/github.com/prometheus/procfs/proc_io.go +++ b/vendor/github.com/prometheus/procfs/proc_io.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_limits.go b/vendor/github.com/prometheus/procfs/proc_limits.go index 9530b14bc681..4b7d33784712 100644 --- a/vendor/github.com/prometheus/procfs/proc_limits.go +++ b/vendor/github.com/prometheus/procfs/proc_limits.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -19,6 +19,7 @@ import ( "os" "regexp" "strconv" + "strings" ) // ProcLimits represents the soft limits for each of the process's resource @@ -74,7 +75,7 @@ const ( ) var ( - limitsMatch = regexp.MustCompile(`(Max \w+\s{0,1}?\w*\s{0,1}\w*)\s{2,}(\w+)\s+(\w+)`) + limitsMatch = regexp.MustCompile(`(Max \w+\s??\w*\s?\w*)\s{2,}(\w+)\s+(\w+)`) ) // NewLimits returns the current soft limits of the process. @@ -106,7 +107,7 @@ func (p Proc) Limits() (ProcLimits, error) { return ProcLimits{}, fmt.Errorf("%w: couldn't parse %q line %q", ErrFileParse, f.Name(), s.Text()) } - switch fields[1] { + switch strings.TrimSpace(fields[1]) { case "Max cpu time": l.CPUTime, err = parseUint(fields[2]) case "Max file size": diff --git a/vendor/github.com/prometheus/procfs/proc_maps.go b/vendor/github.com/prometheus/procfs/proc_maps.go index 7e75c286b5b4..cc519f92f9af 100644 --- a/vendor/github.com/prometheus/procfs/proc_maps.go +++ b/vendor/github.com/prometheus/procfs/proc_maps.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_netstat.go b/vendor/github.com/prometheus/procfs/proc_netstat.go index 4248c1716ee9..7f94cc89145b 100644 --- a/vendor/github.com/prometheus/procfs/proc_netstat.go +++ b/vendor/github.com/prometheus/procfs/proc_netstat.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_ns.go b/vendor/github.com/prometheus/procfs/proc_ns.go index 0f8f847f954b..5fc0eb9e2f9f 100644 --- a/vendor/github.com/prometheus/procfs/proc_ns.go +++ b/vendor/github.com/prometheus/procfs/proc_ns.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_psi.go b/vendor/github.com/prometheus/procfs/proc_psi.go index ccd35f153a05..cc2c5de873e0 100644 --- a/vendor/github.com/prometheus/procfs/proc_psi.go +++ b/vendor/github.com/prometheus/procfs/proc_psi.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_smaps.go b/vendor/github.com/prometheus/procfs/proc_smaps.go index 9a297afcf89e..3e48afd1d39c 100644 --- a/vendor/github.com/prometheus/procfs/proc_smaps.go +++ b/vendor/github.com/prometheus/procfs/proc_smaps.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_snmp.go b/vendor/github.com/prometheus/procfs/proc_snmp.go index 4bdc90b07eae..8d9a9bcd67aa 100644 --- a/vendor/github.com/prometheus/procfs/proc_snmp.go +++ b/vendor/github.com/prometheus/procfs/proc_snmp.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_snmp6.go b/vendor/github.com/prometheus/procfs/proc_snmp6.go index fb7fd3995bef..841fef464925 100644 --- a/vendor/github.com/prometheus/procfs/proc_snmp6.go +++ b/vendor/github.com/prometheus/procfs/proc_snmp6.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/proc_stat.go b/vendor/github.com/prometheus/procfs/proc_stat.go index 06a8d931c983..02e3f9e316af 100644 --- a/vendor/github.com/prometheus/procfs/proc_stat.go +++ b/vendor/github.com/prometheus/procfs/proc_stat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -101,6 +101,12 @@ type ProcStat struct { RSS int // Soft limit in bytes on the rss of the process. RSSLimit uint64 + // The address above which program text can run. + StartCode uint64 + // The address below which program text can run. + EndCode uint64 + // The address of the start (i.e., bottom) of the stack. + StartStack uint64 // CPU number last executed on. Processor uint // Real-time scheduling priority, a number in the range 1 to 99 for processes @@ -177,9 +183,9 @@ func (p Proc) Stat() (ProcStat, error) { &s.VSize, &s.RSS, &s.RSSLimit, - &ignoreUint64, - &ignoreUint64, - &ignoreUint64, + &s.StartCode, + &s.EndCode, + &s.StartStack, &ignoreUint64, &ignoreUint64, &ignoreUint64, diff --git a/vendor/github.com/prometheus/procfs/proc_statm.go b/vendor/github.com/prometheus/procfs/proc_statm.go new file mode 100644 index 000000000000..b0a936016774 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/proc_statm.go @@ -0,0 +1,116 @@ +// Copyright 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 procfs + +import ( + "os" + "strconv" + "strings" + + "github.com/prometheus/procfs/internal/util" +) + +// - https://man7.org/linux/man-pages/man5/proc_pid_statm.5.html + +// ProcStatm Provides memory usage information for a process, measured in memory pages. +// Read from /proc/[pid]/statm. +type ProcStatm struct { + // The process ID. + PID int + // total program size (same as VmSize in status) + Size uint64 + // resident set size (same as VmRSS in status) + Resident uint64 + // number of resident shared pages (i.e., backed by a file) + Shared uint64 + // text (code) + Text uint64 + // library (unused since Linux 2.6; always 0) + Lib uint64 + // data + stack + Data uint64 + // dirty pages (unused since Linux 2.6; always 0) + Dt uint64 +} + +// NewStatm returns the current status information of the process. +// Deprecated: Use p.Statm() instead. +func (p Proc) NewStatm() (ProcStatm, error) { + return p.Statm() +} + +// Statm returns the current memory usage information of the process. +func (p Proc) Statm() (ProcStatm, error) { + data, err := util.ReadFileNoStat(p.path("statm")) + if err != nil { + return ProcStatm{}, err + } + + statmSlice, err := parseStatm(data) + if err != nil { + return ProcStatm{}, err + } + + procStatm := ProcStatm{ + PID: p.PID, + Size: statmSlice[0], + Resident: statmSlice[1], + Shared: statmSlice[2], + Text: statmSlice[3], + Lib: statmSlice[4], + Data: statmSlice[5], + Dt: statmSlice[6], + } + + return procStatm, nil +} + +// parseStatm return /proc/[pid]/statm data to uint64 slice. +func parseStatm(data []byte) ([]uint64, error) { + var statmSlice []uint64 + statmItems := strings.Fields(string(data)) + for i := range statmItems { + statmItem, err := strconv.ParseUint(statmItems[i], 10, 64) + if err != nil { + return nil, err + } + statmSlice = append(statmSlice, statmItem) + } + return statmSlice, nil +} + +// SizeBytes returns the process of total program size in bytes. +func (s ProcStatm) SizeBytes() uint64 { + return s.Size * uint64(os.Getpagesize()) +} + +// ResidentBytes returns the process of resident set size in bytes. +func (s ProcStatm) ResidentBytes() uint64 { + return s.Resident * uint64(os.Getpagesize()) +} + +// SHRBytes returns the process of share memory size in bytes. +func (s ProcStatm) SHRBytes() uint64 { + return s.Shared * uint64(os.Getpagesize()) +} + +// TextBytes returns the process of text (code) size in bytes. +func (s ProcStatm) TextBytes() uint64 { + return s.Text * uint64(os.Getpagesize()) +} + +// DataBytes returns the process of data + stack size in bytes. +func (s ProcStatm) DataBytes() uint64 { + return s.Data * uint64(os.Getpagesize()) +} diff --git a/vendor/github.com/prometheus/procfs/proc_status.go b/vendor/github.com/prometheus/procfs/proc_status.go index dd8aa56885ec..1ed2bced4174 100644 --- a/vendor/github.com/prometheus/procfs/proc_status.go +++ b/vendor/github.com/prometheus/procfs/proc_status.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -16,7 +16,7 @@ package procfs import ( "bytes" "math/bits" - "sort" + "slices" "strconv" "strings" @@ -94,8 +94,7 @@ func (p Proc) NewStatus() (ProcStatus, error) { s := ProcStatus{PID: p.PID} - lines := strings.Split(string(data), "\n") - for _, line := range lines { + for line := range strings.SplitSeq(string(data), "\n") { if !bytes.Contains([]byte(line), []byte(":")) { continue } @@ -222,7 +221,7 @@ func calcCpusAllowedList(cpuString string) []uint64 { } - sort.Slice(g, func(i, j int) bool { return g[i] < g[j] }) + slices.Sort(g) return g } diff --git a/vendor/github.com/prometheus/procfs/proc_sys.go b/vendor/github.com/prometheus/procfs/proc_sys.go index 3810d1ac999f..52658a4d52d4 100644 --- a/vendor/github.com/prometheus/procfs/proc_sys.go +++ b/vendor/github.com/prometheus/procfs/proc_sys.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/schedstat.go b/vendor/github.com/prometheus/procfs/schedstat.go index 5f7f32dc83c6..fafd8dff740b 100644 --- a/vendor/github.com/prometheus/procfs/schedstat.go +++ b/vendor/github.com/prometheus/procfs/schedstat.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/slab.go b/vendor/github.com/prometheus/procfs/slab.go index 8611c901770a..32a04678ad0b 100644 --- a/vendor/github.com/prometheus/procfs/slab.go +++ b/vendor/github.com/prometheus/procfs/slab.go @@ -1,4 +1,4 @@ -// Copyright 2020 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/softirqs.go b/vendor/github.com/prometheus/procfs/softirqs.go index 403e6ae70868..47b73a7297b3 100644 --- a/vendor/github.com/prometheus/procfs/softirqs.go +++ b/vendor/github.com/prometheus/procfs/softirqs.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go index e36b41c18a90..593ad0f62f05 100644 --- a/vendor/github.com/prometheus/procfs/stat.go +++ b/vendor/github.com/prometheus/procfs/stat.go @@ -1,4 +1,4 @@ -// Copyright 2018 The Prometheus Authors +// Copyright 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 @@ -16,6 +16,7 @@ package procfs import ( "bufio" "bytes" + "errors" "fmt" "io" "strconv" @@ -92,7 +93,7 @@ func parseCPUStat(line string) (CPUStat, int64, error) { &cpuStat.Iowait, &cpuStat.IRQ, &cpuStat.SoftIRQ, &cpuStat.Steal, &cpuStat.Guest, &cpuStat.GuestNice) - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return CPUStat{}, -1, fmt.Errorf("%w: couldn't parse %q (cpu): %w", ErrFileParse, line, err) } if count == 0 { diff --git a/vendor/github.com/prometheus/procfs/swaps.go b/vendor/github.com/prometheus/procfs/swaps.go index 65fec834bf41..ee17bf4888cd 100644 --- a/vendor/github.com/prometheus/procfs/swaps.go +++ b/vendor/github.com/prometheus/procfs/swaps.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/thread.go b/vendor/github.com/prometheus/procfs/thread.go index 80e0e947be78..0cfbb5418445 100644 --- a/vendor/github.com/prometheus/procfs/thread.go +++ b/vendor/github.com/prometheus/procfs/thread.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/vm.go b/vendor/github.com/prometheus/procfs/vm.go index 51c49d89e81b..2a8d76390973 100644 --- a/vendor/github.com/prometheus/procfs/vm.go +++ b/vendor/github.com/prometheus/procfs/vm.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 diff --git a/vendor/github.com/prometheus/procfs/zoneinfo.go b/vendor/github.com/prometheus/procfs/zoneinfo.go index e54d94b09039..806e171147d0 100644 --- a/vendor/github.com/prometheus/procfs/zoneinfo.go +++ b/vendor/github.com/prometheus/procfs/zoneinfo.go @@ -1,4 +1,4 @@ -// Copyright 2019 The Prometheus Authors +// Copyright 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 @@ -88,11 +88,9 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) { zoneinfo := []Zoneinfo{} - zoneinfoBlocks := bytes.Split(zoneinfoData, []byte("\nNode")) - for _, block := range zoneinfoBlocks { + for block := range bytes.SplitSeq(zoneinfoData, []byte("\nNode")) { var zoneinfoElement Zoneinfo - lines := strings.Split(string(block), "\n") - for _, line := range lines { + for line := range strings.SplitSeq(string(block), "\n") { if nodeZone := nodeZoneRE.FindStringSubmatch(line); nodeZone != nil { zoneinfoElement.Node = nodeZone[1] diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go index 159297ef0a49..8702d6d39e09 100644 --- a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go @@ -1521,7 +1521,13 @@ func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(_ DecodeContext, vr return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} } - if vr.Type() == bsontype.Null { + // If BSON value is null and the go value is a pointer, then don't call + // UnmarshalBSONValue. Even if the Go pointer is already initialized (i.e., + // non-nil), encountering null in BSON will result in the pointer being + // directly set to nil here. Since the pointer is being replaced with nil, + // there is no opportunity (or reason) for the custom UnmarshalBSONValue logic + // to be called. + if vr.Type() == bsontype.Null && val.Kind() == reflect.Ptr { val.Set(reflect.Zero(val.Type())) return vr.ReadNull() diff --git a/vendor/go.mongodb.org/mongo-driver/bson/unmarshal.go b/vendor/go.mongodb.org/mongo-driver/bson/unmarshal.go index 66da17ee0172..d749ba373b59 100644 --- a/vendor/go.mongodb.org/mongo-driver/bson/unmarshal.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/unmarshal.go @@ -41,6 +41,9 @@ type ValueUnmarshaler interface { // Unmarshal parses the BSON-encoded data and stores the result in the value // pointed to by val. If val is nil or not a pointer, Unmarshal returns // InvalidUnmarshalError. +// +// When unmarshaling BSON, if the BSON value is null and the Go value is a +// pointer, the pointer is set to nil without calling UnmarshalBSONValue. func Unmarshal(data []byte, val interface{}) error { return UnmarshalWithRegistry(DefaultRegistry, data, val) } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/LICENSE b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/LICENSE index 261eeb9e9f8b..f1aee0f11001 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/LICENSE +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/LICENSE @@ -199,3 +199,33 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +-------------------------------------------------------------------------------- + +Copyright 2009 The Go Authors. + +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 LLC 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. \ No newline at end of file diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/exporter.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/exporter.go index 3f0a518ae0f2..30446bd28b64 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/exporter.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/exporter.go @@ -94,7 +94,7 @@ func NewUnstarted(client Client) *Exporter { } // MarshalLog is the marshaling function used by the logging system to represent this Exporter. -func (e *Exporter) MarshalLog() interface{} { +func (e *Exporter) MarshalLog() any { return struct { Type string Client Client diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/attribute.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/attribute.go index ca4544f0dae7..d9bfd6e1765b 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/attribute.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/attribute.go @@ -6,9 +6,10 @@ package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform" import ( + commonpb "go.opentelemetry.io/proto/otlp/common/v1" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/sdk/resource" - commonpb "go.opentelemetry.io/proto/otlp/common/v1" ) // KeyValues transforms a slice of attribute KeyValues into OTLP key-values. diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go index 2e7690e43a24..43359c894496 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go @@ -4,8 +4,9 @@ package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform" import ( - "go.opentelemetry.io/otel/sdk/instrumentation" commonpb "go.opentelemetry.io/proto/otlp/common/v1" + + "go.opentelemetry.io/otel/sdk/instrumentation" ) func InstrumentationScope(il instrumentation.Scope) *commonpb.InstrumentationScope { diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/resource.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/resource.go index db7b698a566c..526bb5e070b5 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/resource.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/resource.go @@ -4,8 +4,9 @@ package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform" import ( - "go.opentelemetry.io/otel/sdk/resource" resourcepb "go.opentelemetry.io/proto/otlp/resource/v1" + + "go.opentelemetry.io/otel/sdk/resource" ) // Resource transforms a Resource into an OTLP Resource. diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go index bf27ef0220e7..d431fc4517d9 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go @@ -6,12 +6,13 @@ package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptr import ( "math" + tracepb "go.opentelemetry.io/proto/otlp/trace/v1" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/sdk/instrumentation" tracesdk "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/trace" - tracepb "go.opentelemetry.io/proto/otlp/trace/v1" ) // Spans transforms a slice of OpenTelemetry spans into a slice of OTLP @@ -112,7 +113,7 @@ func span(sd tracesdk.ReadOnlySpan) *tracepb.Span { if psid := sd.Parent().SpanID(); psid.IsValid() { s.ParentSpanId = psid[:] } - s.Flags = buildSpanFlags(sd.Parent()) + s.Flags = buildSpanFlagsWith(sd.SpanContext().TraceFlags(), sd.Parent()) return s } @@ -154,12 +155,11 @@ func links(links []tracesdk.Link) []*tracepb.Span_Link { for _, otLink := range links { // This redefinition is necessary to prevent otLink.*ID[:] copies // being reused -- in short we need a new otLink per iteration. - otLink := otLink tid := otLink.SpanContext.TraceID() sid := otLink.SpanContext.SpanID() - flags := buildSpanFlags(otLink.SpanContext) + flags := buildSpanFlagsWith(otLink.SpanContext.TraceFlags(), otLink.SpanContext) sl = append(sl, &tracepb.Span_Link{ TraceId: tid[:], @@ -172,13 +172,15 @@ func links(links []tracesdk.Link) []*tracepb.Span_Link { return sl } -func buildSpanFlags(sc trace.SpanContext) uint32 { - flags := tracepb.SpanFlags_SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK - if sc.IsRemote() { - flags |= tracepb.SpanFlags_SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK +func buildSpanFlagsWith(tf trace.TraceFlags, parent trace.SpanContext) uint32 { + // Lower 8 bits are the W3C TraceFlags; always indicate that we know whether the parent is remote + flags := uint32(tf) | uint32(tracepb.SpanFlags_SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK) + // Set the parent-is-remote bit when applicable + if parent.IsRemote() { + flags |= uint32(tracepb.SpanFlags_SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK) } - return uint32(flags) // nolint:gosec // Flags is a bitmask and can't be negative + return flags // nolint:gosec // Flags is a bitmask and can't be negative } // spanEvents transforms span Events to an OTLP span events. @@ -189,7 +191,7 @@ func spanEvents(es []tracesdk.Event) []*tracepb.Span_Event { events := make([]*tracepb.Span_Event, len(es)) // Transform message events - for i := 0; i < len(es); i++ { + for i := range es { events[i] = &tracepb.Span_Event{ Name: es[i].Name, TimeUnixNano: uint64(max(0, es[i].Time.UnixNano())), // nolint:gosec // Overflow checked. diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/LICENSE b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/LICENSE index 261eeb9e9f8b..f1aee0f11001 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/LICENSE +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/LICENSE @@ -199,3 +199,33 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +-------------------------------------------------------------------------------- + +Copyright 2009 The Go Authors. + +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 LLC 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. \ No newline at end of file diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go index 8236c995a9c6..76b7cd461bf9 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go @@ -9,19 +9,20 @@ import ( "sync" "time" + coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1" + tracepb "go.opentelemetry.io/proto/otlp/trace/v1" "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/counter" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry" - coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1" - tracepb "go.opentelemetry.io/proto/otlp/trace/v1" ) type client struct { @@ -45,6 +46,9 @@ type client struct { conn *grpc.ClientConn tscMu sync.RWMutex tsc coltracepb.TraceServiceClient + + instID int64 + inst *observ.Instrumentation } // Compile time check *client implements otlptrace.Client. @@ -68,6 +72,7 @@ func newClient(opts ...Option) *client { stopCtx: ctx, stopFunc: cancel, conn: cfg.GRPCConn, + instID: counter.NextExporterID(), } if len(cfg.Traces.Headers) > 0 { @@ -92,13 +97,24 @@ func (c *client) Start(context.Context) error { c.conn = conn } + // Initialize the instrumentation if not already done. + // + // Initialize here instead of NewClient to allow any errors to be passed + // back to the caller and so that any setup of the environment variables to + // enable instrumentation can be set via code. + var err error + if c.inst == nil { + target := c.conn.CanonicalTarget() + c.inst, err = observ.NewInstrumentation(c.instID, target) + } + // The otlptrace.Client interface states this method is called just once, // so no need to check if already started. c.tscMu.Lock() c.tsc = coltracepb.NewTraceServiceClient(c.conn) c.tscMu.Unlock() - return nil + return err } var errAlreadyStopped = errors.New("the client is already stopped") @@ -174,7 +190,7 @@ var errShutdown = errors.New("the client is shutdown") // // Retryable errors from the server will be handled according to any // RetryConfig the client was created with. -func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.ResourceSpans) error { +func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.ResourceSpans) (uploadErr error) { // Hold a read lock to ensure a shut down initiated after this starts does // not abandon the export. This read lock acquire has less priority than a // write lock acquire (i.e. Stop), meaning if the client is shutting down @@ -189,6 +205,12 @@ func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc ctx, cancel := c.exportContext(ctx) defer cancel() + var code codes.Code + if c.inst != nil { + op := c.inst.ExportSpans(ctx, len(protoSpans)) + defer func() { op.End(uploadErr, code) }() + } + return c.requestFunc(ctx, func(iCtx context.Context) error { resp, err := c.tsc.Export(iCtx, &coltracepb.ExportTraceServiceRequest{ ResourceSpans: protoSpans, @@ -197,16 +219,17 @@ func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc msg := resp.PartialSuccess.GetErrorMessage() n := resp.PartialSuccess.GetRejectedSpans() if n != 0 || msg != "" { - err := internal.TracePartialSuccessError(n, msg) - otel.Handle(err) + e := internal.TracePartialSuccessError(n, msg) + uploadErr = errors.Join(uploadErr, e) } } // nil is converted to OK. - if status.Code(err) == codes.OK { + code = status.Code(err) + if code == codes.OK { // Success. - return nil + return uploadErr } - return err + return errors.Join(uploadErr, err) }) } @@ -289,7 +312,7 @@ func throttleDelay(s *status.Status) (bool, time.Duration) { } // MarshalLog is the marshaling function used by the logging system to represent this Client. -func (c *client) MarshalLog() interface{} { +func (c *client) MarshalLog() any { return struct { Type string Endpoint string diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/counter/counter.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/counter/counter.go new file mode 100644 index 000000000000..323b2a2c9a6f --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/counter/counter.go @@ -0,0 +1,31 @@ +// Code generated by gotmpl. DO NOT MODIFY. +// source: internal/shared/counter/counter.go.tmpl + +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package counter provides a simple counter for generating unique IDs. +// +// This package is used to generate unique IDs while allowing testing packages +// to reset the counter. +package counter // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/counter" + +import "sync/atomic" + +// exporterN is a global 0-based count of the number of exporters created. +var exporterN atomic.Int64 + +// NextExporterID returns the next unique ID for an exporter. +func NextExporterID() int64 { + const inc = 1 + return exporterN.Add(inc) - inc +} + +// SetExporterID sets the exporter ID counter to v and returns the previous +// value. +// +// This function is useful for testing purposes, allowing you to reset the +// counter. It should not be used in production code. +func SetExporterID(v int64) int64 { + return exporterN.Swap(v) +} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/gen.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/gen.go index b6e6b10fbf15..7fe9c9f3a335 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/gen.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/gen.go @@ -23,3 +23,12 @@ package internal // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/ot //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlptracetest/collector.go.tmpl "--data={}" --out=otlptracetest/collector.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlptracetest/data.go.tmpl "--data={}" --out=otlptracetest/data.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlptracetest/otlptest.go.tmpl "--data={}" --out=otlptracetest/otlptest.go + +//go:generate gotmpl --body=../../../../../internal/shared/x/x.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc\" }" --out=x/x.go +//go:generate gotmpl --body=../../../../../internal/shared/x/x_test.go.tmpl "--data={}" --out=x/x_test.go + +//go:generate gotmpl --body=../../../../../internal/shared/otlp/observ/target.go.tmpl "--data={ \"pkg\": \"observ\", \"pkg_path\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ\" }" --out=observ/target.go +//go:generate gotmpl --body=../../../../../internal/shared/otlp/observ/target_test.go.tmpl "--data={ \"pkg\": \"observ\" }" --out=observ/target_test.go + +//go:generate gotmpl --body=../../../../../internal/shared/counter/counter.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/counter\" }" --out=counter/counter.go +//go:generate gotmpl --body=../../../../../internal/shared/counter/counter_test.go.tmpl "--data={}" --out=counter/counter_test.go diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/doc.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/doc.go new file mode 100644 index 000000000000..0dd54e4b9690 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/doc.go @@ -0,0 +1,6 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package observ provides experimental observability instrumentation for the +// otlptracegrpc exporter. +package observ // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ" diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/instrumentation.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/instrumentation.go new file mode 100644 index 000000000000..2257fcc865fd --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/instrumentation.go @@ -0,0 +1,341 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package observ // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ" + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "google.golang.org/grpc/codes" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x" + "go.opentelemetry.io/otel/internal/global" + "go.opentelemetry.io/otel/metric" + semconv "go.opentelemetry.io/otel/semconv/v1.37.0" + "go.opentelemetry.io/otel/semconv/v1.37.0/otelconv" +) + +const ( + // ScopeName is the unique name of the meter used for instrumentation. + ScopeName = "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ" + + // SchemaURL is the schema URL of the metrics produced by this + // instrumentation. + SchemaURL = semconv.SchemaURL + + // Version is the current version of this instrumentation. + // + // This matches the version of the exporter. + Version = internal.Version +) + +var ( + measureAttrsPool = &sync.Pool{ + New: func() any { + const n = 1 + // component.name + 1 + // component.type + 1 + // server.addr + 1 + // server.port + 1 + // error.type + 1 // rpc.grpc.status_code + s := make([]attribute.KeyValue, 0, n) + // Return a pointer to a slice instead of a slice itself + // to avoid allocations on every call. + return &s + }, + } + + addOptPool = &sync.Pool{ + New: func() any { + const n = 1 // WithAttributeSet + o := make([]metric.AddOption, 0, n) + return &o + }, + } + + recordOptPool = &sync.Pool{ + New: func() any { + const n = 1 // WithAttributeSet + o := make([]metric.RecordOption, 0, n) + return &o + }, + } +) + +func get[T any](p *sync.Pool) *[]T { return p.Get().(*[]T) } + +func put[T any](p *sync.Pool, s *[]T) { + *s = (*s)[:0] // Reset. + p.Put(s) +} + +// ComponentName returns the component name for the exporter with the +// provided ID. +func ComponentName(id int64) string { + t := semconv.OTelComponentTypeOtlpGRPCSpanExporter.Value.AsString() + return fmt.Sprintf("%s/%d", t, id) +} + +// Instrumentation is experimental instrumentation for the exporter. +type Instrumentation struct { + inflightSpans metric.Int64UpDownCounter + exportedSpans metric.Int64Counter + opDuration metric.Float64Histogram + + attrs []attribute.KeyValue + addOpt metric.AddOption + recOpt metric.RecordOption +} + +// NewInstrumentation returns instrumentation for an OTLP over gPRC trace +// exporter with the provided ID using the global MeterProvider. +// +// The id should be the unique exporter instance ID. It is used +// to set the "component.name" attribute. +// +// The target is the endpoint the exporter is exporting to. +// +// If the experimental observability is disabled, nil is returned. +func NewInstrumentation(id int64, target string) (*Instrumentation, error) { + if !x.Observability.Enabled() { + return nil, nil + } + + attrs := BaseAttrs(id, target) + i := &Instrumentation{ + attrs: attrs, + addOpt: metric.WithAttributeSet(attribute.NewSet(attrs...)), + + // Do not modify attrs (NewSet sorts in-place), make a new slice. + recOpt: metric.WithAttributeSet(attribute.NewSet(append( + // Default to OK status code. + []attribute.KeyValue{semconv.RPCGRPCStatusCodeOk}, + attrs..., + )...)), + } + + mp := otel.GetMeterProvider() + m := mp.Meter( + ScopeName, + metric.WithInstrumentationVersion(Version), + metric.WithSchemaURL(SchemaURL), + ) + + var err error + + inflightSpans, e := otelconv.NewSDKExporterSpanInflight(m) + if e != nil { + e = fmt.Errorf("failed to create span inflight metric: %w", e) + err = errors.Join(err, e) + } + i.inflightSpans = inflightSpans.Inst() + + exportedSpans, e := otelconv.NewSDKExporterSpanExported(m) + if e != nil { + e = fmt.Errorf("failed to create span exported metric: %w", e) + err = errors.Join(err, e) + } + i.exportedSpans = exportedSpans.Inst() + + opDuration, e := otelconv.NewSDKExporterOperationDuration(m) + if e != nil { + e = fmt.Errorf("failed to create operation duration metric: %w", e) + err = errors.Join(err, e) + } + i.opDuration = opDuration.Inst() + + return i, err +} + +// BaseAttrs returns the base attributes for the exporter with the provided ID +// and target. +// +// The id should be the unique exporter instance ID. It is used +// to set the "component.name" attribute. +// +// The target is the gRPC target the exporter is exporting to. It is expected +// to be the output of the Client's CanonicalTarget method. +func BaseAttrs(id int64, target string) []attribute.KeyValue { + host, port, err := ParseCanonicalTarget(target) + if err != nil || (host == "" && port < 0) { + if err != nil { + global.Debug("failed to parse target", "target", target, "error", err) + } + return []attribute.KeyValue{ + semconv.OTelComponentName(ComponentName(id)), + semconv.OTelComponentTypeOtlpGRPCSpanExporter, + } + } + + // Do not use append so the slice is exactly allocated. + + if port < 0 { + return []attribute.KeyValue{ + semconv.OTelComponentName(ComponentName(id)), + semconv.OTelComponentTypeOtlpGRPCSpanExporter, + semconv.ServerAddress(host), + } + } + + if host == "" { + return []attribute.KeyValue{ + semconv.OTelComponentName(ComponentName(id)), + semconv.OTelComponentTypeOtlpGRPCSpanExporter, + semconv.ServerPort(port), + } + } + + return []attribute.KeyValue{ + semconv.OTelComponentName(ComponentName(id)), + semconv.OTelComponentTypeOtlpGRPCSpanExporter, + semconv.ServerAddress(host), + semconv.ServerPort(port), + } +} + +// ExportSpans instruments the ExportSpans method of the exporter. It returns +// an [ExportOp] that must have its [ExportOp.End] method called when the +// ExportSpans method returns. +func (i *Instrumentation) ExportSpans(ctx context.Context, nSpans int) ExportOp { + start := time.Now() + + addOpt := get[metric.AddOption](addOptPool) + defer put(addOptPool, addOpt) + *addOpt = append(*addOpt, i.addOpt) + i.inflightSpans.Add(ctx, int64(nSpans), *addOpt...) + + return ExportOp{ + ctx: ctx, + start: start, + nSpans: int64(nSpans), + inst: i, + } +} + +// ExportOp tracks the operation being observed by [Instrumentation.ExportSpans]. +type ExportOp struct { + ctx context.Context + start time.Time + nSpans int64 + + inst *Instrumentation +} + +// End completes the observation of the operation being observed by a call to +// [Instrumentation.ExportSpans]. +// +// Any error that is encountered is provided as err. +// +// If err is not nil, all spans will be recorded as failures unless error is of +// type [internal.PartialSuccess]. In the case of a PartialSuccess, the number +// of successfully exported spans will be determined by inspecting the +// RejectedItems field of the PartialSuccess. +func (e ExportOp) End(err error, code codes.Code) { + addOpt := get[metric.AddOption](addOptPool) + defer put(addOptPool, addOpt) + *addOpt = append(*addOpt, e.inst.addOpt) + + e.inst.inflightSpans.Add(e.ctx, -e.nSpans, *addOpt...) + + success := successful(e.nSpans, err) + // Record successfully exported spans, even if the value is 0 which are + // meaningful to distribution aggregations. + e.inst.exportedSpans.Add(e.ctx, success, *addOpt...) + + if err != nil { + attrs := get[attribute.KeyValue](measureAttrsPool) + defer put(measureAttrsPool, attrs) + *attrs = append(*attrs, e.inst.attrs...) + *attrs = append(*attrs, semconv.ErrorType(err)) + + // Do not inefficiently make a copy of attrs by using + // WithAttributes instead of WithAttributeSet. + o := metric.WithAttributeSet(attribute.NewSet(*attrs...)) + // Reset addOpt with new attribute set. + *addOpt = append((*addOpt)[:0], o) + + e.inst.exportedSpans.Add(e.ctx, e.nSpans-success, *addOpt...) + } + + recOpt := get[metric.RecordOption](recordOptPool) + defer put(recordOptPool, recOpt) + *recOpt = append(*recOpt, e.inst.recordOption(err, code)) + + d := time.Since(e.start).Seconds() + e.inst.opDuration.Record(e.ctx, d, *recOpt...) +} + +// recordOption returns a RecordOption with attributes representing the +// outcome of the operation being recorded. +// +// If err is nil and code is codes.OK, the default recOpt of the +// Instrumentation is returned. +// +// If err is not nil or code is not codes.OK, a new RecordOption is returned +// with the base attributes of the Instrumentation plus the rpc.grpc.status_code +// attribute set to the provided code, and if err is not nil, the error.type +// attribute set to the type of the error. +func (i *Instrumentation) recordOption(err error, code codes.Code) metric.RecordOption { + if err == nil && code == codes.OK { + return i.recOpt + } + + attrs := get[attribute.KeyValue](measureAttrsPool) + defer put(measureAttrsPool, attrs) + *attrs = append(*attrs, i.attrs...) + + c := int64(code) // uint32 -> int64. + *attrs = append(*attrs, semconv.RPCGRPCStatusCodeKey.Int64(c)) + if err != nil { + *attrs = append(*attrs, semconv.ErrorType(err)) + } + + // Do not inefficiently make a copy of attrs by using WithAttributes + // instead of WithAttributeSet. + return metric.WithAttributeSet(attribute.NewSet(*attrs...)) +} + +// successful returns the number of successfully exported spans out of the n +// that were exported based on the provided error. +// +// If err is nil, n is returned. All spans were successfully exported. +// +// If err is not nil and not an [internal.PartialSuccess] error, 0 is returned. +// It is assumed all spans failed to be exported. +// +// If err is an [internal.PartialSuccess] error, the number of successfully +// exported spans is computed by subtracting the RejectedItems field from n. If +// RejectedItems is negative, n is returned. If RejectedItems is greater than +// n, 0 is returned. +func successful(n int64, err error) int64 { + if err == nil { + return n // All spans successfully exported. + } + // Split rejection calculation so successful is inlinable. + return n - rejected(n, err) +} + +var errPartialPool = &sync.Pool{ + New: func() any { return new(internal.PartialSuccess) }, +} + +// rejected returns how many out of the n spans exporter were rejected based on +// the provided non-nil err. +func rejected(n int64, err error) int64 { + ps := errPartialPool.Get().(*internal.PartialSuccess) + defer errPartialPool.Put(ps) + // Check for partial success. + if errors.As(err, ps) { + // Bound RejectedItems to [0, n]. This should not be needed, + // but be defensive as this is from an external source. + return min(max(ps.RejectedItems, 0), n) + } + return n // All spans rejected. +} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/target.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/target.go new file mode 100644 index 000000000000..34eee27db0dc --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/target.go @@ -0,0 +1,143 @@ +// Code generated by gotmpl. DO NOT MODIFY. +// source: internal/shared/otlp/observ/target.go.tmpl + +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package observ // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ" + +import ( + "errors" + "fmt" + "net" + "net/netip" + "strconv" + "strings" +) + +const ( + schemeUnix = "unix" + schemeUnixAbstract = "unix-abstract" +) + +// ParseCanonicalTarget parses a target string and returns the extracted host +// (domain address or IP), the target port, or an error. +// +// If no port is specified, -1 is returned. +// +// If no host is specified, an empty string is returned. +// +// The target string is expected to always have the form +// "://[authority]/". For example: +// - "dns:///example.com:42" +// - "dns://8.8.8.8/example.com:42" +// - "unix:///path/to/socket" +// - "unix-abstract:///socket-name" +// - "passthrough:///192.34.2.1:42" +// +// The target is expected to come from the CanonicalTarget method of a gRPC +// Client. +func ParseCanonicalTarget(target string) (string, int, error) { + const sep = "://" + + // Find scheme. Do not allocate the string by using url.Parse. + idx := strings.Index(target, sep) + if idx == -1 { + return "", -1, fmt.Errorf("invalid target %q: missing scheme", target) + } + scheme, endpoint := target[:idx], target[idx+len(sep):] + + // Check for unix schemes. + if scheme == schemeUnix || scheme == schemeUnixAbstract { + return parseUnix(endpoint) + } + + // Strip leading slash and any authority. + if i := strings.Index(endpoint, "/"); i != -1 { + endpoint = endpoint[i+1:] + } + + // DNS, passthrough, and custom resolvers. + return parseEndpoint(endpoint) +} + +// parseUnix parses unix socket targets. +func parseUnix(endpoint string) (string, int, error) { + // Format: unix[-abstract]://path + // + // We should have "/path" (empty authority) if valid. + if len(endpoint) >= 1 && endpoint[0] == '/' { + // Return the full path including leading slash. + return endpoint, -1, nil + } + + // If there's no leading slash, it means there might be an authority + // Check for authority case (should error): "authority/path" + if slashIdx := strings.Index(endpoint, "/"); slashIdx > 0 { + return "", -1, fmt.Errorf("invalid (non-empty) authority: %s", endpoint[:slashIdx]) + } + + return "", -1, errors.New("invalid unix target format") +} + +// parseEndpoint parses an endpoint from a gRPC target. +// +// It supports the following formats: +// - "host" +// - "host%zone" +// - "host:port" +// - "host%zone:port" +// - "ipv4" +// - "ipv4%zone" +// - "ipv4:port" +// - "ipv4%zone:port" +// - "ipv6" +// - "ipv6%zone" +// - "[ipv6]" +// - "[ipv6%zone]" +// - "[ipv6]:port" +// - "[ipv6%zone]:port" +// +// It returns the host or host%zone (domain address or IP), the port (or -1 if +// not specified), or an error if the input is not a valid. +func parseEndpoint(endpoint string) (string, int, error) { + // First check if the endpoint is just an IP address. + if ip := parseIP(endpoint); ip != "" { + return ip, -1, nil + } + + // If there's no colon, there is no port (IPv6 with no port checked above). + if !strings.Contains(endpoint, ":") { + return endpoint, -1, nil + } + + host, portStr, err := net.SplitHostPort(endpoint) + if err != nil { + return "", -1, fmt.Errorf("invalid host:port %q: %w", endpoint, err) + } + + const base, bitSize = 10, 16 + port16, err := strconv.ParseUint(portStr, base, bitSize) + if err != nil { + return "", -1, fmt.Errorf("invalid port %q: %w", portStr, err) + } + port := int(port16) // port is guaranteed to be in the range [0, 65535]. + + return host, port, nil +} + +// parseIP attempts to parse the entire endpoint as an IP address. +// It returns the normalized string form of the IP if successful, +// or an empty string if parsing fails. +func parseIP(ip string) string { + // Strip leading and trailing brackets for IPv6 addresses. + if len(ip) >= 2 && ip[0] == '[' && ip[len(ip)-1] == ']' { + ip = ip[1 : len(ip)-1] + } + addr, err := netip.ParseAddr(ip) + if err != nil { + return "" + } + // Return the normalized string form of the IP. + return addr.String() +} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/partialsuccess.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/partialsuccess.go index 1c4659423361..a811a07b3529 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/partialsuccess.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/partialsuccess.go @@ -29,6 +29,17 @@ func (ps PartialSuccess) Error() string { return fmt.Sprintf("OTLP partial success: %s (%d %s rejected)", msg, ps.RejectedItems, ps.RejectedKind) } +// As returns true if ps can be assigned to target and makes the assignment. +// Otherwise, it returns false. This supports the errors.As() interface. +func (ps PartialSuccess) As(target any) bool { + t, ok := target.(*PartialSuccess) + if !ok { + return false + } + *t = ps + return true +} + // Is supports the errors.Is() interface. func (ps PartialSuccess) Is(err error) bool { _, ok := err.(PartialSuccess) diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go index 259a898ae771..a7b8e81a7868 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go @@ -94,6 +94,11 @@ func (c Config) RequestFunc(evaluate EvaluateFunc) RequestFunc { return err } + // Check if context is canceled before attempting to wait and retry. + if ctx.Err() != nil { + return fmt.Errorf("%w: %w", ctx.Err(), err) + } + if maxElapsedTime != 0 && time.Since(startTime) > maxElapsedTime { return fmt.Errorf("max retry time elapsed: %w", err) } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/version.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/version.go new file mode 100644 index 000000000000..e2d7cee1e17e --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/version.go @@ -0,0 +1,8 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package internal // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal" + +// Version is the current release version of the OpenTelemetry OTLP gRPC trace +// exporter in use. +const Version = "1.39.0" diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/README.md b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/README.md new file mode 100644 index 000000000000..15a3011bff31 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/README.md @@ -0,0 +1,36 @@ +# Experimental Features + +The `otlptracegrpc` exporter contains features that have not yet stabilized in the OpenTelemetry specification. +These features are added to the `otlptracegrpc` exporter prior to stabilization in the specification so that users can start experimenting with them and provide feedback. + +These feature may change in backwards incompatible ways as feedback is applied. +See the [Compatibility and Stability](#compatibility-and-stability) section for more information. + +## Features + +- [Observability](#observability) + +### Observability + +The `otlptracegrpc` exporter provides a observability feature that allows you to monitor the SDK itself. + +To opt-in, set the environment variable `OTEL_GO_X_OBSERVABILITY` to `true`. + +When enabled, the SDK will create the following metrics using the global `MeterProvider`: + +- `otel.sdk.exporter.span.inflight` +- `otel.sdk.exporter.span.exported` +- `otel.sdk.exporter.operation.duration` + +Please see the [Semantic conventions for OpenTelemetry SDK metrics] documentation for more details on these metrics. + +[Semantic conventions for OpenTelemetry SDK metrics]: https://github.com/open-telemetry/semantic-conventions/blob/v1.37.0/docs/otel/sdk-metrics.md + +## Compatibility and Stability + +Experimental features do not fall within the scope of the OpenTelemetry Go versioning and stability [policy](../../../../../../VERSIONING.md). +These features may be removed or modified in successive version releases, including patch versions. + +When an experimental feature is promoted to a stable feature, a migration path will be included in the changelog entry of the release. +There is no guarantee that any environment variable feature flags that enabled the experimental feature will be supported by the stable version. +If they are supported, they may be accompanied with a deprecation notice stating a timeline for the removal of that support. diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/observ.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/observ.go new file mode 100644 index 000000000000..4e89c6524f0b --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/observ.go @@ -0,0 +1,22 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package x // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x" + +import "strings" + +// Observability is an experimental feature flag that determines if exporter +// observability metrics are enabled. +// +// To enable this feature set the OTEL_GO_X_OBSERVABILITY environment variable +// to the case-insensitive string value of "true" (i.e. "True" and "TRUE" +// will also enable this). +var Observability = newFeature( + []string{"OBSERVABILITY"}, + func(v string) (string, bool) { + if strings.EqualFold(v, "true") { + return v, true + } + return "", false + }, +) diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/x.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/x.go new file mode 100644 index 000000000000..741ba62c97f7 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x/x.go @@ -0,0 +1,58 @@ +// Code generated by gotmpl. DO NOT MODIFY. +// source: internal/shared/x/x.go.tmpl + +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package x documents experimental features for [go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc]. +package x // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x" + +import ( + "os" +) + +// Feature is an experimental feature control flag. It provides a uniform way +// to interact with these feature flags and parse their values. +type Feature[T any] struct { + keys []string + parse func(v string) (T, bool) +} + +func newFeature[T any](suffix []string, parse func(string) (T, bool)) Feature[T] { + const envKeyRoot = "OTEL_GO_X_" + keys := make([]string, 0, len(suffix)) + for _, s := range suffix { + keys = append(keys, envKeyRoot+s) + } + return Feature[T]{ + keys: keys, + parse: parse, + } +} + +// Keys returns the environment variable keys that can be set to enable the +// feature. +func (f Feature[T]) Keys() []string { return f.keys } + +// Lookup returns the user configured value for the feature and true if the +// user has enabled the feature. Otherwise, if the feature is not enabled, a +// zero-value and false are returned. +func (f Feature[T]) Lookup() (v T, ok bool) { + // https://github.com/open-telemetry/opentelemetry-specification/blob/62effed618589a0bec416a87e559c0a9d96289bb/specification/configuration/sdk-environment-variables.md#parsing-empty-value + // + // > The SDK MUST interpret an empty value of an environment variable the + // > same way as when the variable is unset. + for _, key := range f.keys { + vRaw := os.Getenv(key) + if vRaw != "" { + return f.parse(vRaw) + } + } + return v, ok +} + +// Enabled reports whether the feature is enabled. +func (f Feature[T]) Enabled() bool { + _, ok := f.Lookup() + return ok +} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go index ed2ddce718bf..6838f3c4e3fa 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go @@ -5,5 +5,5 @@ package otlptrace // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace" // Version is the current release version of the OpenTelemetry OTLP trace exporter in use. func Version() string { - return "1.37.0" + return "1.39.0" } diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/otelconv/metric.go b/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/otelconv/metric.go new file mode 100644 index 000000000000..fd064530c34c --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/otelconv/metric.go @@ -0,0 +1,2264 @@ +// Code generated from semantic convention specification. DO NOT EDIT. + +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package otelconv provides types and functionality for OpenTelemetry semantic +// conventions in the "otel" namespace. +package otelconv + +import ( + "context" + "sync" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/noop" +) + +var ( + addOptPool = &sync.Pool{New: func() any { return &[]metric.AddOption{} }} + recOptPool = &sync.Pool{New: func() any { return &[]metric.RecordOption{} }} +) + +// ErrorTypeAttr is an attribute conforming to the error.type semantic +// conventions. It represents the describes a class of error the operation ended +// with. +type ErrorTypeAttr string + +var ( + // ErrorTypeOther is a fallback error value to be used when the instrumentation + // doesn't define a custom value. + ErrorTypeOther ErrorTypeAttr = "_OTHER" +) + +// ComponentTypeAttr is an attribute conforming to the otel.component.type +// semantic conventions. It represents a name identifying the type of the +// OpenTelemetry component. +type ComponentTypeAttr string + +var ( + // ComponentTypeBatchingSpanProcessor is the builtin SDK batching span + // processor. + ComponentTypeBatchingSpanProcessor ComponentTypeAttr = "batching_span_processor" + // ComponentTypeSimpleSpanProcessor is the builtin SDK simple span processor. + ComponentTypeSimpleSpanProcessor ComponentTypeAttr = "simple_span_processor" + // ComponentTypeBatchingLogProcessor is the builtin SDK batching log record + // processor. + ComponentTypeBatchingLogProcessor ComponentTypeAttr = "batching_log_processor" + // ComponentTypeSimpleLogProcessor is the builtin SDK simple log record + // processor. + ComponentTypeSimpleLogProcessor ComponentTypeAttr = "simple_log_processor" + // ComponentTypeOtlpGRPCSpanExporter is the OTLP span exporter over gRPC with + // protobuf serialization. + ComponentTypeOtlpGRPCSpanExporter ComponentTypeAttr = "otlp_grpc_span_exporter" + // ComponentTypeOtlpHTTPSpanExporter is the OTLP span exporter over HTTP with + // protobuf serialization. + ComponentTypeOtlpHTTPSpanExporter ComponentTypeAttr = "otlp_http_span_exporter" + // ComponentTypeOtlpHTTPJSONSpanExporter is the OTLP span exporter over HTTP + // with JSON serialization. + ComponentTypeOtlpHTTPJSONSpanExporter ComponentTypeAttr = "otlp_http_json_span_exporter" + // ComponentTypeZipkinHTTPSpanExporter is the zipkin span exporter over HTTP. + ComponentTypeZipkinHTTPSpanExporter ComponentTypeAttr = "zipkin_http_span_exporter" + // ComponentTypeOtlpGRPCLogExporter is the OTLP log record exporter over gRPC + // with protobuf serialization. + ComponentTypeOtlpGRPCLogExporter ComponentTypeAttr = "otlp_grpc_log_exporter" + // ComponentTypeOtlpHTTPLogExporter is the OTLP log record exporter over HTTP + // with protobuf serialization. + ComponentTypeOtlpHTTPLogExporter ComponentTypeAttr = "otlp_http_log_exporter" + // ComponentTypeOtlpHTTPJSONLogExporter is the OTLP log record exporter over + // HTTP with JSON serialization. + ComponentTypeOtlpHTTPJSONLogExporter ComponentTypeAttr = "otlp_http_json_log_exporter" + // ComponentTypePeriodicMetricReader is the builtin SDK periodically exporting + // metric reader. + ComponentTypePeriodicMetricReader ComponentTypeAttr = "periodic_metric_reader" + // ComponentTypeOtlpGRPCMetricExporter is the OTLP metric exporter over gRPC + // with protobuf serialization. + ComponentTypeOtlpGRPCMetricExporter ComponentTypeAttr = "otlp_grpc_metric_exporter" + // ComponentTypeOtlpHTTPMetricExporter is the OTLP metric exporter over HTTP + // with protobuf serialization. + ComponentTypeOtlpHTTPMetricExporter ComponentTypeAttr = "otlp_http_metric_exporter" + // ComponentTypeOtlpHTTPJSONMetricExporter is the OTLP metric exporter over HTTP + // with JSON serialization. + ComponentTypeOtlpHTTPJSONMetricExporter ComponentTypeAttr = "otlp_http_json_metric_exporter" + // ComponentTypePrometheusHTTPTextMetricExporter is the prometheus metric + // exporter over HTTP with the default text-based format. + ComponentTypePrometheusHTTPTextMetricExporter ComponentTypeAttr = "prometheus_http_text_metric_exporter" +) + +// SpanParentOriginAttr is an attribute conforming to the otel.span.parent.origin +// semantic conventions. It represents the determines whether the span has a +// parent span, and if so, [whether it is a remote parent]. +// +// [whether it is a remote parent]: https://opentelemetry.io/docs/specs/otel/trace/api/#isremote +type SpanParentOriginAttr string + +var ( + // SpanParentOriginNone is the span does not have a parent, it is a root span. + SpanParentOriginNone SpanParentOriginAttr = "none" + // SpanParentOriginLocal is the span has a parent and the parent's span context + // [isRemote()] is false. + // + // [isRemote()]: https://opentelemetry.io/docs/specs/otel/trace/api/#isremote + SpanParentOriginLocal SpanParentOriginAttr = "local" + // SpanParentOriginRemote is the span has a parent and the parent's span context + // [isRemote()] is true. + // + // [isRemote()]: https://opentelemetry.io/docs/specs/otel/trace/api/#isremote + SpanParentOriginRemote SpanParentOriginAttr = "remote" +) + +// SpanSamplingResultAttr is an attribute conforming to the +// otel.span.sampling_result semantic conventions. It represents the result value +// of the sampler for this span. +type SpanSamplingResultAttr string + +var ( + // SpanSamplingResultDrop is the span is not sampled and not recording. + SpanSamplingResultDrop SpanSamplingResultAttr = "DROP" + // SpanSamplingResultRecordOnly is the span is not sampled, but recording. + SpanSamplingResultRecordOnly SpanSamplingResultAttr = "RECORD_ONLY" + // SpanSamplingResultRecordAndSample is the span is sampled and recording. + SpanSamplingResultRecordAndSample SpanSamplingResultAttr = "RECORD_AND_SAMPLE" +) + +// RPCGRPCStatusCodeAttr is an attribute conforming to the rpc.grpc.status_code +// semantic conventions. It represents the gRPC status code of the last gRPC +// requests performed in scope of this export call. +type RPCGRPCStatusCodeAttr int64 + +var ( + // RPCGRPCStatusCodeOk is the OK. + RPCGRPCStatusCodeOk RPCGRPCStatusCodeAttr = 0 + // RPCGRPCStatusCodeCancelled is the CANCELLED. + RPCGRPCStatusCodeCancelled RPCGRPCStatusCodeAttr = 1 + // RPCGRPCStatusCodeUnknown is the UNKNOWN. + RPCGRPCStatusCodeUnknown RPCGRPCStatusCodeAttr = 2 + // RPCGRPCStatusCodeInvalidArgument is the INVALID_ARGUMENT. + RPCGRPCStatusCodeInvalidArgument RPCGRPCStatusCodeAttr = 3 + // RPCGRPCStatusCodeDeadlineExceeded is the DEADLINE_EXCEEDED. + RPCGRPCStatusCodeDeadlineExceeded RPCGRPCStatusCodeAttr = 4 + // RPCGRPCStatusCodeNotFound is the NOT_FOUND. + RPCGRPCStatusCodeNotFound RPCGRPCStatusCodeAttr = 5 + // RPCGRPCStatusCodeAlreadyExists is the ALREADY_EXISTS. + RPCGRPCStatusCodeAlreadyExists RPCGRPCStatusCodeAttr = 6 + // RPCGRPCStatusCodePermissionDenied is the PERMISSION_DENIED. + RPCGRPCStatusCodePermissionDenied RPCGRPCStatusCodeAttr = 7 + // RPCGRPCStatusCodeResourceExhausted is the RESOURCE_EXHAUSTED. + RPCGRPCStatusCodeResourceExhausted RPCGRPCStatusCodeAttr = 8 + // RPCGRPCStatusCodeFailedPrecondition is the FAILED_PRECONDITION. + RPCGRPCStatusCodeFailedPrecondition RPCGRPCStatusCodeAttr = 9 + // RPCGRPCStatusCodeAborted is the ABORTED. + RPCGRPCStatusCodeAborted RPCGRPCStatusCodeAttr = 10 + // RPCGRPCStatusCodeOutOfRange is the OUT_OF_RANGE. + RPCGRPCStatusCodeOutOfRange RPCGRPCStatusCodeAttr = 11 + // RPCGRPCStatusCodeUnimplemented is the UNIMPLEMENTED. + RPCGRPCStatusCodeUnimplemented RPCGRPCStatusCodeAttr = 12 + // RPCGRPCStatusCodeInternal is the INTERNAL. + RPCGRPCStatusCodeInternal RPCGRPCStatusCodeAttr = 13 + // RPCGRPCStatusCodeUnavailable is the UNAVAILABLE. + RPCGRPCStatusCodeUnavailable RPCGRPCStatusCodeAttr = 14 + // RPCGRPCStatusCodeDataLoss is the DATA_LOSS. + RPCGRPCStatusCodeDataLoss RPCGRPCStatusCodeAttr = 15 + // RPCGRPCStatusCodeUnauthenticated is the UNAUTHENTICATED. + RPCGRPCStatusCodeUnauthenticated RPCGRPCStatusCodeAttr = 16 +) + +// SDKExporterLogExported is an instrument used to record metric values +// conforming to the "otel.sdk.exporter.log.exported" semantic conventions. It +// represents the number of log records for which the export has finished, either +// successful or failed. +type SDKExporterLogExported struct { + metric.Int64Counter +} + +var newSDKExporterLogExportedOpts = []metric.Int64CounterOption{ + metric.WithDescription("The number of log records for which the export has finished, either successful or failed."), + metric.WithUnit("{log_record}"), +} + +// NewSDKExporterLogExported returns a new SDKExporterLogExported instrument. +func NewSDKExporterLogExported( + m metric.Meter, + opt ...metric.Int64CounterOption, +) (SDKExporterLogExported, error) { + // Check if the meter is nil. + if m == nil { + return SDKExporterLogExported{noop.Int64Counter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKExporterLogExportedOpts + } else { + opt = append(opt, newSDKExporterLogExportedOpts...) + } + + i, err := m.Int64Counter( + "otel.sdk.exporter.log.exported", + opt..., + ) + if err != nil { + return SDKExporterLogExported{noop.Int64Counter{}}, err + } + return SDKExporterLogExported{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKExporterLogExported) Inst() metric.Int64Counter { + return m.Int64Counter +} + +// Name returns the semantic convention name of the instrument. +func (SDKExporterLogExported) Name() string { + return "otel.sdk.exporter.log.exported" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKExporterLogExported) Unit() string { + return "{log_record}" +} + +// Description returns the semantic convention description of the instrument +func (SDKExporterLogExported) Description() string { + return "The number of log records for which the export has finished, either successful or failed." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +// For exporters with partial success semantics (e.g. OTLP with +// `rejected_log_records`), rejected log records MUST count as failed and only +// non-rejected log records count as success. +// If no rejection reason is available, `rejected` SHOULD be used as value for +// `error.type`. +func (m SDKExporterLogExported) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +// For exporters with partial success semantics (e.g. OTLP with +// `rejected_log_records`), rejected log records MUST count as failed and only +// non-rejected log records count as success. +// If no rejection reason is available, `rejected` SHOULD be used as value for +// `error.type`. +func (m SDKExporterLogExported) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (SDKExporterLogExported) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKExporterLogExported) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKExporterLogExported) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the server domain name if available without +// reverse DNS lookup; otherwise, IP address or Unix domain socket name. +func (SDKExporterLogExported) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the server port number. +func (SDKExporterLogExported) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// SDKExporterLogInflight is an instrument used to record metric values +// conforming to the "otel.sdk.exporter.log.inflight" semantic conventions. It +// represents the number of log records which were passed to the exporter, but +// that have not been exported yet (neither successful, nor failed). +type SDKExporterLogInflight struct { + metric.Int64UpDownCounter +} + +var newSDKExporterLogInflightOpts = []metric.Int64UpDownCounterOption{ + metric.WithDescription("The number of log records which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)."), + metric.WithUnit("{log_record}"), +} + +// NewSDKExporterLogInflight returns a new SDKExporterLogInflight instrument. +func NewSDKExporterLogInflight( + m metric.Meter, + opt ...metric.Int64UpDownCounterOption, +) (SDKExporterLogInflight, error) { + // Check if the meter is nil. + if m == nil { + return SDKExporterLogInflight{noop.Int64UpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKExporterLogInflightOpts + } else { + opt = append(opt, newSDKExporterLogInflightOpts...) + } + + i, err := m.Int64UpDownCounter( + "otel.sdk.exporter.log.inflight", + opt..., + ) + if err != nil { + return SDKExporterLogInflight{noop.Int64UpDownCounter{}}, err + } + return SDKExporterLogInflight{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKExporterLogInflight) Inst() metric.Int64UpDownCounter { + return m.Int64UpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (SDKExporterLogInflight) Name() string { + return "otel.sdk.exporter.log.inflight" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKExporterLogInflight) Unit() string { + return "{log_record}" +} + +// Description returns the semantic convention description of the instrument +func (SDKExporterLogInflight) Description() string { + return "The number of log records which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +func (m SDKExporterLogInflight) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +func (m SDKExporterLogInflight) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKExporterLogInflight) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKExporterLogInflight) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the server domain name if available without +// reverse DNS lookup; otherwise, IP address or Unix domain socket name. +func (SDKExporterLogInflight) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the server port number. +func (SDKExporterLogInflight) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// SDKExporterMetricDataPointExported is an instrument used to record metric +// values conforming to the "otel.sdk.exporter.metric_data_point.exported" +// semantic conventions. It represents the number of metric data points for which +// the export has finished, either successful or failed. +type SDKExporterMetricDataPointExported struct { + metric.Int64Counter +} + +var newSDKExporterMetricDataPointExportedOpts = []metric.Int64CounterOption{ + metric.WithDescription("The number of metric data points for which the export has finished, either successful or failed."), + metric.WithUnit("{data_point}"), +} + +// NewSDKExporterMetricDataPointExported returns a new +// SDKExporterMetricDataPointExported instrument. +func NewSDKExporterMetricDataPointExported( + m metric.Meter, + opt ...metric.Int64CounterOption, +) (SDKExporterMetricDataPointExported, error) { + // Check if the meter is nil. + if m == nil { + return SDKExporterMetricDataPointExported{noop.Int64Counter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKExporterMetricDataPointExportedOpts + } else { + opt = append(opt, newSDKExporterMetricDataPointExportedOpts...) + } + + i, err := m.Int64Counter( + "otel.sdk.exporter.metric_data_point.exported", + opt..., + ) + if err != nil { + return SDKExporterMetricDataPointExported{noop.Int64Counter{}}, err + } + return SDKExporterMetricDataPointExported{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKExporterMetricDataPointExported) Inst() metric.Int64Counter { + return m.Int64Counter +} + +// Name returns the semantic convention name of the instrument. +func (SDKExporterMetricDataPointExported) Name() string { + return "otel.sdk.exporter.metric_data_point.exported" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKExporterMetricDataPointExported) Unit() string { + return "{data_point}" +} + +// Description returns the semantic convention description of the instrument +func (SDKExporterMetricDataPointExported) Description() string { + return "The number of metric data points for which the export has finished, either successful or failed." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +// For exporters with partial success semantics (e.g. OTLP with +// `rejected_data_points`), rejected data points MUST count as failed and only +// non-rejected data points count as success. +// If no rejection reason is available, `rejected` SHOULD be used as value for +// `error.type`. +func (m SDKExporterMetricDataPointExported) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +// For exporters with partial success semantics (e.g. OTLP with +// `rejected_data_points`), rejected data points MUST count as failed and only +// non-rejected data points count as success. +// If no rejection reason is available, `rejected` SHOULD be used as value for +// `error.type`. +func (m SDKExporterMetricDataPointExported) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (SDKExporterMetricDataPointExported) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKExporterMetricDataPointExported) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKExporterMetricDataPointExported) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the server domain name if available without +// reverse DNS lookup; otherwise, IP address or Unix domain socket name. +func (SDKExporterMetricDataPointExported) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the server port number. +func (SDKExporterMetricDataPointExported) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// SDKExporterMetricDataPointInflight is an instrument used to record metric +// values conforming to the "otel.sdk.exporter.metric_data_point.inflight" +// semantic conventions. It represents the number of metric data points which +// were passed to the exporter, but that have not been exported yet (neither +// successful, nor failed). +type SDKExporterMetricDataPointInflight struct { + metric.Int64UpDownCounter +} + +var newSDKExporterMetricDataPointInflightOpts = []metric.Int64UpDownCounterOption{ + metric.WithDescription("The number of metric data points which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)."), + metric.WithUnit("{data_point}"), +} + +// NewSDKExporterMetricDataPointInflight returns a new +// SDKExporterMetricDataPointInflight instrument. +func NewSDKExporterMetricDataPointInflight( + m metric.Meter, + opt ...metric.Int64UpDownCounterOption, +) (SDKExporterMetricDataPointInflight, error) { + // Check if the meter is nil. + if m == nil { + return SDKExporterMetricDataPointInflight{noop.Int64UpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKExporterMetricDataPointInflightOpts + } else { + opt = append(opt, newSDKExporterMetricDataPointInflightOpts...) + } + + i, err := m.Int64UpDownCounter( + "otel.sdk.exporter.metric_data_point.inflight", + opt..., + ) + if err != nil { + return SDKExporterMetricDataPointInflight{noop.Int64UpDownCounter{}}, err + } + return SDKExporterMetricDataPointInflight{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKExporterMetricDataPointInflight) Inst() metric.Int64UpDownCounter { + return m.Int64UpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (SDKExporterMetricDataPointInflight) Name() string { + return "otel.sdk.exporter.metric_data_point.inflight" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKExporterMetricDataPointInflight) Unit() string { + return "{data_point}" +} + +// Description returns the semantic convention description of the instrument +func (SDKExporterMetricDataPointInflight) Description() string { + return "The number of metric data points which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +func (m SDKExporterMetricDataPointInflight) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +func (m SDKExporterMetricDataPointInflight) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKExporterMetricDataPointInflight) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKExporterMetricDataPointInflight) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the server domain name if available without +// reverse DNS lookup; otherwise, IP address or Unix domain socket name. +func (SDKExporterMetricDataPointInflight) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the server port number. +func (SDKExporterMetricDataPointInflight) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// SDKExporterOperationDuration is an instrument used to record metric values +// conforming to the "otel.sdk.exporter.operation.duration" semantic conventions. +// It represents the duration of exporting a batch of telemetry records. +type SDKExporterOperationDuration struct { + metric.Float64Histogram +} + +var newSDKExporterOperationDurationOpts = []metric.Float64HistogramOption{ + metric.WithDescription("The duration of exporting a batch of telemetry records."), + metric.WithUnit("s"), +} + +// NewSDKExporterOperationDuration returns a new SDKExporterOperationDuration +// instrument. +func NewSDKExporterOperationDuration( + m metric.Meter, + opt ...metric.Float64HistogramOption, +) (SDKExporterOperationDuration, error) { + // Check if the meter is nil. + if m == nil { + return SDKExporterOperationDuration{noop.Float64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newSDKExporterOperationDurationOpts + } else { + opt = append(opt, newSDKExporterOperationDurationOpts...) + } + + i, err := m.Float64Histogram( + "otel.sdk.exporter.operation.duration", + opt..., + ) + if err != nil { + return SDKExporterOperationDuration{noop.Float64Histogram{}}, err + } + return SDKExporterOperationDuration{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKExporterOperationDuration) Inst() metric.Float64Histogram { + return m.Float64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (SDKExporterOperationDuration) Name() string { + return "otel.sdk.exporter.operation.duration" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKExporterOperationDuration) Unit() string { + return "s" +} + +// Description returns the semantic convention description of the instrument +func (SDKExporterOperationDuration) Description() string { + return "The duration of exporting a batch of telemetry records." +} + +// Record records val to the current distribution for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// This metric defines successful operations using the full success definitions +// for [http] +// and [grpc]. Anything else is defined as an unsuccessful operation. For +// successful +// operations, `error.type` MUST NOT be set. For unsuccessful export operations, +// `error.type` MUST contain a relevant failure cause. +// +// [http]: https://github.com/open-telemetry/opentelemetry-proto/blob/v1.5.0/docs/specification.md#full-success-1 +// [grpc]: https://github.com/open-telemetry/opentelemetry-proto/blob/v1.5.0/docs/specification.md#full-success +func (m SDKExporterOperationDuration) Record( + ctx context.Context, + val float64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Float64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +// +// This metric defines successful operations using the full success definitions +// for [http] +// and [grpc]. Anything else is defined as an unsuccessful operation. For +// successful +// operations, `error.type` MUST NOT be set. For unsuccessful export operations, +// `error.type` MUST contain a relevant failure cause. +// +// [http]: https://github.com/open-telemetry/opentelemetry-proto/blob/v1.5.0/docs/specification.md#full-success-1 +// [grpc]: https://github.com/open-telemetry/opentelemetry-proto/blob/v1.5.0/docs/specification.md#full-success +func (m SDKExporterOperationDuration) RecordSet(ctx context.Context, val float64, set attribute.Set) { + if set.Len() == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Float64Histogram.Record(ctx, val, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (SDKExporterOperationDuration) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrHTTPResponseStatusCode returns an optional attribute for the +// "http.response.status_code" semantic convention. It represents the HTTP status +// code of the last HTTP request performed in scope of this export call. +func (SDKExporterOperationDuration) AttrHTTPResponseStatusCode(val int) attribute.KeyValue { + return attribute.Int("http.response.status_code", val) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKExporterOperationDuration) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKExporterOperationDuration) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// AttrRPCGRPCStatusCode returns an optional attribute for the +// "rpc.grpc.status_code" semantic convention. It represents the gRPC status code +// of the last gRPC requests performed in scope of this export call. +func (SDKExporterOperationDuration) AttrRPCGRPCStatusCode(val RPCGRPCStatusCodeAttr) attribute.KeyValue { + return attribute.Int64("rpc.grpc.status_code", int64(val)) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the server domain name if available without +// reverse DNS lookup; otherwise, IP address or Unix domain socket name. +func (SDKExporterOperationDuration) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the server port number. +func (SDKExporterOperationDuration) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// SDKExporterSpanExported is an instrument used to record metric values +// conforming to the "otel.sdk.exporter.span.exported" semantic conventions. It +// represents the number of spans for which the export has finished, either +// successful or failed. +type SDKExporterSpanExported struct { + metric.Int64Counter +} + +var newSDKExporterSpanExportedOpts = []metric.Int64CounterOption{ + metric.WithDescription("The number of spans for which the export has finished, either successful or failed."), + metric.WithUnit("{span}"), +} + +// NewSDKExporterSpanExported returns a new SDKExporterSpanExported instrument. +func NewSDKExporterSpanExported( + m metric.Meter, + opt ...metric.Int64CounterOption, +) (SDKExporterSpanExported, error) { + // Check if the meter is nil. + if m == nil { + return SDKExporterSpanExported{noop.Int64Counter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKExporterSpanExportedOpts + } else { + opt = append(opt, newSDKExporterSpanExportedOpts...) + } + + i, err := m.Int64Counter( + "otel.sdk.exporter.span.exported", + opt..., + ) + if err != nil { + return SDKExporterSpanExported{noop.Int64Counter{}}, err + } + return SDKExporterSpanExported{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKExporterSpanExported) Inst() metric.Int64Counter { + return m.Int64Counter +} + +// Name returns the semantic convention name of the instrument. +func (SDKExporterSpanExported) Name() string { + return "otel.sdk.exporter.span.exported" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKExporterSpanExported) Unit() string { + return "{span}" +} + +// Description returns the semantic convention description of the instrument +func (SDKExporterSpanExported) Description() string { + return "The number of spans for which the export has finished, either successful or failed." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +// For exporters with partial success semantics (e.g. OTLP with `rejected_spans` +// ), rejected spans MUST count as failed and only non-rejected spans count as +// success. +// If no rejection reason is available, `rejected` SHOULD be used as value for +// `error.type`. +func (m SDKExporterSpanExported) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +// For exporters with partial success semantics (e.g. OTLP with `rejected_spans` +// ), rejected spans MUST count as failed and only non-rejected spans count as +// success. +// If no rejection reason is available, `rejected` SHOULD be used as value for +// `error.type`. +func (m SDKExporterSpanExported) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (SDKExporterSpanExported) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKExporterSpanExported) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKExporterSpanExported) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the server domain name if available without +// reverse DNS lookup; otherwise, IP address or Unix domain socket name. +func (SDKExporterSpanExported) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the server port number. +func (SDKExporterSpanExported) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// SDKExporterSpanInflight is an instrument used to record metric values +// conforming to the "otel.sdk.exporter.span.inflight" semantic conventions. It +// represents the number of spans which were passed to the exporter, but that +// have not been exported yet (neither successful, nor failed). +type SDKExporterSpanInflight struct { + metric.Int64UpDownCounter +} + +var newSDKExporterSpanInflightOpts = []metric.Int64UpDownCounterOption{ + metric.WithDescription("The number of spans which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)."), + metric.WithUnit("{span}"), +} + +// NewSDKExporterSpanInflight returns a new SDKExporterSpanInflight instrument. +func NewSDKExporterSpanInflight( + m metric.Meter, + opt ...metric.Int64UpDownCounterOption, +) (SDKExporterSpanInflight, error) { + // Check if the meter is nil. + if m == nil { + return SDKExporterSpanInflight{noop.Int64UpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKExporterSpanInflightOpts + } else { + opt = append(opt, newSDKExporterSpanInflightOpts...) + } + + i, err := m.Int64UpDownCounter( + "otel.sdk.exporter.span.inflight", + opt..., + ) + if err != nil { + return SDKExporterSpanInflight{noop.Int64UpDownCounter{}}, err + } + return SDKExporterSpanInflight{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKExporterSpanInflight) Inst() metric.Int64UpDownCounter { + return m.Int64UpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (SDKExporterSpanInflight) Name() string { + return "otel.sdk.exporter.span.inflight" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKExporterSpanInflight) Unit() string { + return "{span}" +} + +// Description returns the semantic convention description of the instrument +func (SDKExporterSpanInflight) Description() string { + return "The number of spans which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +func (m SDKExporterSpanInflight) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// For successful exports, `error.type` MUST NOT be set. For failed exports, +// `error.type` MUST contain the failure cause. +func (m SDKExporterSpanInflight) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKExporterSpanInflight) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKExporterSpanInflight) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// AttrServerAddress returns an optional attribute for the "server.address" +// semantic convention. It represents the server domain name if available without +// reverse DNS lookup; otherwise, IP address or Unix domain socket name. +func (SDKExporterSpanInflight) AttrServerAddress(val string) attribute.KeyValue { + return attribute.String("server.address", val) +} + +// AttrServerPort returns an optional attribute for the "server.port" semantic +// convention. It represents the server port number. +func (SDKExporterSpanInflight) AttrServerPort(val int) attribute.KeyValue { + return attribute.Int("server.port", val) +} + +// SDKLogCreated is an instrument used to record metric values conforming to the +// "otel.sdk.log.created" semantic conventions. It represents the number of logs +// submitted to enabled SDK Loggers. +type SDKLogCreated struct { + metric.Int64Counter +} + +var newSDKLogCreatedOpts = []metric.Int64CounterOption{ + metric.WithDescription("The number of logs submitted to enabled SDK Loggers."), + metric.WithUnit("{log_record}"), +} + +// NewSDKLogCreated returns a new SDKLogCreated instrument. +func NewSDKLogCreated( + m metric.Meter, + opt ...metric.Int64CounterOption, +) (SDKLogCreated, error) { + // Check if the meter is nil. + if m == nil { + return SDKLogCreated{noop.Int64Counter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKLogCreatedOpts + } else { + opt = append(opt, newSDKLogCreatedOpts...) + } + + i, err := m.Int64Counter( + "otel.sdk.log.created", + opt..., + ) + if err != nil { + return SDKLogCreated{noop.Int64Counter{}}, err + } + return SDKLogCreated{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKLogCreated) Inst() metric.Int64Counter { + return m.Int64Counter +} + +// Name returns the semantic convention name of the instrument. +func (SDKLogCreated) Name() string { + return "otel.sdk.log.created" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKLogCreated) Unit() string { + return "{log_record}" +} + +// Description returns the semantic convention description of the instrument +func (SDKLogCreated) Description() string { + return "The number of logs submitted to enabled SDK Loggers." +} + +// Add adds incr to the existing count for attrs. +func (m SDKLogCreated) Add(ctx context.Context, incr int64, attrs ...attribute.KeyValue) { + if len(attrs) == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributes(attrs...)) + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +func (m SDKLogCreated) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Counter.Add(ctx, incr, *o...) +} + +// SDKMetricReaderCollectionDuration is an instrument used to record metric +// values conforming to the "otel.sdk.metric_reader.collection.duration" semantic +// conventions. It represents the duration of the collect operation of the metric +// reader. +type SDKMetricReaderCollectionDuration struct { + metric.Float64Histogram +} + +var newSDKMetricReaderCollectionDurationOpts = []metric.Float64HistogramOption{ + metric.WithDescription("The duration of the collect operation of the metric reader."), + metric.WithUnit("s"), +} + +// NewSDKMetricReaderCollectionDuration returns a new +// SDKMetricReaderCollectionDuration instrument. +func NewSDKMetricReaderCollectionDuration( + m metric.Meter, + opt ...metric.Float64HistogramOption, +) (SDKMetricReaderCollectionDuration, error) { + // Check if the meter is nil. + if m == nil { + return SDKMetricReaderCollectionDuration{noop.Float64Histogram{}}, nil + } + + if len(opt) == 0 { + opt = newSDKMetricReaderCollectionDurationOpts + } else { + opt = append(opt, newSDKMetricReaderCollectionDurationOpts...) + } + + i, err := m.Float64Histogram( + "otel.sdk.metric_reader.collection.duration", + opt..., + ) + if err != nil { + return SDKMetricReaderCollectionDuration{noop.Float64Histogram{}}, err + } + return SDKMetricReaderCollectionDuration{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKMetricReaderCollectionDuration) Inst() metric.Float64Histogram { + return m.Float64Histogram +} + +// Name returns the semantic convention name of the instrument. +func (SDKMetricReaderCollectionDuration) Name() string { + return "otel.sdk.metric_reader.collection.duration" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKMetricReaderCollectionDuration) Unit() string { + return "s" +} + +// Description returns the semantic convention description of the instrument +func (SDKMetricReaderCollectionDuration) Description() string { + return "The duration of the collect operation of the metric reader." +} + +// Record records val to the current distribution for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful collections, `error.type` MUST NOT be set. For failed +// collections, `error.type` SHOULD contain the failure cause. +// It can happen that metrics collection is successful for some MetricProducers, +// while others fail. In that case `error.type` SHOULD be set to any of the +// failure causes. +func (m SDKMetricReaderCollectionDuration) Record( + ctx context.Context, + val float64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Float64Histogram.Record(ctx, val, *o...) +} + +// RecordSet records val to the current distribution for set. +// +// For successful collections, `error.type` MUST NOT be set. For failed +// collections, `error.type` SHOULD contain the failure cause. +// It can happen that metrics collection is successful for some MetricProducers, +// while others fail. In that case `error.type` SHOULD be set to any of the +// failure causes. +func (m SDKMetricReaderCollectionDuration) RecordSet(ctx context.Context, val float64, set attribute.Set) { + if set.Len() == 0 { + m.Float64Histogram.Record(ctx, val) + return + } + + o := recOptPool.Get().(*[]metric.RecordOption) + defer func() { + *o = (*o)[:0] + recOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Float64Histogram.Record(ctx, val, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents the describes a class of error the operation ended +// with. +func (SDKMetricReaderCollectionDuration) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKMetricReaderCollectionDuration) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKMetricReaderCollectionDuration) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// SDKProcessorLogProcessed is an instrument used to record metric values +// conforming to the "otel.sdk.processor.log.processed" semantic conventions. It +// represents the number of log records for which the processing has finished, +// either successful or failed. +type SDKProcessorLogProcessed struct { + metric.Int64Counter +} + +var newSDKProcessorLogProcessedOpts = []metric.Int64CounterOption{ + metric.WithDescription("The number of log records for which the processing has finished, either successful or failed."), + metric.WithUnit("{log_record}"), +} + +// NewSDKProcessorLogProcessed returns a new SDKProcessorLogProcessed instrument. +func NewSDKProcessorLogProcessed( + m metric.Meter, + opt ...metric.Int64CounterOption, +) (SDKProcessorLogProcessed, error) { + // Check if the meter is nil. + if m == nil { + return SDKProcessorLogProcessed{noop.Int64Counter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKProcessorLogProcessedOpts + } else { + opt = append(opt, newSDKProcessorLogProcessedOpts...) + } + + i, err := m.Int64Counter( + "otel.sdk.processor.log.processed", + opt..., + ) + if err != nil { + return SDKProcessorLogProcessed{noop.Int64Counter{}}, err + } + return SDKProcessorLogProcessed{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKProcessorLogProcessed) Inst() metric.Int64Counter { + return m.Int64Counter +} + +// Name returns the semantic convention name of the instrument. +func (SDKProcessorLogProcessed) Name() string { + return "otel.sdk.processor.log.processed" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKProcessorLogProcessed) Unit() string { + return "{log_record}" +} + +// Description returns the semantic convention description of the instrument +func (SDKProcessorLogProcessed) Description() string { + return "The number of log records for which the processing has finished, either successful or failed." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful processing, `error.type` MUST NOT be set. For failed +// processing, `error.type` MUST contain the failure cause. +// For the SDK Simple and Batching Log Record Processor a log record is +// considered to be processed already when it has been submitted to the exporter, +// not when the corresponding export call has finished. +func (m SDKProcessorLogProcessed) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// For successful processing, `error.type` MUST NOT be set. For failed +// processing, `error.type` MUST contain the failure cause. +// For the SDK Simple and Batching Log Record Processor a log record is +// considered to be processed already when it has been submitted to the exporter, +// not when the corresponding export call has finished. +func (m SDKProcessorLogProcessed) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents a low-cardinality description of the failure reason. +// SDK Batching Log Record Processors MUST use `queue_full` for log records +// dropped due to a full queue. +func (SDKProcessorLogProcessed) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKProcessorLogProcessed) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKProcessorLogProcessed) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// SDKProcessorLogQueueCapacity is an instrument used to record metric values +// conforming to the "otel.sdk.processor.log.queue.capacity" semantic +// conventions. It represents the maximum number of log records the queue of a +// given instance of an SDK Log Record processor can hold. +type SDKProcessorLogQueueCapacity struct { + metric.Int64ObservableUpDownCounter +} + +var newSDKProcessorLogQueueCapacityOpts = []metric.Int64ObservableUpDownCounterOption{ + metric.WithDescription("The maximum number of log records the queue of a given instance of an SDK Log Record processor can hold."), + metric.WithUnit("{log_record}"), +} + +// NewSDKProcessorLogQueueCapacity returns a new SDKProcessorLogQueueCapacity +// instrument. +func NewSDKProcessorLogQueueCapacity( + m metric.Meter, + opt ...metric.Int64ObservableUpDownCounterOption, +) (SDKProcessorLogQueueCapacity, error) { + // Check if the meter is nil. + if m == nil { + return SDKProcessorLogQueueCapacity{noop.Int64ObservableUpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKProcessorLogQueueCapacityOpts + } else { + opt = append(opt, newSDKProcessorLogQueueCapacityOpts...) + } + + i, err := m.Int64ObservableUpDownCounter( + "otel.sdk.processor.log.queue.capacity", + opt..., + ) + if err != nil { + return SDKProcessorLogQueueCapacity{noop.Int64ObservableUpDownCounter{}}, err + } + return SDKProcessorLogQueueCapacity{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKProcessorLogQueueCapacity) Inst() metric.Int64ObservableUpDownCounter { + return m.Int64ObservableUpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (SDKProcessorLogQueueCapacity) Name() string { + return "otel.sdk.processor.log.queue.capacity" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKProcessorLogQueueCapacity) Unit() string { + return "{log_record}" +} + +// Description returns the semantic convention description of the instrument +func (SDKProcessorLogQueueCapacity) Description() string { + return "The maximum number of log records the queue of a given instance of an SDK Log Record processor can hold." +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKProcessorLogQueueCapacity) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKProcessorLogQueueCapacity) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// SDKProcessorLogQueueSize is an instrument used to record metric values +// conforming to the "otel.sdk.processor.log.queue.size" semantic conventions. It +// represents the number of log records in the queue of a given instance of an +// SDK log processor. +type SDKProcessorLogQueueSize struct { + metric.Int64ObservableUpDownCounter +} + +var newSDKProcessorLogQueueSizeOpts = []metric.Int64ObservableUpDownCounterOption{ + metric.WithDescription("The number of log records in the queue of a given instance of an SDK log processor."), + metric.WithUnit("{log_record}"), +} + +// NewSDKProcessorLogQueueSize returns a new SDKProcessorLogQueueSize instrument. +func NewSDKProcessorLogQueueSize( + m metric.Meter, + opt ...metric.Int64ObservableUpDownCounterOption, +) (SDKProcessorLogQueueSize, error) { + // Check if the meter is nil. + if m == nil { + return SDKProcessorLogQueueSize{noop.Int64ObservableUpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKProcessorLogQueueSizeOpts + } else { + opt = append(opt, newSDKProcessorLogQueueSizeOpts...) + } + + i, err := m.Int64ObservableUpDownCounter( + "otel.sdk.processor.log.queue.size", + opt..., + ) + if err != nil { + return SDKProcessorLogQueueSize{noop.Int64ObservableUpDownCounter{}}, err + } + return SDKProcessorLogQueueSize{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKProcessorLogQueueSize) Inst() metric.Int64ObservableUpDownCounter { + return m.Int64ObservableUpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (SDKProcessorLogQueueSize) Name() string { + return "otel.sdk.processor.log.queue.size" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKProcessorLogQueueSize) Unit() string { + return "{log_record}" +} + +// Description returns the semantic convention description of the instrument +func (SDKProcessorLogQueueSize) Description() string { + return "The number of log records in the queue of a given instance of an SDK log processor." +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKProcessorLogQueueSize) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKProcessorLogQueueSize) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// SDKProcessorSpanProcessed is an instrument used to record metric values +// conforming to the "otel.sdk.processor.span.processed" semantic conventions. It +// represents the number of spans for which the processing has finished, either +// successful or failed. +type SDKProcessorSpanProcessed struct { + metric.Int64Counter +} + +var newSDKProcessorSpanProcessedOpts = []metric.Int64CounterOption{ + metric.WithDescription("The number of spans for which the processing has finished, either successful or failed."), + metric.WithUnit("{span}"), +} + +// NewSDKProcessorSpanProcessed returns a new SDKProcessorSpanProcessed +// instrument. +func NewSDKProcessorSpanProcessed( + m metric.Meter, + opt ...metric.Int64CounterOption, +) (SDKProcessorSpanProcessed, error) { + // Check if the meter is nil. + if m == nil { + return SDKProcessorSpanProcessed{noop.Int64Counter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKProcessorSpanProcessedOpts + } else { + opt = append(opt, newSDKProcessorSpanProcessedOpts...) + } + + i, err := m.Int64Counter( + "otel.sdk.processor.span.processed", + opt..., + ) + if err != nil { + return SDKProcessorSpanProcessed{noop.Int64Counter{}}, err + } + return SDKProcessorSpanProcessed{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKProcessorSpanProcessed) Inst() metric.Int64Counter { + return m.Int64Counter +} + +// Name returns the semantic convention name of the instrument. +func (SDKProcessorSpanProcessed) Name() string { + return "otel.sdk.processor.span.processed" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKProcessorSpanProcessed) Unit() string { + return "{span}" +} + +// Description returns the semantic convention description of the instrument +func (SDKProcessorSpanProcessed) Description() string { + return "The number of spans for which the processing has finished, either successful or failed." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// For successful processing, `error.type` MUST NOT be set. For failed +// processing, `error.type` MUST contain the failure cause. +// For the SDK Simple and Batching Span Processor a span is considered to be +// processed already when it has been submitted to the exporter, not when the +// corresponding export call has finished. +func (m SDKProcessorSpanProcessed) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// For successful processing, `error.type` MUST NOT be set. For failed +// processing, `error.type` MUST contain the failure cause. +// For the SDK Simple and Batching Span Processor a span is considered to be +// processed already when it has been submitted to the exporter, not when the +// corresponding export call has finished. +func (m SDKProcessorSpanProcessed) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AttrErrorType returns an optional attribute for the "error.type" semantic +// convention. It represents a low-cardinality description of the failure reason. +// SDK Batching Span Processors MUST use `queue_full` for spans dropped due to a +// full queue. +func (SDKProcessorSpanProcessed) AttrErrorType(val ErrorTypeAttr) attribute.KeyValue { + return attribute.String("error.type", string(val)) +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKProcessorSpanProcessed) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKProcessorSpanProcessed) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// SDKProcessorSpanQueueCapacity is an instrument used to record metric values +// conforming to the "otel.sdk.processor.span.queue.capacity" semantic +// conventions. It represents the maximum number of spans the queue of a given +// instance of an SDK span processor can hold. +type SDKProcessorSpanQueueCapacity struct { + metric.Int64ObservableUpDownCounter +} + +var newSDKProcessorSpanQueueCapacityOpts = []metric.Int64ObservableUpDownCounterOption{ + metric.WithDescription("The maximum number of spans the queue of a given instance of an SDK span processor can hold."), + metric.WithUnit("{span}"), +} + +// NewSDKProcessorSpanQueueCapacity returns a new SDKProcessorSpanQueueCapacity +// instrument. +func NewSDKProcessorSpanQueueCapacity( + m metric.Meter, + opt ...metric.Int64ObservableUpDownCounterOption, +) (SDKProcessorSpanQueueCapacity, error) { + // Check if the meter is nil. + if m == nil { + return SDKProcessorSpanQueueCapacity{noop.Int64ObservableUpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKProcessorSpanQueueCapacityOpts + } else { + opt = append(opt, newSDKProcessorSpanQueueCapacityOpts...) + } + + i, err := m.Int64ObservableUpDownCounter( + "otel.sdk.processor.span.queue.capacity", + opt..., + ) + if err != nil { + return SDKProcessorSpanQueueCapacity{noop.Int64ObservableUpDownCounter{}}, err + } + return SDKProcessorSpanQueueCapacity{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKProcessorSpanQueueCapacity) Inst() metric.Int64ObservableUpDownCounter { + return m.Int64ObservableUpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (SDKProcessorSpanQueueCapacity) Name() string { + return "otel.sdk.processor.span.queue.capacity" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKProcessorSpanQueueCapacity) Unit() string { + return "{span}" +} + +// Description returns the semantic convention description of the instrument +func (SDKProcessorSpanQueueCapacity) Description() string { + return "The maximum number of spans the queue of a given instance of an SDK span processor can hold." +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKProcessorSpanQueueCapacity) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKProcessorSpanQueueCapacity) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// SDKProcessorSpanQueueSize is an instrument used to record metric values +// conforming to the "otel.sdk.processor.span.queue.size" semantic conventions. +// It represents the number of spans in the queue of a given instance of an SDK +// span processor. +type SDKProcessorSpanQueueSize struct { + metric.Int64ObservableUpDownCounter +} + +var newSDKProcessorSpanQueueSizeOpts = []metric.Int64ObservableUpDownCounterOption{ + metric.WithDescription("The number of spans in the queue of a given instance of an SDK span processor."), + metric.WithUnit("{span}"), +} + +// NewSDKProcessorSpanQueueSize returns a new SDKProcessorSpanQueueSize +// instrument. +func NewSDKProcessorSpanQueueSize( + m metric.Meter, + opt ...metric.Int64ObservableUpDownCounterOption, +) (SDKProcessorSpanQueueSize, error) { + // Check if the meter is nil. + if m == nil { + return SDKProcessorSpanQueueSize{noop.Int64ObservableUpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKProcessorSpanQueueSizeOpts + } else { + opt = append(opt, newSDKProcessorSpanQueueSizeOpts...) + } + + i, err := m.Int64ObservableUpDownCounter( + "otel.sdk.processor.span.queue.size", + opt..., + ) + if err != nil { + return SDKProcessorSpanQueueSize{noop.Int64ObservableUpDownCounter{}}, err + } + return SDKProcessorSpanQueueSize{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKProcessorSpanQueueSize) Inst() metric.Int64ObservableUpDownCounter { + return m.Int64ObservableUpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (SDKProcessorSpanQueueSize) Name() string { + return "otel.sdk.processor.span.queue.size" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKProcessorSpanQueueSize) Unit() string { + return "{span}" +} + +// Description returns the semantic convention description of the instrument +func (SDKProcessorSpanQueueSize) Description() string { + return "The number of spans in the queue of a given instance of an SDK span processor." +} + +// AttrComponentName returns an optional attribute for the "otel.component.name" +// semantic convention. It represents a name uniquely identifying the instance of +// the OpenTelemetry component within its containing SDK instance. +func (SDKProcessorSpanQueueSize) AttrComponentName(val string) attribute.KeyValue { + return attribute.String("otel.component.name", val) +} + +// AttrComponentType returns an optional attribute for the "otel.component.type" +// semantic convention. It represents a name identifying the type of the +// OpenTelemetry component. +func (SDKProcessorSpanQueueSize) AttrComponentType(val ComponentTypeAttr) attribute.KeyValue { + return attribute.String("otel.component.type", string(val)) +} + +// SDKSpanLive is an instrument used to record metric values conforming to the +// "otel.sdk.span.live" semantic conventions. It represents the number of created +// spans with `recording=true` for which the end operation has not been called +// yet. +type SDKSpanLive struct { + metric.Int64UpDownCounter +} + +var newSDKSpanLiveOpts = []metric.Int64UpDownCounterOption{ + metric.WithDescription("The number of created spans with `recording=true` for which the end operation has not been called yet."), + metric.WithUnit("{span}"), +} + +// NewSDKSpanLive returns a new SDKSpanLive instrument. +func NewSDKSpanLive( + m metric.Meter, + opt ...metric.Int64UpDownCounterOption, +) (SDKSpanLive, error) { + // Check if the meter is nil. + if m == nil { + return SDKSpanLive{noop.Int64UpDownCounter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKSpanLiveOpts + } else { + opt = append(opt, newSDKSpanLiveOpts...) + } + + i, err := m.Int64UpDownCounter( + "otel.sdk.span.live", + opt..., + ) + if err != nil { + return SDKSpanLive{noop.Int64UpDownCounter{}}, err + } + return SDKSpanLive{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKSpanLive) Inst() metric.Int64UpDownCounter { + return m.Int64UpDownCounter +} + +// Name returns the semantic convention name of the instrument. +func (SDKSpanLive) Name() string { + return "otel.sdk.span.live" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKSpanLive) Unit() string { + return "{span}" +} + +// Description returns the semantic convention description of the instrument +func (SDKSpanLive) Description() string { + return "The number of created spans with `recording=true` for which the end operation has not been called yet." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +func (m SDKSpanLive) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +func (m SDKSpanLive) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64UpDownCounter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64UpDownCounter.Add(ctx, incr, *o...) +} + +// AttrSpanSamplingResult returns an optional attribute for the +// "otel.span.sampling_result" semantic convention. It represents the result +// value of the sampler for this span. +func (SDKSpanLive) AttrSpanSamplingResult(val SpanSamplingResultAttr) attribute.KeyValue { + return attribute.String("otel.span.sampling_result", string(val)) +} + +// SDKSpanStarted is an instrument used to record metric values conforming to the +// "otel.sdk.span.started" semantic conventions. It represents the number of +// created spans. +type SDKSpanStarted struct { + metric.Int64Counter +} + +var newSDKSpanStartedOpts = []metric.Int64CounterOption{ + metric.WithDescription("The number of created spans."), + metric.WithUnit("{span}"), +} + +// NewSDKSpanStarted returns a new SDKSpanStarted instrument. +func NewSDKSpanStarted( + m metric.Meter, + opt ...metric.Int64CounterOption, +) (SDKSpanStarted, error) { + // Check if the meter is nil. + if m == nil { + return SDKSpanStarted{noop.Int64Counter{}}, nil + } + + if len(opt) == 0 { + opt = newSDKSpanStartedOpts + } else { + opt = append(opt, newSDKSpanStartedOpts...) + } + + i, err := m.Int64Counter( + "otel.sdk.span.started", + opt..., + ) + if err != nil { + return SDKSpanStarted{noop.Int64Counter{}}, err + } + return SDKSpanStarted{i}, nil +} + +// Inst returns the underlying metric instrument. +func (m SDKSpanStarted) Inst() metric.Int64Counter { + return m.Int64Counter +} + +// Name returns the semantic convention name of the instrument. +func (SDKSpanStarted) Name() string { + return "otel.sdk.span.started" +} + +// Unit returns the semantic convention unit of the instrument +func (SDKSpanStarted) Unit() string { + return "{span}" +} + +// Description returns the semantic convention description of the instrument +func (SDKSpanStarted) Description() string { + return "The number of created spans." +} + +// Add adds incr to the existing count for attrs. +// +// All additional attrs passed are included in the recorded value. +// +// Implementations MUST record this metric for all spans, even for non-recording +// ones. +func (m SDKSpanStarted) Add( + ctx context.Context, + incr int64, + attrs ...attribute.KeyValue, +) { + if len(attrs) == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append( + *o, + metric.WithAttributes( + attrs..., + ), + ) + + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AddSet adds incr to the existing count for set. +// +// Implementations MUST record this metric for all spans, even for non-recording +// ones. +func (m SDKSpanStarted) AddSet(ctx context.Context, incr int64, set attribute.Set) { + if set.Len() == 0 { + m.Int64Counter.Add(ctx, incr) + return + } + + o := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *o = (*o)[:0] + addOptPool.Put(o) + }() + + *o = append(*o, metric.WithAttributeSet(set)) + m.Int64Counter.Add(ctx, incr, *o...) +} + +// AttrSpanParentOrigin returns an optional attribute for the +// "otel.span.parent.origin" semantic convention. It represents the determines +// whether the span has a parent span, and if so, [whether it is a remote parent] +// . +// +// [whether it is a remote parent]: https://opentelemetry.io/docs/specs/otel/trace/api/#isremote +func (SDKSpanStarted) AttrSpanParentOrigin(val SpanParentOriginAttr) attribute.KeyValue { + return attribute.String("otel.span.parent.origin", string(val)) +} + +// AttrSpanSamplingResult returns an optional attribute for the +// "otel.span.sampling_result" semantic convention. It represents the result +// value of the sampler for this span. +func (SDKSpanStarted) AttrSpanSamplingResult(val SpanSamplingResultAttr) attribute.KeyValue { + return attribute.String("otel.span.sampling_result", string(val)) +} diff --git a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go index a7c5d19bff38..1f8d49bc9837 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go @@ -34,7 +34,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// AnyValue is used to represent any type of attribute value. AnyValue may contain a +// Represents any type of attribute value. AnyValue may contain a // primitive value such as a string or integer or it may contain an arbitrary nested // object containing arrays, key-value lists and primitives. type AnyValue struct { @@ -252,8 +252,10 @@ type KeyValueList struct { // A collection of key/value pairs of key-value pairs. The list may be empty (may // contain 0 elements). + // // The keys MUST be unique (it is not allowed to have more than one // value with the same key). + // The behavior of software that receives duplicated keys can be unpredictable. Values []*KeyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` } @@ -296,14 +298,16 @@ func (x *KeyValueList) GetValues() []*KeyValue { return nil } -// KeyValue is a key-value pair that is used to store Span attributes, Link +// Represents a key-value pair that is used to store Span attributes, Link // attributes, etc. type KeyValue struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + // The key name of the pair. + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + // The value of the pair. Value *AnyValue `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } @@ -360,14 +364,21 @@ type InstrumentationScope struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + // A name denoting the Instrumentation scope. // An empty instrumentation scope name means the name is unknown. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // Defines the version of the instrumentation scope. + // An empty instrumentation scope version means the version is unknown. Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` // Additional attributes that describe the scope. [Optional]. // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). - Attributes []*KeyValue `protobuf:"bytes,3,rep,name=attributes,proto3" json:"attributes,omitempty"` - DroppedAttributesCount uint32 `protobuf:"varint,4,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` + // The behavior of software that receives duplicated keys can be unpredictable. + Attributes []*KeyValue `protobuf:"bytes,3,rep,name=attributes,proto3" json:"attributes,omitempty"` + // The number of attributes that were discarded. Attributes + // can be discarded because their keys are too long or because there are too many + // attributes. If this value is 0, then no attributes were dropped. + DroppedAttributesCount uint32 `protobuf:"varint,4,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` } func (x *InstrumentationScope) Reset() { diff --git a/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go b/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go index eb7745d66e02..301247ddfee4 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go @@ -44,8 +44,9 @@ type Resource struct { // Set of attributes that describe the resource. // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). + // The behavior of software that receives duplicated keys can be unpredictable. Attributes []*v1.KeyValue `protobuf:"bytes,1,rep,name=attributes,proto3" json:"attributes,omitempty"` - // dropped_attributes_count is the number of dropped attributes. If the value is 0, then + // The number of dropped attributes. If the value is 0, then // no attributes were dropped. DroppedAttributesCount uint32 `protobuf:"varint,2,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` // Set of entities that participate in this Resource. diff --git a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go index b342a0a94012..d7bfca90299a 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go @@ -388,7 +388,8 @@ type ScopeSpans struct { // is recorded in. Notably, the last part of the URL path is the version number of the // schema: http[s]://server[:port]/path/. To learn more about Schema URL see // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url - // This schema_url applies to all spans and span events in the "spans" field. + // This schema_url applies to the data in the "scope" field and all spans and span + // events in the "spans" field. SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` } @@ -512,21 +513,21 @@ type Span struct { // two spans with the same name may be distinguished using `CLIENT` (caller) // and `SERVER` (callee) to identify queueing latency associated with the span. Kind Span_SpanKind `protobuf:"varint,6,opt,name=kind,proto3,enum=opentelemetry.proto.trace.v1.Span_SpanKind" json:"kind,omitempty"` - // start_time_unix_nano is the start time of the span. On the client side, this is the time + // The start time of the span. On the client side, this is the time // kept by the local machine where the span execution starts. On the server side, this // is the time when the server's application handler starts running. // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970. // // This field is semantically required and it is expected that end_time >= start_time. StartTimeUnixNano uint64 `protobuf:"fixed64,7,opt,name=start_time_unix_nano,json=startTimeUnixNano,proto3" json:"start_time_unix_nano,omitempty"` - // end_time_unix_nano is the end time of the span. On the client side, this is the time + // The end time of the span. On the client side, this is the time // kept by the local machine where the span execution ends. On the server side, this // is the time when the server application handler stops running. // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970. // // This field is semantically required and it is expected that end_time >= start_time. EndTimeUnixNano uint64 `protobuf:"fixed64,8,opt,name=end_time_unix_nano,json=endTimeUnixNano,proto3" json:"end_time_unix_nano,omitempty"` - // attributes is a collection of key/value pairs. Note, global attributes + // A collection of key/value pairs. Note, global attributes // like server name can be set using the resource API. Examples of attributes: // // "/http/user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" @@ -534,24 +535,23 @@ type Span struct { // "example.com/myattribute": true // "example.com/score": 10.239 // - // The OpenTelemetry API specification further restricts the allowed value types: - // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/common/README.md#attribute // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). + // The behavior of software that receives duplicated keys can be unpredictable. Attributes []*v11.KeyValue `protobuf:"bytes,9,rep,name=attributes,proto3" json:"attributes,omitempty"` - // dropped_attributes_count is the number of attributes that were discarded. Attributes + // The number of attributes that were discarded. Attributes // can be discarded because their keys are too long or because there are too many // attributes. If this value is 0, then no attributes were dropped. DroppedAttributesCount uint32 `protobuf:"varint,10,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` - // events is a collection of Event items. + // A collection of Event items. Events []*Span_Event `protobuf:"bytes,11,rep,name=events,proto3" json:"events,omitempty"` - // dropped_events_count is the number of dropped events. If the value is 0, then no + // The number of dropped events. If the value is 0, then no // events were dropped. DroppedEventsCount uint32 `protobuf:"varint,12,opt,name=dropped_events_count,json=droppedEventsCount,proto3" json:"dropped_events_count,omitempty"` - // links is a collection of Links, which are references from this span to a span + // A collection of Links, which are references from this span to a span // in the same or different trace. Links []*Span_Link `protobuf:"bytes,13,rep,name=links,proto3" json:"links,omitempty"` - // dropped_links_count is the number of dropped links after the maximum size was + // The number of dropped links after the maximum size was // enforced. If this value is 0, then no links were dropped. DroppedLinksCount uint32 `protobuf:"varint,14,opt,name=dropped_links_count,json=droppedLinksCount,proto3" json:"dropped_links_count,omitempty"` // An optional final status for this span. Semantically when Status isn't set, it means @@ -769,16 +769,17 @@ type Span_Event struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // time_unix_nano is the time the event occurred. + // The time the event occurred. TimeUnixNano uint64 `protobuf:"fixed64,1,opt,name=time_unix_nano,json=timeUnixNano,proto3" json:"time_unix_nano,omitempty"` - // name of the event. + // The name of the event. // This field is semantically required to be set to non-empty string. Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - // attributes is a collection of attribute key/value pairs on the event. + // A collection of attribute key/value pairs on the event. // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). + // The behavior of software that receives duplicated keys can be unpredictable. Attributes []*v11.KeyValue `protobuf:"bytes,3,rep,name=attributes,proto3" json:"attributes,omitempty"` - // dropped_attributes_count is the number of dropped attributes. If the value is 0, + // The number of dropped attributes. If the value is 0, // then no attributes were dropped. DroppedAttributesCount uint32 `protobuf:"varint,4,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` } @@ -859,11 +860,12 @@ type Span_Link struct { SpanId []byte `protobuf:"bytes,2,opt,name=span_id,json=spanId,proto3" json:"span_id,omitempty"` // The trace_state associated with the link. TraceState string `protobuf:"bytes,3,opt,name=trace_state,json=traceState,proto3" json:"trace_state,omitempty"` - // attributes is a collection of attribute key/value pairs on the link. + // A collection of attribute key/value pairs on the link. // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). + // The behavior of software that receives duplicated keys can be unpredictable. Attributes []*v11.KeyValue `protobuf:"bytes,4,rep,name=attributes,proto3" json:"attributes,omitempty"` - // dropped_attributes_count is the number of dropped attributes. If the value is 0, + // The number of dropped attributes. If the value is 0, // then no attributes were dropped. DroppedAttributesCount uint32 `protobuf:"varint,5,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` // Flags, a bit field. diff --git a/vendor/gopkg.in/evanphx/json-patch.v4/README.md b/vendor/gopkg.in/evanphx/json-patch.v4/README.md index 28e35169375b..86fefd5bf7d6 100644 --- a/vendor/gopkg.in/evanphx/json-patch.v4/README.md +++ b/vendor/gopkg.in/evanphx/json-patch.v4/README.md @@ -4,7 +4,7 @@ well as for calculating & applying [RFC7396 JSON merge patches](https://tools.ietf.org/html/rfc7396). [![GoDoc](https://godoc.org/github.com/evanphx/json-patch?status.svg)](http://godoc.org/github.com/evanphx/json-patch) -[![Build Status](https://travis-ci.org/evanphx/json-patch.svg?branch=master)](https://travis-ci.org/evanphx/json-patch) +[![Build Status](https://github.com/evanphx/json-patch/actions/workflows/go.yml/badge.svg)](https://github.com/evanphx/json-patch/actions/workflows/go.yml) [![Report Card](https://goreportcard.com/badge/github.com/evanphx/json-patch)](https://goreportcard.com/report/github.com/evanphx/json-patch) # Get It! @@ -14,9 +14,7 @@ well as for calculating & applying [RFC7396 JSON merge patches](https://tools.ie go get -u github.com/evanphx/json-patch/v5 ``` -**Stable Versions**: -* Version 5: `go get -u gopkg.in/evanphx/json-patch.v5` -* Version 4: `go get -u gopkg.in/evanphx/json-patch.v4` +If you need version 4, use `go get -u gopkg.in/evanphx/json-patch.v4` (previous versions below `v3` are unavailable) @@ -314,4 +312,4 @@ go test -cover ./... ``` Builds for pull requests are tested automatically -using [TravisCI](https://travis-ci.org/evanphx/json-patch). +using [GitHub Actions](https://github.com/evanphx/json-patch/actions/workflows/go.yml). diff --git a/vendor/gopkg.in/evanphx/json-patch.v4/patch.go b/vendor/gopkg.in/evanphx/json-patch.v4/patch.go index dc2b7e51e60b..95136681ba76 100644 --- a/vendor/gopkg.in/evanphx/json-patch.v4/patch.go +++ b/vendor/gopkg.in/evanphx/json-patch.v4/patch.go @@ -3,11 +3,10 @@ package jsonpatch import ( "bytes" "encoding/json" + "errors" "fmt" "strconv" "strings" - - "github.com/pkg/errors" ) const ( @@ -277,7 +276,7 @@ func (o Operation) Path() (string, error) { return op, nil } - return "unknown", errors.Wrapf(ErrMissing, "operation missing path field") + return "unknown", fmt.Errorf("operation missing path field: %w", ErrMissing) } // From reads the "from" field of the Operation. @@ -294,7 +293,7 @@ func (o Operation) From() (string, error) { return op, nil } - return "unknown", errors.Wrapf(ErrMissing, "operation, missing from field") + return "unknown", fmt.Errorf("operation, missing from field: %w", ErrMissing) } func (o Operation) value() *lazyNode { @@ -319,7 +318,7 @@ func (o Operation) ValueInterface() (interface{}, error) { return v, nil } - return nil, errors.Wrapf(ErrMissing, "operation, missing value field") + return nil, fmt.Errorf("operation, missing value field: %w", ErrMissing) } func isArray(buf []byte) bool { @@ -359,7 +358,7 @@ func findObject(pd *container, path string) (container, string) { next, ok := doc.get(decodePatchKey(part)) - if next == nil || ok != nil { + if next == nil || ok != nil || next.raw == nil { return nil, "" } @@ -398,7 +397,7 @@ func (d *partialDoc) get(key string) (*lazyNode, error) { func (d *partialDoc) remove(key string) error { _, ok := (*d)[key] if !ok { - return errors.Wrapf(ErrMissing, "Unable to remove nonexistent key: %s", key) + return fmt.Errorf("Unable to remove nonexistent key: %s: %w", key, ErrMissing) } delete(*d, key) @@ -415,10 +414,10 @@ func (d *partialArray) set(key string, val *lazyNode) error { if idx < 0 { if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(*d) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(*d) } @@ -435,7 +434,7 @@ func (d *partialArray) add(key string, val *lazyNode) error { idx, err := strconv.Atoi(key) if err != nil { - return errors.Wrapf(err, "value was not a proper array index: '%s'", key) + return fmt.Errorf("value was not a proper array index: '%s': %w", key, err) } sz := len(*d) + 1 @@ -445,15 +444,15 @@ func (d *partialArray) add(key string, val *lazyNode) error { cur := *d if idx >= len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < 0 { if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(ary) } @@ -475,16 +474,16 @@ func (d *partialArray) get(key string) (*lazyNode, error) { if idx < 0 { if !SupportNegativeIndices { - return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(*d) { - return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(*d) } if idx >= len(*d) { - return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } return (*d)[idx], nil @@ -499,15 +498,15 @@ func (d *partialArray) remove(key string) error { cur := *d if idx >= len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < 0 { if !SupportNegativeIndices { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) + return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(cur) } @@ -525,18 +524,18 @@ func (d *partialArray) remove(key string) error { func (p Patch) add(doc *container, op Operation) error { path, err := op.Path() if err != nil { - return errors.Wrapf(ErrMissing, "add operation failed to decode path") + return fmt.Errorf("add operation failed to decode path: %w", ErrMissing) } con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "add operation does not apply: doc is missing path: \"%s\"", path) + return fmt.Errorf("add operation does not apply: doc is missing path: \"%s\": %w", path, ErrMissing) } err = con.add(key, op.value()) if err != nil { - return errors.Wrapf(err, "error in add for path: '%s'", path) + return fmt.Errorf("error in add for path: '%s': %w", path, err) } return nil @@ -545,18 +544,18 @@ func (p Patch) add(doc *container, op Operation) error { func (p Patch) remove(doc *container, op Operation) error { path, err := op.Path() if err != nil { - return errors.Wrapf(ErrMissing, "remove operation failed to decode path") + return fmt.Errorf("remove operation failed to decode path: %w", ErrMissing) } con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "remove operation does not apply: doc is missing path: \"%s\"", path) + return fmt.Errorf("remove operation does not apply: doc is missing path: \"%s\": %w", path, ErrMissing) } err = con.remove(key) if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) + return fmt.Errorf("error in remove for path: '%s': %w", path, err) } return nil @@ -565,7 +564,7 @@ func (p Patch) remove(doc *container, op Operation) error { func (p Patch) replace(doc *container, op Operation) error { path, err := op.Path() if err != nil { - return errors.Wrapf(err, "replace operation failed to decode path") + return fmt.Errorf("replace operation failed to decode path: %w", err) } if path == "" { @@ -574,7 +573,7 @@ func (p Patch) replace(doc *container, op Operation) error { if val.which == eRaw { if !val.tryDoc() { if !val.tryAry() { - return errors.Wrapf(err, "replace operation value must be object or array") + return fmt.Errorf("replace operation value must be object or array: %w", err) } } } @@ -585,7 +584,7 @@ func (p Patch) replace(doc *container, op Operation) error { case eDoc: *doc = &val.doc case eRaw: - return errors.Wrapf(err, "replace operation hit impossible case") + return fmt.Errorf("replace operation hit impossible case: %w", err) } return nil @@ -594,17 +593,17 @@ func (p Patch) replace(doc *container, op Operation) error { con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing path: %s", path) + return fmt.Errorf("replace operation does not apply: doc is missing path: %s: %w", path, ErrMissing) } _, ok := con.get(key) if ok != nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing key: %s", path) + return fmt.Errorf("replace operation does not apply: doc is missing key: %s: %w", path, ErrMissing) } err = con.set(key, op.value()) if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) + return fmt.Errorf("error in remove for path: '%s': %w", path, err) } return nil @@ -613,39 +612,39 @@ func (p Patch) replace(doc *container, op Operation) error { func (p Patch) move(doc *container, op Operation) error { from, err := op.From() if err != nil { - return errors.Wrapf(err, "move operation failed to decode from") + return fmt.Errorf("move operation failed to decode from: %w", err) } con, key := findObject(doc, from) if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing from path: %s", from) + return fmt.Errorf("move operation does not apply: doc is missing from path: %s: %w", from, ErrMissing) } val, err := con.get(key) if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) + return fmt.Errorf("error in move for path: '%s': %w", key, err) } err = con.remove(key) if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) + return fmt.Errorf("error in move for path: '%s': %w", key, err) } path, err := op.Path() if err != nil { - return errors.Wrapf(err, "move operation failed to decode path") + return fmt.Errorf("move operation failed to decode path: %w", err) } con, key = findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing destination path: %s", path) + return fmt.Errorf("move operation does not apply: doc is missing destination path: %s: %w", path, ErrMissing) } err = con.add(key, val) if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", path) + return fmt.Errorf("error in move for path: '%s': %w", path, err) } return nil @@ -654,7 +653,7 @@ func (p Patch) move(doc *container, op Operation) error { func (p Patch) test(doc *container, op Operation) error { path, err := op.Path() if err != nil { - return errors.Wrapf(err, "test operation failed to decode path") + return fmt.Errorf("test operation failed to decode path: %w", err) } if path == "" { @@ -673,67 +672,67 @@ func (p Patch) test(doc *container, op Operation) error { return nil } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } con, key := findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "test operation does not apply: is missing path: %s", path) + return fmt.Errorf("test operation does not apply: is missing path: %s: %w", path, ErrMissing) } val, err := con.get(key) if err != nil { - return errors.Wrapf(err, "error in test for path: '%s'", path) + return fmt.Errorf("error in test for path: '%s': %w", path, err) } if val == nil { - if op.value().raw == nil { + if op.value() == nil || op.value().raw == nil { return nil } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } else if op.value() == nil { - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } if val.equal(op.value()) { return nil } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) + return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64) error { from, err := op.From() if err != nil { - return errors.Wrapf(err, "copy operation failed to decode from") + return fmt.Errorf("copy operation failed to decode from: %w", err) } con, key := findObject(doc, from) if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing from path: %s", from) + return fmt.Errorf("copy operation does not apply: doc is missing from path: %s: %w", from, ErrMissing) } val, err := con.get(key) if err != nil { - return errors.Wrapf(err, "error in copy for from: '%s'", from) + return fmt.Errorf("error in copy for from: '%s': %w", from, err) } path, err := op.Path() if err != nil { - return errors.Wrapf(ErrMissing, "copy operation failed to decode path") + return fmt.Errorf("copy operation failed to decode path: %w", ErrMissing) } con, key = findObject(doc, path) if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing destination path: %s", path) + return fmt.Errorf("copy operation does not apply: doc is missing destination path: %s: %w", path, ErrMissing) } valCopy, sz, err := deepCopy(val) if err != nil { - return errors.Wrapf(err, "error while performing deep copy") + return fmt.Errorf("error while performing deep copy: %w", err) } (*accumulatedCopySize) += int64(sz) @@ -743,7 +742,7 @@ func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64) er err = con.add(key, valCopy) if err != nil { - return errors.Wrapf(err, "error while adding value during copy") + return fmt.Errorf("error while adding value during copy: %w", err) } return nil diff --git a/vendor/k8s.io/apimachinery/pkg/api/apitesting/close.go b/vendor/k8s.io/apimachinery/pkg/api/apitesting/close.go new file mode 100644 index 000000000000..dfb5657eb98d --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/apitesting/close.go @@ -0,0 +1,54 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package apitesting + +import ( + "io" + "testing" +) + +// Close and fail the test if it returns an error. +func Close(t TestingT, c io.Closer) { + t.Helper() + assertNoError(t, c.Close()) +} + +// CloseNoOp does nothing. Use as a replacement for Close when you +// need to disable a defer. +func CloseNoOp(TestingT, io.Closer) {} + +// TestingT simulates assert.TestingT and assert.tHelper without adding +// testify as a non-test dependency. +type TestingT interface { + Errorf(format string, args ...interface{}) + Helper() +} + +// Ensure that testing T & B satisfy the TestingT interface +var _ TestingT = &testing.T{} +var _ TestingT = &testing.B{} + +// assertNoError simulates assert.NoError without adding testify as a +// non-test dependency. +// +// In test files, use github.com/stretchr/testify/assert instead. +func assertNoError(t TestingT, err error) { + t.Helper() + if err != nil { + t.Errorf("Received unexpected error:\n%+v", err) + } +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/apitesting/codec.go b/vendor/k8s.io/apimachinery/pkg/api/apitesting/codec.go new file mode 100644 index 000000000000..542b0aa275d2 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/apitesting/codec.go @@ -0,0 +1,116 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package apitesting + +import ( + "fmt" + "mime" + "os" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/apimachinery/pkg/runtime/serializer/recognizer" +) + +var ( + testCodecMediaType string + testStorageCodecMediaType string +) + +// TestCodec returns the codec for the API version to test against, as set by the +// KUBE_TEST_API_TYPE env var. +func TestCodec(codecs runtimeserializer.CodecFactory, gvs ...schema.GroupVersion) runtime.Codec { + if len(testCodecMediaType) != 0 { + serializerInfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), testCodecMediaType) + if !ok { + panic(fmt.Sprintf("no serializer for %s", testCodecMediaType)) + } + return codecs.CodecForVersions(serializerInfo.Serializer, codecs.UniversalDeserializer(), schema.GroupVersions(gvs), nil) + } + return codecs.LegacyCodec(gvs...) +} + +// TestStorageCodec returns the codec for the API version to test against used in storage, as set by the +// KUBE_TEST_API_STORAGE_TYPE env var. +func TestStorageCodec(codecs runtimeserializer.CodecFactory, gvs ...schema.GroupVersion) runtime.Codec { + if len(testStorageCodecMediaType) != 0 { + serializerInfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), testStorageCodecMediaType) + if !ok { + panic(fmt.Sprintf("no serializer for %s", testStorageCodecMediaType)) + } + + // etcd2 only supports string data - we must wrap any result before returning + // TODO: remove for etcd3 / make parameterizable + serializer := serializerInfo.Serializer + if !serializerInfo.EncodesAsText { + serializer = runtime.NewBase64Serializer(serializer, serializer) + } + + decoder := recognizer.NewDecoder(serializer, codecs.UniversalDeserializer()) + return codecs.CodecForVersions(serializer, decoder, schema.GroupVersions(gvs), nil) + + } + return codecs.LegacyCodec(gvs...) +} + +func init() { + var err error + if apiMediaType := os.Getenv("KUBE_TEST_API_TYPE"); len(apiMediaType) > 0 { + testCodecMediaType, _, err = mime.ParseMediaType(apiMediaType) + if err != nil { + panic(err) + } + } + + if storageMediaType := os.Getenv("KUBE_TEST_API_STORAGE_TYPE"); len(storageMediaType) > 0 { + testStorageCodecMediaType, _, err = mime.ParseMediaType(storageMediaType) + if err != nil { + panic(err) + } + } +} + +// InstallOrDieFunc mirrors install functions that require success +type InstallOrDieFunc func(scheme *runtime.Scheme) + +// SchemeForInstallOrDie builds a simple test scheme and codecfactory pair for easy unit testing from higher level install methods +func SchemeForInstallOrDie(installFns ...InstallOrDieFunc) (*runtime.Scheme, runtimeserializer.CodecFactory) { + scheme := runtime.NewScheme() + codecFactory := runtimeserializer.NewCodecFactory(scheme) + for _, installFn := range installFns { + installFn(scheme) + } + + return scheme, codecFactory +} + +// InstallFunc mirrors install functions that can return an error +type InstallFunc func(scheme *runtime.Scheme) error + +// SchemeForOrDie builds a simple test scheme and codecfactory pair for easy unit testing from the bare registration methods. +func SchemeForOrDie(installFns ...InstallFunc) (*runtime.Scheme, runtimeserializer.CodecFactory) { + scheme := runtime.NewScheme() + codecFactory := runtimeserializer.NewCodecFactory(scheme) + for _, installFn := range installFns { + if err := installFn(scheme); err != nil { + panic(err) + } + } + + return scheme, codecFactory +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/fuzzer.go b/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/fuzzer.go new file mode 100644 index 000000000000..a12370886fc4 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/fuzzer.go @@ -0,0 +1,73 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package fuzzer + +import ( + "encoding/json" + "fmt" + "math/rand" + + "sigs.k8s.io/randfill" + + "k8s.io/apimachinery/pkg/runtime" + runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" + kjson "k8s.io/apimachinery/pkg/util/json" +) + +// FuzzerFuncs returns a list of func(*SomeType, c randfill.Continue) functions. +type FuzzerFuncs func(codecs runtimeserializer.CodecFactory) []interface{} + +// FuzzerFor can randomly populate api objects that are destined for version. +func FuzzerFor(funcs FuzzerFuncs, src rand.Source, codecs runtimeserializer.CodecFactory) *randfill.Filler { + f := randfill.New().NilChance(.5).NumElements(0, 1) + if src != nil { + f.RandSource(src) + } + f.Funcs(funcs(codecs)...) + return f +} + +// MergeFuzzerFuncs will merge the given funcLists, overriding early funcs with later ones if there first +// argument has the same type. +func MergeFuzzerFuncs(funcs ...FuzzerFuncs) FuzzerFuncs { + return FuzzerFuncs(func(codecs runtimeserializer.CodecFactory) []interface{} { + result := []interface{}{} + for _, f := range funcs { + if f != nil { + result = append(result, f(codecs)...) + } + } + return result + }) +} + +func NormalizeJSONRawExtension(ext *runtime.RawExtension) { + if json.Valid(ext.Raw) { + // RawExtension->JSON encodes struct fields in field index order while map[string]interface{}->JSON encodes + // struct fields (i.e. keys in the map) lexicographically. We have to sort the fields here to ensure the + // JSON in the (RawExtension->)JSON->map[string]interface{}->JSON round trip results in identical JSON. + var u any + err := kjson.Unmarshal(ext.Raw, &u) + if err != nil { + panic(fmt.Sprintf("Failed to encode object: %v", err)) + } + ext.Raw, err = kjson.Marshal(&u) + if err != nil { + panic(fmt.Sprintf("Failed to encode object: %v", err)) + } + } +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz.go b/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz.go new file mode 100644 index 000000000000..facff57bbadf --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz.go @@ -0,0 +1,86 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package fuzzer + +import ( + "reflect" +) + +// ValueFuzz recursively changes all basic type values in an object. Any kind of references will not +// be touch, i.e. the addresses of slices, maps, pointers will stay unchanged. +func ValueFuzz(obj interface{}) { + valueFuzz(reflect.ValueOf(obj)) +} + +func valueFuzz(obj reflect.Value) { + switch obj.Kind() { + case reflect.Array: + for i := 0; i < obj.Len(); i++ { + valueFuzz(obj.Index(i)) + } + case reflect.Slice: + if obj.IsNil() { + // TODO: set non-nil value + } else { + for i := 0; i < obj.Len(); i++ { + valueFuzz(obj.Index(i)) + } + } + case reflect.Interface, reflect.Pointer: + if obj.IsNil() { + // TODO: set non-nil value + } else { + valueFuzz(obj.Elem()) + } + case reflect.Struct: + for i, n := 0, obj.NumField(); i < n; i++ { + valueFuzz(obj.Field(i)) + } + case reflect.Map: + if obj.IsNil() { + // TODO: set non-nil value + } else { + for _, k := range obj.MapKeys() { + // map values are not addressable. We need a copy. + v := obj.MapIndex(k) + copy := reflect.New(v.Type()) + copy.Elem().Set(v) + valueFuzz(copy.Elem()) + obj.SetMapIndex(k, copy.Elem()) + } + // TODO: set some new value + } + case reflect.Func: // ignore, we don't have function types in our API + default: + if !obj.CanSet() { + return + } + switch obj.Kind() { + case reflect.String: + obj.SetString(obj.String() + "x") + case reflect.Bool: + obj.SetBool(!obj.Bool()) + case reflect.Float32, reflect.Float64: + obj.SetFloat(obj.Float()*2.0 + 1.0) + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + obj.SetInt(obj.Int() + 1) + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + obj.SetUint(obj.Uint() + 1) + default: + } + } +} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go new file mode 100644 index 000000000000..c263f1450dd6 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go @@ -0,0 +1,339 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package fuzzer + +import ( + "fmt" + "math/rand" + "sort" + "strconv" + "strings" + + "sigs.k8s.io/randfill" + + apitesting "k8s.io/apimachinery/pkg/api/apitesting" + "k8s.io/apimachinery/pkg/api/apitesting/fuzzer" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" + "k8s.io/apimachinery/pkg/runtime" + runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/sets" +) + +func genericFuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} { + return []interface{}{ + func(q *resource.Quantity, c randfill.Continue) { + *q = *resource.NewQuantity(c.Int63n(1000), resource.DecimalExponent) + }, + func(j *int, c randfill.Continue) { + *j = int(c.Int31()) + }, + func(j **int, c randfill.Continue) { + if c.Bool() { + i := int(c.Int31()) + *j = &i + } else { + *j = nil + } + }, + func(j *runtime.TypeMeta, c randfill.Continue) { + // We have to customize the randomization of TypeMetas because their + // APIVersion and Kind must remain blank in memory. + j.APIVersion = "" + j.Kind = "" + }, + func(j *runtime.Object, c randfill.Continue) { + // TODO: uncomment when round trip starts from a versioned object + if true { // c.Bool() { + *j = &runtime.Unknown{ + // We do not set TypeMeta here because it is not carried through a round trip + Raw: []byte(`{"apiVersion":"unknown.group/unknown","kind":"Something","someKey":"someValue"}`), + ContentType: runtime.ContentTypeJSON, + } + } else { + types := []runtime.Object{&metav1.Status{}, &metav1.APIGroup{}} + t := types[c.Rand.Intn(len(types))] + c.Fill(t) + *j = t + } + }, + func(r *runtime.RawExtension, c randfill.Continue) { + // Pick an arbitrary type and fuzz it + types := []runtime.Object{&metav1.Status{}, &metav1.APIGroup{}} + obj := types[c.Rand.Intn(len(types))] + c.Fill(obj) + + // Find a codec for converting the object to raw bytes. This is necessary for the + // api version and kind to be correctly set be serialization. + var codec = apitesting.TestCodec(codecs, metav1.SchemeGroupVersion) + + // Convert the object to raw bytes + bytes, err := runtime.Encode(codec, obj) + if err != nil { + panic(fmt.Sprintf("Failed to encode object: %v", err)) + } + + // strip trailing newlines which do not survive roundtrips + for len(bytes) >= 1 && bytes[len(bytes)-1] == 10 { + bytes = bytes[:len(bytes)-1] + } + + // Set the bytes field on the RawExtension + r.Raw = bytes + }, + } +} + +// taken from randfill (nee gofuzz) internals for RandString +type charRange struct { + first, last rune +} + +func (c *charRange) choose(r *rand.Rand) rune { + count := int64(c.last - c.first + 1) + ch := c.first + rune(r.Int63n(count)) + + return ch +} + +// randomLabelPart produces a valid random label value or name-part +// of a label key. +func randomLabelPart(c randfill.Continue, canBeEmpty bool) string { + validStartEnd := []charRange{{'0', '9'}, {'a', 'z'}, {'A', 'Z'}} + validMiddle := []charRange{{'0', '9'}, {'a', 'z'}, {'A', 'Z'}, + {'.', '.'}, {'-', '-'}, {'_', '_'}} + + partLen := c.Rand.Intn(64) // len is [0, 63] + if !canBeEmpty { + partLen = c.Rand.Intn(63) + 1 // len is [1, 63] + } + + runes := make([]rune, partLen) + if partLen == 0 { + return string(runes) + } + + runes[0] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand) + for i := range runes[1:] { + runes[i+1] = validMiddle[c.Rand.Intn(len(validMiddle))].choose(c.Rand) + } + runes[len(runes)-1] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand) + + return string(runes) +} + +func randomDNSLabel(c randfill.Continue) string { + validStartEnd := []charRange{{'0', '9'}, {'a', 'z'}} + validMiddle := []charRange{{'0', '9'}, {'a', 'z'}, {'-', '-'}} + + partLen := c.Rand.Intn(63) + 1 // len is [1, 63] + runes := make([]rune, partLen) + + runes[0] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand) + for i := range runes[1:] { + runes[i+1] = validMiddle[c.Rand.Intn(len(validMiddle))].choose(c.Rand) + } + runes[len(runes)-1] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand) + + return string(runes) +} + +func randomLabelKey(c randfill.Continue) string { + namePart := randomLabelPart(c, false) + prefixPart := "" + + usePrefix := c.Bool() + if usePrefix { + // we can fit, with dots, at most 3 labels in the 253 allotted characters + prefixPartsLen := c.Rand.Intn(2) + 1 + prefixParts := make([]string, prefixPartsLen) + for i := range prefixParts { + prefixParts[i] = randomDNSLabel(c) + } + prefixPart = strings.Join(prefixParts, ".") + "/" + } + + return prefixPart + namePart +} + +func v1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} { + + return []interface{}{ + func(j *metav1.TypeMeta, c randfill.Continue) { + // We have to customize the randomization of TypeMetas because their + // APIVersion and Kind must remain blank in memory. + j.APIVersion = "" + j.Kind = "" + }, + func(j *metav1.ObjectMeta, c randfill.Continue) { + c.FillNoCustom(j) + + j.ResourceVersion = strconv.FormatUint(c.Uint64(), 10) + j.UID = types.UID(c.String(0)) + + // Fuzzing sec and nsec in a smaller range (uint32 instead of int64), + // so that the result Unix time is a valid date and can be parsed into RFC3339 format. + var sec, nsec uint32 + c.Fill(&sec) + c.Fill(&nsec) + j.CreationTimestamp = metav1.Unix(int64(sec), int64(nsec)).Rfc3339Copy() + + if j.DeletionTimestamp != nil { + c.Fill(&sec) + c.Fill(&nsec) + t := metav1.Unix(int64(sec), int64(nsec)).Rfc3339Copy() + j.DeletionTimestamp = &t + } + + if len(j.Labels) == 0 { + j.Labels = nil + } else { + delete(j.Labels, "") + } + if len(j.Annotations) == 0 { + j.Annotations = nil + } else { + delete(j.Annotations, "") + } + if len(j.OwnerReferences) == 0 { + j.OwnerReferences = nil + } + if len(j.Finalizers) == 0 { + j.Finalizers = nil + } + }, + func(j *metav1.ResourceVersionMatch, c randfill.Continue) { + matches := []metav1.ResourceVersionMatch{"", metav1.ResourceVersionMatchExact, metav1.ResourceVersionMatchNotOlderThan} + *j = matches[c.Rand.Intn(len(matches))] + }, + func(j *metav1.ListMeta, c randfill.Continue) { + j.ResourceVersion = strconv.FormatUint(c.Uint64(), 10) + j.SelfLink = c.String(0) //nolint:staticcheck // SA1019 backwards compatibility + }, + func(j *metav1.LabelSelector, c randfill.Continue) { + c.FillNoCustom(j) + // we can't have an entirely empty selector, so force + // use of MatchExpression if necessary + if len(j.MatchLabels) == 0 && len(j.MatchExpressions) == 0 { + j.MatchExpressions = make([]metav1.LabelSelectorRequirement, c.Rand.Intn(2)+1) + } + + if j.MatchLabels != nil { + fuzzedMatchLabels := make(map[string]string, len(j.MatchLabels)) + for i := 0; i < len(j.MatchLabels); i++ { + fuzzedMatchLabels[randomLabelKey(c)] = randomLabelPart(c, true) + } + j.MatchLabels = fuzzedMatchLabels + } + + validOperators := []metav1.LabelSelectorOperator{ + metav1.LabelSelectorOpIn, + metav1.LabelSelectorOpNotIn, + metav1.LabelSelectorOpExists, + metav1.LabelSelectorOpDoesNotExist, + } + + if j.MatchExpressions != nil { + // NB: the label selector parser code sorts match expressions by key, and + // sorts and deduplicates the values, so we need to make sure ours are + // sorted and deduplicated as well here to preserve round-trip comparison. + // In practice, not sorting doesn't hurt anything... + + for i := range j.MatchExpressions { + req := metav1.LabelSelectorRequirement{} + c.Fill(&req) + req.Key = randomLabelKey(c) + req.Operator = validOperators[c.Rand.Intn(len(validOperators))] + if req.Operator == metav1.LabelSelectorOpIn || req.Operator == metav1.LabelSelectorOpNotIn { + if len(req.Values) == 0 { + // we must have some values here, so randomly choose a short length + req.Values = make([]string, c.Rand.Intn(2)+1) + } + for i := range req.Values { + req.Values[i] = randomLabelPart(c, true) + } + req.Values = sets.List(sets.New(req.Values...)) + } else { + req.Values = nil + } + j.MatchExpressions[i] = req + } + + sort.Slice(j.MatchExpressions, func(a, b int) bool { return j.MatchExpressions[a].Key < j.MatchExpressions[b].Key }) + } + }, + func(j *metav1.ManagedFieldsEntry, c randfill.Continue) { + c.FillNoCustom(j) + j.FieldsV1 = nil + }, + } +} + +func v1beta1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} { + return []interface{}{ + func(r *metav1beta1.TableOptions, c randfill.Continue) { + c.FillNoCustom(r) + // NoHeaders is not serialized to the wire but is allowed within the versioned + // type because we don't use meta internal types in the client and API server. + r.NoHeaders = false + }, + func(r *metav1beta1.TableRow, c randfill.Continue) { + c.Fill(&r.Object) + c.Fill(&r.Conditions) + if len(r.Conditions) == 0 { + r.Conditions = nil + } + n := c.Intn(10) + if n > 0 { + r.Cells = make([]interface{}, n) + } + for i := range r.Cells { + t := c.Intn(6) + switch t { + case 0: + r.Cells[i] = c.String(0) + case 1: + r.Cells[i] = c.Int63() + case 2: + r.Cells[i] = c.Bool() + case 3: + x := map[string]interface{}{} + for j := c.Intn(10) + 1; j >= 0; j-- { + x[c.String(0)] = c.String(0) + } + r.Cells[i] = x + case 4: + x := make([]interface{}, c.Intn(10)) + for i := range x { + x[i] = c.Int63() + } + r.Cells[i] = x + default: + r.Cells[i] = nil + } + } + }, + } +} + +var Funcs = fuzzer.MergeFuzzerFuncs( + genericFuzzerFuncs, + v1FuzzerFuncs, + v1beta1FuzzerFuncs, +) diff --git a/vendor/k8s.io/kube-openapi/pkg/util/util.go b/vendor/k8s.io/kube-openapi/pkg/util/util.go index 6eee935b22a9..830ec3ca091a 100644 --- a/vendor/k8s.io/kube-openapi/pkg/util/util.go +++ b/vendor/k8s.io/kube-openapi/pkg/util/util.go @@ -92,10 +92,21 @@ type OpenAPICanonicalTypeNamer interface { OpenAPICanonicalTypeName() string } +// OpenAPIModelNamer is an interface Go types may implement to provide an OpenAPI model name. +// +// This takes precedence over OpenAPICanonicalTypeNamer, and should be used when a Go type has a model +// name that differs from its canonical type name as determined by Go package name reflection. +type OpenAPIModelNamer interface { + OpenAPIModelName() string +} + // GetCanonicalTypeName will find the canonical type name of a sample object, removing // the "vendor" part of the path func GetCanonicalTypeName(model interface{}) string { - if namer, ok := model.(OpenAPICanonicalTypeNamer); ok { + switch namer := model.(type) { + case OpenAPIModelNamer: + return namer.OpenAPIModelName() + case OpenAPICanonicalTypeNamer: return namer.OpenAPICanonicalTypeName() } t := reflect.TypeOf(model) diff --git a/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go b/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go index 775b3b0c3673..29cec61930c1 100644 --- a/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go +++ b/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go @@ -16,10 +16,6 @@ package spec import ( "encoding/json" - "net/http" - "os" - "path/filepath" - "github.com/go-openapi/jsonreference" "k8s.io/kube-openapi/pkg/internal" @@ -56,52 +52,6 @@ func (r *Ref) RemoteURI() string { return u.String() } -// IsValidURI returns true when the url the ref points to can be found -func (r *Ref) IsValidURI(basepaths ...string) bool { - if r.String() == "" { - return true - } - - v := r.RemoteURI() - if v == "" { - return true - } - - if r.HasFullURL { - rr, err := http.Get(v) - if err != nil { - return false - } - - return rr.StatusCode/100 == 2 - } - - if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) { - return false - } - - // check for local file - pth := v - if r.HasURLPathOnly { - base := "." - if len(basepaths) > 0 { - base = filepath.Dir(filepath.Join(basepaths...)) - } - p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth))) - if e != nil { - return false - } - pth = p - } - - fi, err := os.Stat(filepath.ToSlash(pth)) - if err != nil { - return false - } - - return !fi.IsDir() -} - // Inherits creates a new reference from a parent and a child // If the child cannot inherit from the parent, an error is returned func (r *Ref) Inherits(child Ref) (*Ref, error) { diff --git a/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/default.go b/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/default.go index 97b2f989e9f4..23109816eb6c 100644 --- a/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/default.go +++ b/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/default.go @@ -17,7 +17,6 @@ package strfmt import ( "encoding/base64" "encoding/json" - "fmt" "net/mail" "regexp" "strings" @@ -247,29 +246,6 @@ func (b *Base64) UnmarshalText(data []byte) error { // validation is performed l return nil } -// Scan read a value from a database driver -func (b *Base64) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - dbuf := make([]byte, base64.StdEncoding.DecodedLen(len(v))) - n, err := base64.StdEncoding.Decode(dbuf, v) - if err != nil { - return err - } - *b = dbuf[:n] - case string: - vv, err := base64.StdEncoding.DecodeString(v) - if err != nil { - return err - } - *b = Base64(vv) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.Base64 from: %#v", v) - } - - return nil -} - func (b Base64) String() string { return base64.StdEncoding.EncodeToString([]byte(b)) } @@ -324,20 +300,6 @@ func (u *URI) UnmarshalText(data []byte) error { // validation is performed late return nil } -// Scan read a value from a database driver -func (u *URI) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = URI(string(v)) - case string: - *u = URI(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.URI from: %#v", v) - } - - return nil -} - func (u URI) String() string { return string(u) } @@ -388,20 +350,6 @@ func (e *Email) UnmarshalText(data []byte) error { // validation is performed la return nil } -// Scan read a value from a database driver -func (e *Email) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *e = Email(string(v)) - case string: - *e = Email(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.Email from: %#v", v) - } - - return nil -} - func (e Email) String() string { return string(e) } @@ -452,20 +400,6 @@ func (h *Hostname) UnmarshalText(data []byte) error { // validation is performed return nil } -// Scan read a value from a database driver -func (h *Hostname) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *h = Hostname(string(v)) - case string: - *h = Hostname(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.Hostname from: %#v", v) - } - - return nil -} - func (h Hostname) String() string { return string(h) } @@ -516,20 +450,6 @@ func (u *IPv4) UnmarshalText(data []byte) error { // validation is performed lat return nil } -// Scan read a value from a database driver -func (u *IPv4) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = IPv4(string(v)) - case string: - *u = IPv4(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.IPv4 from: %#v", v) - } - - return nil -} - func (u IPv4) String() string { return string(u) } @@ -580,20 +500,6 @@ func (u *IPv6) UnmarshalText(data []byte) error { // validation is performed lat return nil } -// Scan read a value from a database driver -func (u *IPv6) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = IPv6(string(v)) - case string: - *u = IPv6(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.IPv6 from: %#v", v) - } - - return nil -} - func (u IPv6) String() string { return string(u) } @@ -644,20 +550,6 @@ func (u *CIDR) UnmarshalText(data []byte) error { // validation is performed lat return nil } -// Scan read a value from a database driver -func (u *CIDR) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = CIDR(string(v)) - case string: - *u = CIDR(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.CIDR from: %#v", v) - } - - return nil -} - func (u CIDR) String() string { return string(u) } @@ -708,20 +600,6 @@ func (u *MAC) UnmarshalText(data []byte) error { // validation is performed late return nil } -// Scan read a value from a database driver -func (u *MAC) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = MAC(string(v)) - case string: - *u = MAC(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.IPv4 from: %#v", v) - } - - return nil -} - func (u MAC) String() string { return string(u) } @@ -772,20 +650,6 @@ func (u *UUID) UnmarshalText(data []byte) error { // validation is performed lat return nil } -// Scan read a value from a database driver -func (u *UUID) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = UUID(string(v)) - case string: - *u = UUID(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.UUID from: %#v", v) - } - - return nil -} - func (u UUID) String() string { return string(u) } @@ -839,20 +703,6 @@ func (u *UUID3) UnmarshalText(data []byte) error { // validation is performed la return nil } -// Scan read a value from a database driver -func (u *UUID3) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = UUID3(string(v)) - case string: - *u = UUID3(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.UUID3 from: %#v", v) - } - - return nil -} - func (u UUID3) String() string { return string(u) } @@ -906,20 +756,6 @@ func (u *UUID4) UnmarshalText(data []byte) error { // validation is performed la return nil } -// Scan read a value from a database driver -func (u *UUID4) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = UUID4(string(v)) - case string: - *u = UUID4(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.UUID4 from: %#v", v) - } - - return nil -} - func (u UUID4) String() string { return string(u) } @@ -973,20 +809,6 @@ func (u *UUID5) UnmarshalText(data []byte) error { // validation is performed la return nil } -// Scan read a value from a database driver -func (u *UUID5) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = UUID5(string(v)) - case string: - *u = UUID5(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.UUID5 from: %#v", v) - } - - return nil -} - func (u UUID5) String() string { return string(u) } @@ -1040,20 +862,6 @@ func (u *ISBN) UnmarshalText(data []byte) error { // validation is performed lat return nil } -// Scan read a value from a database driver -func (u *ISBN) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = ISBN(string(v)) - case string: - *u = ISBN(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.ISBN from: %#v", v) - } - - return nil -} - func (u ISBN) String() string { return string(u) } @@ -1107,20 +915,6 @@ func (u *ISBN10) UnmarshalText(data []byte) error { // validation is performed l return nil } -// Scan read a value from a database driver -func (u *ISBN10) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = ISBN10(string(v)) - case string: - *u = ISBN10(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.ISBN10 from: %#v", v) - } - - return nil -} - func (u ISBN10) String() string { return string(u) } @@ -1174,20 +968,6 @@ func (u *ISBN13) UnmarshalText(data []byte) error { // validation is performed l return nil } -// Scan read a value from a database driver -func (u *ISBN13) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = ISBN13(string(v)) - case string: - *u = ISBN13(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.ISBN13 from: %#v", v) - } - - return nil -} - func (u ISBN13) String() string { return string(u) } @@ -1241,20 +1021,6 @@ func (u *CreditCard) UnmarshalText(data []byte) error { // validation is perform return nil } -// Scan read a value from a database driver -func (u *CreditCard) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = CreditCard(string(v)) - case string: - *u = CreditCard(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.CreditCard from: %#v", v) - } - - return nil -} - func (u CreditCard) String() string { return string(u) } @@ -1308,20 +1074,6 @@ func (u *SSN) UnmarshalText(data []byte) error { // validation is performed late return nil } -// Scan read a value from a database driver -func (u *SSN) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *u = SSN(string(v)) - case string: - *u = SSN(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.SSN from: %#v", v) - } - - return nil -} - func (u SSN) String() string { return string(u) } @@ -1375,20 +1127,6 @@ func (h *HexColor) UnmarshalText(data []byte) error { // validation is performed return nil } -// Scan read a value from a database driver -func (h *HexColor) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *h = HexColor(string(v)) - case string: - *h = HexColor(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.HexColor from: %#v", v) - } - - return nil -} - func (h HexColor) String() string { return string(h) } @@ -1442,20 +1180,6 @@ func (r *RGBColor) UnmarshalText(data []byte) error { // validation is performed return nil } -// Scan read a value from a database driver -func (r *RGBColor) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *r = RGBColor(string(v)) - case string: - *r = RGBColor(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.RGBColor from: %#v", v) - } - - return nil -} - func (r RGBColor) String() string { return string(r) } @@ -1510,20 +1234,6 @@ func (r *Password) UnmarshalText(data []byte) error { // validation is performed return nil } -// Scan read a value from a database driver -func (r *Password) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - *r = Password(string(v)) - case string: - *r = Password(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.Password from: %#v", v) - } - - return nil -} - func (r Password) String() string { return string(r) } diff --git a/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/duration.go b/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/duration.go index 8fbeb635fb43..04545296bd3e 100644 --- a/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/duration.go +++ b/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/duration.go @@ -119,23 +119,6 @@ func ParseDuration(cand string) (time.Duration, error) { return 0, fmt.Errorf("unable to parse %s as duration", cand) } -// Scan reads a Duration value from database driver type. -func (d *Duration) Scan(raw interface{}) error { - switch v := raw.(type) { - // TODO: case []byte: // ? - case int64: - *d = Duration(v) - case float64: - *d = Duration(int64(v)) - case nil: - *d = Duration(0) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.Duration from: %#v", v) - } - - return nil -} - // String converts this duration to a string func (d Duration) String() string { return time.Duration(d).String() diff --git a/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/time.go b/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/time.go index b2324db052c5..d0fd31a9dbf6 100644 --- a/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/time.go +++ b/vendor/k8s.io/kube-openapi/pkg/validation/strfmt/time.go @@ -16,7 +16,6 @@ package strfmt import ( "encoding/json" - "fmt" "regexp" "strings" "time" @@ -114,25 +113,6 @@ func (t *DateTime) UnmarshalText(text []byte) error { return nil } -// Scan scans a DateTime value from database driver type. -func (t *DateTime) Scan(raw interface{}) error { - // TODO: case int64: and case float64: ? - switch v := raw.(type) { - case []byte: - return t.UnmarshalText(v) - case string: - return t.UnmarshalText([]byte(v)) - case time.Time: - *t = DateTime(v) - case nil: - *t = DateTime{} - default: - return fmt.Errorf("cannot sql.Scan() strfmt.DateTime from: %#v", v) - } - - return nil -} - // MarshalJSON returns the DateTime as JSON func (t DateTime) MarshalJSON() ([]byte, error) { return json.Marshal(time.Time(t).Format(MarshalFormat)) diff --git a/vendor/modules.txt b/vendor/modules.txt index 96ba85c885d9..f7423d38f9aa 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -91,8 +91,8 @@ github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources # github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.4.0 ## explicit; go 1.23.0 github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys -# github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.3.1 -## explicit; go 1.18 +# github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0 +## explicit; go 1.23.0 github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets # github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 ## explicit; go 1.23.0 @@ -112,7 +112,7 @@ github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/internal/shared github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/pageblob github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service -# github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 +# github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c ## explicit; go 1.16 github.com/Azure/go-ansiterm github.com/Azure/go-ansiterm/winterm @@ -145,8 +145,8 @@ github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity github.com/AzureAD/microsoft-authentication-library-for-go/apps/public -# github.com/IBM-Cloud/power-go-client v1.11.0 -## explicit; go 1.22.0 +# github.com/IBM-Cloud/power-go-client v1.12.0 +## explicit; go 1.24.0 github.com/IBM-Cloud/power-go-client/clients/instance github.com/IBM-Cloud/power-go-client/errors github.com/IBM-Cloud/power-go-client/helpers @@ -206,17 +206,19 @@ github.com/IBM-Cloud/power-go-client/power/client/p_cloud_volume_groups github.com/IBM-Cloud/power-go-client/power/client/p_cloud_volume_onboarding github.com/IBM-Cloud/power-go-client/power/client/p_cloud_volumes github.com/IBM-Cloud/power-go-client/power/client/power_edge_router +github.com/IBM-Cloud/power-go-client/power/client/routes github.com/IBM-Cloud/power-go-client/power/client/service_bindings github.com/IBM-Cloud/power-go-client/power/client/service_instances github.com/IBM-Cloud/power-go-client/power/client/snapshots +github.com/IBM-Cloud/power-go-client/power/client/ssh_keys github.com/IBM-Cloud/power-go-client/power/client/storage_types github.com/IBM-Cloud/power-go-client/power/client/swagger_spec github.com/IBM-Cloud/power-go-client/power/client/workspaces github.com/IBM-Cloud/power-go-client/power/models -# github.com/IBM/go-sdk-core/v5 v5.19.1 +# github.com/IBM/go-sdk-core/v5 v5.21.0 ## explicit; go 1.23.0 github.com/IBM/go-sdk-core/v5/core -# github.com/IBM/ibm-cos-sdk-go v1.12.2 +# github.com/IBM/ibm-cos-sdk-go v1.12.3 ## explicit; go 1.23.0 github.com/IBM/ibm-cos-sdk-go/aws github.com/IBM/ibm-cos-sdk-go/aws/arn @@ -259,13 +261,13 @@ github.com/IBM/ibm-cos-sdk-go/private/protocol/xml/xmlutil github.com/IBM/ibm-cos-sdk-go/service/s3 github.com/IBM/ibm-cos-sdk-go/service/s3/s3iface github.com/IBM/ibm-cos-sdk-go/service/s3/s3manager -# github.com/IBM/networking-go-sdk v0.51.4 +# github.com/IBM/networking-go-sdk v0.51.11 ## explicit; go 1.23.2 github.com/IBM/networking-go-sdk/common github.com/IBM/networking-go-sdk/dnsrecordsv1 github.com/IBM/networking-go-sdk/transitgatewayapisv1 github.com/IBM/networking-go-sdk/zonesv1 -# github.com/IBM/platform-services-go-sdk v0.81.0 +# github.com/IBM/platform-services-go-sdk v0.86.1 ## explicit; go 1.23.0 github.com/IBM/platform-services-go-sdk/common github.com/IBM/platform-services-go-sdk/globalcatalogv1 @@ -274,7 +276,7 @@ github.com/IBM/platform-services-go-sdk/iamidentityv1 github.com/IBM/platform-services-go-sdk/iampolicymanagementv1 github.com/IBM/platform-services-go-sdk/resourcecontrollerv2 github.com/IBM/platform-services-go-sdk/resourcemanagerv2 -# github.com/IBM/vpc-go-sdk v0.68.0 +# github.com/IBM/vpc-go-sdk v0.71.1 ## explicit; go 1.23.0 github.com/IBM/vpc-go-sdk/common github.com/IBM/vpc-go-sdk/vpcv1 @@ -520,7 +522,7 @@ github.com/blang/semver # github.com/blang/semver/v4 v4.0.0 ## explicit; go 1.14 github.com/blang/semver/v4 -# github.com/cenkalti/backoff/v5 v5.0.2 +# github.com/cenkalti/backoff/v5 v5.0.3 ## explicit; go 1.23 github.com/cenkalti/backoff/v5 # github.com/cespare/xxhash/v2 v2.3.0 @@ -612,7 +614,7 @@ github.com/dustin/go-humanize github.com/elazarl/goproxy github.com/elazarl/goproxy/internal/http1parser github.com/elazarl/goproxy/internal/signer -# github.com/emicklei/go-restful/v3 v3.12.2 +# github.com/emicklei/go-restful/v3 v3.13.0 ## explicit; go 1.13 github.com/emicklei/go-restful/v3 github.com/emicklei/go-restful/v3/log @@ -639,8 +641,8 @@ github.com/fsnotify/fsnotify/internal # github.com/fxamacker/cbor/v2 v2.9.0 ## explicit; go 1.20 github.com/fxamacker/cbor/v2 -# github.com/gabriel-vasile/mimetype v1.4.8 -## explicit; go 1.20 +# github.com/gabriel-vasile/mimetype v1.4.9 +## explicit; go 1.23.0 github.com/gabriel-vasile/mimetype github.com/gabriel-vasile/mimetype/internal/charset github.com/gabriel-vasile/mimetype/internal/json @@ -670,8 +672,8 @@ github.com/go-logr/stdr # github.com/go-logr/zapr v1.3.0 ## explicit; go 1.18 github.com/go-logr/zapr -# github.com/go-openapi/analysis v0.21.5 -## explicit; go 1.19 +# github.com/go-openapi/analysis v0.23.0 +## explicit; go 1.20 github.com/go-openapi/analysis github.com/go-openapi/analysis/internal/debug github.com/go-openapi/analysis/internal/flatten/normalize @@ -682,18 +684,18 @@ github.com/go-openapi/analysis/internal/flatten/sortref # github.com/go-openapi/errors v0.22.1 ## explicit; go 1.20 github.com/go-openapi/errors -# github.com/go-openapi/jsonpointer v0.21.1 -## explicit; go 1.20 +# github.com/go-openapi/jsonpointer v0.22.4 +## explicit; go 1.24.0 github.com/go-openapi/jsonpointer -# github.com/go-openapi/jsonreference v0.21.0 -## explicit; go 1.20 +# github.com/go-openapi/jsonreference v0.21.4 +## explicit; go 1.24.0 github.com/go-openapi/jsonreference github.com/go-openapi/jsonreference/internal -# github.com/go-openapi/loads v0.21.3 -## explicit; go 1.19 +# github.com/go-openapi/loads v0.22.0 +## explicit; go 1.20 github.com/go-openapi/loads -# github.com/go-openapi/runtime v0.26.2 -## explicit; go 1.19 +# github.com/go-openapi/runtime v0.28.0 +## explicit; go 1.20 github.com/go-openapi/runtime github.com/go-openapi/runtime/client github.com/go-openapi/runtime/logger @@ -703,17 +705,53 @@ github.com/go-openapi/runtime/middleware/header github.com/go-openapi/runtime/middleware/untyped github.com/go-openapi/runtime/security github.com/go-openapi/runtime/yamlpc -# github.com/go-openapi/spec v0.20.12 -## explicit; go 1.19 +# github.com/go-openapi/spec v0.21.0 +## explicit; go 1.20 github.com/go-openapi/spec # github.com/go-openapi/strfmt v0.23.0 ## explicit; go 1.20 github.com/go-openapi/strfmt -# github.com/go-openapi/swag v0.23.1 -## explicit; go 1.20 +# github.com/go-openapi/swag v0.25.4 +## explicit; go 1.24.0 github.com/go-openapi/swag -# github.com/go-openapi/validate v0.22.4 -## explicit; go 1.19 +# github.com/go-openapi/swag/cmdutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/cmdutils +# github.com/go-openapi/swag/conv v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/conv +# github.com/go-openapi/swag/fileutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/fileutils +# github.com/go-openapi/swag/jsonname v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/jsonname +# github.com/go-openapi/swag/jsonutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/jsonutils +github.com/go-openapi/swag/jsonutils/adapters +github.com/go-openapi/swag/jsonutils/adapters/ifaces +github.com/go-openapi/swag/jsonutils/adapters/stdlib/json +# github.com/go-openapi/swag/loading v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/loading +# github.com/go-openapi/swag/mangling v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/mangling +# github.com/go-openapi/swag/netutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/netutils +# github.com/go-openapi/swag/stringutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/stringutils +# github.com/go-openapi/swag/typeutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/typeutils +# github.com/go-openapi/swag/yamlutils v0.25.4 +## explicit; go 1.24.0 +github.com/go-openapi/swag/yamlutils +# github.com/go-openapi/validate v0.24.0 +## explicit; go 1.20 github.com/go-openapi/validate # github.com/go-playground/locales v0.14.1 ## explicit; go 1.17 @@ -777,7 +815,7 @@ github.com/google/cel-go/interpreter github.com/google/cel-go/interpreter/functions github.com/google/cel-go/parser github.com/google/cel-go/parser/gen -# github.com/google/gnostic-models v0.7.0 +# github.com/google/gnostic-models v0.7.1 ## explicit; go 1.22 github.com/google/gnostic-models/compiler github.com/google/gnostic-models/extensions @@ -838,7 +876,7 @@ github.com/googleapis/gax-go/v2/callctx github.com/googleapis/gax-go/v2/internal github.com/googleapis/gax-go/v2/internallog github.com/googleapis/gax-go/v2/internallog/internal -# github.com/gophercloud/gophercloud/v2 v2.4.0 +# github.com/gophercloud/gophercloud/v2 v2.10.0 ## explicit; go 1.22 github.com/gophercloud/gophercloud/v2 # github.com/gorilla/mux v1.8.1 @@ -862,8 +900,8 @@ github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors # github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 ## explicit github.com/grpc-ecosystem/go-grpc-prometheus -# github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 -## explicit; go 1.23.0 +# github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 +## explicit; go 1.24.0 github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options github.com/grpc-ecosystem/grpc-gateway/v2/runtime @@ -883,9 +921,6 @@ github.com/jmespath/go-jmespath # github.com/jonboulle/clockwork v0.5.0 ## explicit; go 1.21 github.com/jonboulle/clockwork -# github.com/josharian/intern v1.0.0 -## explicit; go 1.5 -github.com/josharian/intern # github.com/json-iterator/go v1.1.12 ## explicit; go 1.12 github.com/json-iterator/go @@ -908,11 +943,6 @@ github.com/leodido/go-urn/scim/schema # github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de ## explicit github.com/liggitt/tabwriter -# github.com/mailru/easyjson v0.9.0 -## explicit; go 1.20 -github.com/mailru/easyjson/buffer -github.com/mailru/easyjson/jlexer -github.com/mailru/easyjson/jwriter # github.com/mattn/go-colorable v0.1.14 ## explicit; go 1.18 github.com/mattn/go-colorable @@ -938,7 +968,7 @@ github.com/moby/spdystream/spdy # github.com/moby/sys/user v0.4.0 ## explicit; go 1.17 github.com/moby/sys/user -# github.com/moby/term v0.5.0 +# github.com/moby/term v0.5.2 ## explicit; go 1.18 github.com/moby/term github.com/moby/term/windows @@ -1011,6 +1041,9 @@ github.com/opencontainers/image-spec/specs-go/v1 ## explicit; go 1.19 github.com/opencontainers/selinux/go-selinux github.com/opencontainers/selinux/pkg/pwalkdir +# github.com/openshift-online/ocm-common v0.0.31 +## explicit; go 1.21 +github.com/openshift-online/ocm-common/pkg/resource/validations # github.com/openshift/api v0.0.0-20260304122341-cf5d8996109f ## explicit; go 1.24.0 github.com/openshift/api @@ -1116,8 +1149,8 @@ github.com/openshift/cloud-credential-operator/pkg/apis/cloudcredential/v1 github.com/openshift/cloud-credential-operator/pkg/cmd/provisioning github.com/openshift/cloud-credential-operator/pkg/cmd/provisioning/ibmcloud github.com/openshift/cloud-credential-operator/pkg/ibmcloud -# github.com/openshift/cluster-api-provider-agent/api v0.0.0-20250624174747-899af6573f5f -## explicit; go 1.21 +# github.com/openshift/cluster-api-provider-agent/api v0.0.0-20260120122324-898e638ec7d1 +## explicit; go 1.25 github.com/openshift/cluster-api-provider-agent/api/v1alpha1 github.com/openshift/cluster-api-provider-agent/api/v1beta1 # github.com/openshift/cluster-autoscaler-operator v0.0.1-0.20241204142113-43631b045675 @@ -1240,8 +1273,8 @@ github.com/prometheus/client_model/go ## explicit; go 1.24.0 github.com/prometheus/common/expfmt github.com/prometheus/common/model -# github.com/prometheus/procfs v0.16.1 -## explicit; go 1.23.0 +# github.com/prometheus/procfs v0.19.2 +## explicit; go 1.24.0 github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util @@ -1263,8 +1296,6 @@ github.com/samber/lo github.com/samber/lo/internal/constraints github.com/samber/lo/internal/rand github.com/samber/lo/mutable -# github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 -## explicit; go 1.13 # github.com/shopspring/decimal v1.4.0 ## explicit; go 1.10 github.com/shopspring/decimal @@ -1438,7 +1469,7 @@ go.etcd.io/raft/v3/confchange go.etcd.io/raft/v3/quorum go.etcd.io/raft/v3/raftpb go.etcd.io/raft/v3/tracker -# go.mongodb.org/mongo-driver v1.17.2 +# go.mongodb.org/mongo-driver v1.17.3 ## explicit; go 1.18 go.mongodb.org/mongo-driver/bson go.mongodb.org/mongo-driver/bson/bsoncodec @@ -1480,20 +1511,24 @@ go.opentelemetry.io/otel/semconv/v1.17.0/httpconv go.opentelemetry.io/otel/semconv/v1.20.0 go.opentelemetry.io/otel/semconv/v1.26.0 go.opentelemetry.io/otel/semconv/v1.37.0 +go.opentelemetry.io/otel/semconv/v1.37.0/otelconv go.opentelemetry.io/otel/semconv/v1.37.0/rpcconv go.opentelemetry.io/otel/semconv/v1.39.0 go.opentelemetry.io/otel/semconv/v1.39.0/otelconv -# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 -## explicit; go 1.23.0 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.39.0 +## explicit; go 1.24.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 -## explicit; go 1.23.0 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.39.0 +## explicit; go 1.24.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/counter go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x # go.opentelemetry.io/otel/metric v1.40.0 ## explicit; go 1.24.0 go.opentelemetry.io/otel/metric @@ -1514,7 +1549,7 @@ go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded go.opentelemetry.io/otel/trace/internal/telemetry go.opentelemetry.io/otel/trace/noop -# go.opentelemetry.io/proto/otlp v1.7.1 +# go.opentelemetry.io/proto/otlp v1.9.0 ## explicit; go 1.23.0 go.opentelemetry.io/proto/otlp/collector/trace/v1 go.opentelemetry.io/proto/otlp/common/v1 @@ -1568,8 +1603,8 @@ golang.org/x/crypto/salsa20/salsa golang.org/x/crypto/sha3 golang.org/x/crypto/ssh golang.org/x/crypto/ssh/internal/bcrypt_pbkdf -# golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b -## explicit; go 1.23.0 +# golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 +## explicit; go 1.24.0 golang.org/x/exp/maps golang.org/x/exp/slices # golang.org/x/mod v0.33.0 @@ -1824,7 +1859,7 @@ google.golang.org/protobuf/types/known/fieldmaskpb google.golang.org/protobuf/types/known/structpb google.golang.org/protobuf/types/known/timestamppb google.golang.org/protobuf/types/known/wrapperspb -# gopkg.in/evanphx/json-patch.v4 v4.12.0 +# gopkg.in/evanphx/json-patch.v4 v4.13.0 ## explicit gopkg.in/evanphx/json-patch.v4 # gopkg.in/inf.v0 v0.9.1 @@ -1917,6 +1952,8 @@ k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextension k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1 # k8s.io/apimachinery v0.34.3 ## explicit; go 1.24.0 +k8s.io/apimachinery/pkg/api/apitesting +k8s.io/apimachinery/pkg/api/apitesting/fuzzer k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors k8s.io/apimachinery/pkg/api/meta @@ -1930,6 +1967,7 @@ k8s.io/apimachinery/pkg/api/validate/content k8s.io/apimachinery/pkg/api/validation k8s.io/apimachinery/pkg/api/validation/path k8s.io/apimachinery/pkg/apis/asn1 +k8s.io/apimachinery/pkg/apis/meta/fuzzer k8s.io/apimachinery/pkg/apis/meta/internalversion k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme k8s.io/apimachinery/pkg/apis/meta/internalversion/validation @@ -2155,7 +2193,7 @@ k8s.io/apiserver/plugin/pkg/authorizer/webhook/metrics # k8s.io/autoscaler/vertical-pod-autoscaler v1.3.0 ## explicit; go 1.23.0 k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/autoscaling.k8s.io/v1 -# k8s.io/cli-runtime v0.34.2 +# k8s.io/cli-runtime v0.34.3 ## explicit; go 1.24.0 k8s.io/cli-runtime/pkg/genericclioptions k8s.io/cli-runtime/pkg/genericiooptions @@ -2557,7 +2595,7 @@ k8s.io/component-base/zpages/features k8s.io/component-base/zpages/flagz k8s.io/component-base/zpages/httputil k8s.io/component-base/zpages/statusz -# k8s.io/component-helpers v0.34.2 +# k8s.io/component-helpers v0.34.3 ## explicit; go 1.24.0 k8s.io/component-helpers/resource # k8s.io/csi-translation-lib v0.34.1 @@ -2591,8 +2629,8 @@ k8s.io/kube-aggregator/pkg/apis/apiregistration/v1 k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1 k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/typed/apiregistration/v1 -# k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b -## explicit; go 1.23 +# k8s.io/kube-openapi v0.0.0-20251125145642-4e65d59e963e +## explicit; go 1.23.0 k8s.io/kube-openapi/pkg/builder k8s.io/kube-openapi/pkg/builder3 k8s.io/kube-openapi/pkg/builder3/util @@ -2617,7 +2655,7 @@ k8s.io/kube-openapi/pkg/validation/strfmt/bson # k8s.io/kube-scheduler v0.34.2 ## explicit; go 1.24.0 k8s.io/kube-scheduler/config/v1 -# k8s.io/kubectl v0.34.2 +# k8s.io/kubectl v0.34.3 ## explicit; go 1.24.0 k8s.io/kubectl/pkg/cmd/util k8s.io/kubectl/pkg/drain @@ -2661,7 +2699,7 @@ kubevirt.io/api/core/v1 ## explicit; go 1.23.0 kubevirt.io/containerized-data-importer-api/pkg/apis/core kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1 -# kubevirt.io/controller-lifecycle-operator-sdk/api v0.0.0-20220329064328-f3cc58c6ed90 +# kubevirt.io/controller-lifecycle-operator-sdk/api v0.2.4 ## explicit; go 1.17 kubevirt.io/controller-lifecycle-operator-sdk/api # sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.33.0 @@ -2670,54 +2708,54 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client -# sigs.k8s.io/cluster-api v1.10.4 => github.com/csrwng/cluster-api v1.10.3-0.20251126211330-81cd715cb87e -## explicit; go 1.23.0 -sigs.k8s.io/cluster-api/api/addons/v1beta1 -sigs.k8s.io/cluster-api/api/v1beta1 +# sigs.k8s.io/cluster-api v1.11.5 +## explicit; go 1.24.0 +sigs.k8s.io/cluster-api/api/addons/v1beta2 +sigs.k8s.io/cluster-api/api/core/v1beta1 +sigs.k8s.io/cluster-api/api/core/v1beta2 +sigs.k8s.io/cluster-api/api/ipam/v1beta2 sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3 sigs.k8s.io/cluster-api/errors -sigs.k8s.io/cluster-api/exp/api/v1beta1 -sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1 sigs.k8s.io/cluster-api/feature sigs.k8s.io/cluster-api/util sigs.k8s.io/cluster-api/util/annotations sigs.k8s.io/cluster-api/util/conditions -sigs.k8s.io/cluster-api/util/conditions/v1beta2 -sigs.k8s.io/cluster-api/util/contract +sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1 sigs.k8s.io/cluster-api/util/conversion sigs.k8s.io/cluster-api/util/labels/format sigs.k8s.io/cluster-api/util/patch sigs.k8s.io/cluster-api/util/topology -# sigs.k8s.io/cluster-api-provider-aws/v2 v2.8.2-0.20250820205306-645f38e4c152 -## explicit; go 1.23.1 +# sigs.k8s.io/cluster-api-provider-aws/v2 v2.10.0 +## explicit; go 1.24.0 sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1 sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2 +sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2 sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1 sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2 sigs.k8s.io/cluster-api-provider-aws/v2/feature sigs.k8s.io/cluster-api-provider-aws/v2/iam/api/v1beta1 sigs.k8s.io/cluster-api-provider-aws/v2/pkg/eks sigs.k8s.io/cluster-api-provider-aws/v2/pkg/hash -# sigs.k8s.io/cluster-api-provider-azure v1.21.0 -## explicit; go 1.24.0 +# sigs.k8s.io/cluster-api-provider-azure v1.22.0 +## explicit; go 1.24.6 sigs.k8s.io/cluster-api-provider-azure/api/v1beta1 sigs.k8s.io/cluster-api-provider-azure/feature sigs.k8s.io/cluster-api-provider-azure/util/azure sigs.k8s.io/cluster-api-provider-azure/util/ssh sigs.k8s.io/cluster-api-provider-azure/util/versions sigs.k8s.io/cluster-api-provider-azure/util/webhook -# sigs.k8s.io/cluster-api-provider-gcp v1.10.0 -## explicit; go 1.23.7 +# sigs.k8s.io/cluster-api-provider-gcp v1.11.0 +## explicit; go 1.24.0 sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1 -# sigs.k8s.io/cluster-api-provider-ibmcloud v0.11.0 -## explicit; go 1.23.2 +# sigs.k8s.io/cluster-api-provider-ibmcloud v0.12.0 +## explicit; go 1.24.0 sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1 sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2 -# sigs.k8s.io/cluster-api-provider-kubevirt v0.1.9 -## explicit; go 1.22.0 +# sigs.k8s.io/cluster-api-provider-kubevirt v0.11.1 +## explicit; go 1.24.0 sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1 -# sigs.k8s.io/cluster-api-provider-openstack v0.12.1 -## explicit; go 1.23.0 +# sigs.k8s.io/cluster-api-provider-openstack v0.13.3 +## explicit; go 1.24.0 sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1 sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1 sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/errors @@ -2796,8 +2834,8 @@ sigs.k8s.io/kube-storage-version-migrator/pkg/apis/migration/v1alpha1 sigs.k8s.io/kube-storage-version-migrator/pkg/clients/clientset sigs.k8s.io/kube-storage-version-migrator/pkg/clients/clientset/scheme sigs.k8s.io/kube-storage-version-migrator/pkg/clients/clientset/typed/migration/v1alpha1 -# sigs.k8s.io/kustomize/api v0.20.1 -## explicit; go 1.22.7 +# sigs.k8s.io/kustomize/api v0.21.0 +## explicit; go 1.24.0 sigs.k8s.io/kustomize/api/filters/annotations sigs.k8s.io/kustomize/api/filters/fieldspec sigs.k8s.io/kustomize/api/filters/filtersutil @@ -2842,8 +2880,8 @@ sigs.k8s.io/kustomize/api/provider sigs.k8s.io/kustomize/api/resmap sigs.k8s.io/kustomize/api/resource sigs.k8s.io/kustomize/api/types -# sigs.k8s.io/kustomize/kyaml v0.20.1 -## explicit; go 1.22.7 +# sigs.k8s.io/kustomize/kyaml v0.21.0 +## explicit; go 1.24.0 sigs.k8s.io/kustomize/kyaml/comments sigs.k8s.io/kustomize/kyaml/errors sigs.k8s.io/kustomize/kyaml/ext @@ -2881,7 +2919,7 @@ sigs.k8s.io/randfill/bytesource # sigs.k8s.io/secrets-store-csi-driver v1.4.8 ## explicit; go 1.21 sigs.k8s.io/secrets-store-csi-driver/apis/v1 -# sigs.k8s.io/structured-merge-diff/v6 v6.3.0 +# sigs.k8s.io/structured-merge-diff/v6 v6.3.1 ## explicit; go 1.23 sigs.k8s.io/structured-merge-diff/v6/fieldpath sigs.k8s.io/structured-merge-diff/v6/merge @@ -2895,7 +2933,6 @@ sigs.k8s.io/yaml/goyaml.v2 sigs.k8s.io/yaml/kyaml # github.com/openshift/hypershift/api => ./api # github.com/k-orc/openstack-resource-controller => sigs.k8s.io/cluster-api-provider-openstack/orc v0.0.0-20250113192833-e4f56a2b4f32 -# sigs.k8s.io/cluster-api => github.com/csrwng/cluster-api v1.10.3-0.20251126211330-81cd715cb87e # github.com/golang-jwt/jwt/v4 => github.com/golang-jwt/jwt/v4 v4.5.2 # sigs.k8s.io/controller-runtime => sigs.k8s.io/controller-runtime v0.19.7 # github.com/aws/karpenter-provider-aws => github.com/openshift/aws-karpenter-provider-aws v0.0.0-20260207025257-2e871ee4d207 diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awscluster_conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awscluster_conversion.go index 0e0d8eadde04..805d60856edc 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awscluster_conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awscluster_conversion.go @@ -66,6 +66,10 @@ func (src *AWSCluster) ConvertTo(dstRaw conversion.Hub) error { dst.Status.Bastion.HostAffinity = restored.Status.Bastion.HostAffinity dst.Status.Bastion.HostID = restored.Status.Bastion.HostID dst.Status.Bastion.CapacityReservationPreference = restored.Status.Bastion.CapacityReservationPreference + dst.Status.Bastion.CPUOptions = restored.Status.Bastion.CPUOptions + if restored.Status.Bastion.DynamicHostAllocation != nil { + dst.Status.Bastion.DynamicHostAllocation = restored.Status.Bastion.DynamicHostAllocation + } } dst.Spec.Partition = restored.Spec.Partition diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awscluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awscluster_types.go index ddb1d2cd5a89..0c258d7cf640 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awscluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awscluster_types.go @@ -19,7 +19,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -45,7 +45,7 @@ type AWSClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` // AdditionalTags is an optional set of tags to add to AWS resources managed by the AWS provider, in addition to the // ones added by default. @@ -200,11 +200,11 @@ type AWSLoadBalancerSpec struct { // AWSClusterStatus defines the observed state of AWSCluster. type AWSClusterStatus struct { // +kubebuilder:default=false - Ready bool `json:"ready"` - Network NetworkStatus `json:"networkStatus,omitempty"` - FailureDomains clusterv1.FailureDomains `json:"failureDomains,omitempty"` - Bastion *Instance `json:"bastion,omitempty"` - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Ready bool `json:"ready"` + Network NetworkStatus `json:"networkStatus,omitempty"` + FailureDomains clusterv1beta1.FailureDomains `json:"failureDomains,omitempty"` + Bastion *Instance `json:"bastion,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // S3Bucket defines a supporting S3 bucket for the cluster, currently can be optionally used for Ignition. @@ -254,12 +254,12 @@ type AWSClusterList struct { } // GetConditions returns the observations of the operational state of the AWSCluster resource. -func (r *AWSCluster) GetConditions() clusterv1.Conditions { +func (r *AWSCluster) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSCluster to the predescribed clusterv1.Conditions. -func (r *AWSCluster) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSCluster to the predescribed clusterv1beta1.Conditions. +func (r *AWSCluster) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsclustertemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsclustertemplate_types.go index 07e2cf403902..1b0d1f100fb3 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsclustertemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsclustertemplate_types.go @@ -19,7 +19,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AWSClusterTemplateSpec defines the desired state of AWSClusterTemplate. @@ -58,6 +58,6 @@ type AWSClusterTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta clusterv1.ObjectMeta `json:"metadata,omitempty"` - Spec AWSClusterSpec `json:"spec"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` + Spec AWSClusterSpec `json:"spec"` } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachine_conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachine_conversion.go index e9a9e329a166..6e87547918cb 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachine_conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachine_conversion.go @@ -48,6 +48,10 @@ func (src *AWSMachine) ConvertTo(dstRaw conversion.Hub) error { dst.Spec.HostAffinity = restored.Spec.HostAffinity dst.Spec.CapacityReservationPreference = restored.Spec.CapacityReservationPreference dst.Spec.NetworkInterfaceType = restored.Spec.NetworkInterfaceType + dst.Spec.CPUOptions = restored.Spec.CPUOptions + if restored.Spec.DynamicHostAllocation != nil { + dst.Spec.DynamicHostAllocation = restored.Spec.DynamicHostAllocation + } if restored.Spec.ElasticIPPool != nil { if dst.Spec.ElasticIPPool == nil { dst.Spec.ElasticIPPool = &infrav1.ElasticIPPool{} @@ -60,6 +64,7 @@ func (src *AWSMachine) ConvertTo(dstRaw conversion.Hub) error { } } + dst.Status.DedicatedHost = restored.Status.DedicatedHost return nil } @@ -115,6 +120,10 @@ func (r *AWSMachineTemplate) ConvertTo(dstRaw conversion.Hub) error { dst.Spec.Template.Spec.HostAffinity = restored.Spec.Template.Spec.HostAffinity dst.Spec.Template.Spec.CapacityReservationPreference = restored.Spec.Template.Spec.CapacityReservationPreference dst.Spec.Template.Spec.NetworkInterfaceType = restored.Spec.Template.Spec.NetworkInterfaceType + dst.Spec.Template.Spec.CPUOptions = restored.Spec.Template.Spec.CPUOptions + if restored.Spec.Template.Spec.DynamicHostAllocation != nil { + dst.Spec.Template.Spec.DynamicHostAllocation = restored.Spec.Template.Spec.DynamicHostAllocation + } if restored.Spec.Template.Spec.ElasticIPPool != nil { if dst.Spec.Template.Spec.ElasticIPPool == nil { dst.Spec.Template.Spec.ElasticIPPool = &infrav1.ElasticIPPool{} @@ -127,6 +136,10 @@ func (r *AWSMachineTemplate) ConvertTo(dstRaw conversion.Hub) error { } } + // Restore Status fields that don't exist in v1beta1. + dst.Status.NodeInfo = restored.Status.NodeInfo + dst.Status.Conditions = restored.Status.Conditions + return nil } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachine_types.go index 25a8cb4dcdad..d6bf89d1ea39 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachine_types.go @@ -19,7 +19,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -207,7 +207,7 @@ type AWSMachineStatus struct { Interruptible bool `json:"interruptible,omitempty"` // Addresses contains the AWS instance associated addresses. - Addresses []clusterv1.MachineAddress `json:"addresses,omitempty"` + Addresses []clusterv1beta1.MachineAddress `json:"addresses,omitempty"` // InstanceState is the state of the AWS instance for this machine. // +optional @@ -253,7 +253,7 @@ type AWSMachineStatus struct { // Conditions defines current service state of the AWSMachine. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +kubebuilder:object:root=true @@ -276,12 +276,12 @@ type AWSMachine struct { } // GetConditions returns the observations of the operational state of the AWSMachine resource. -func (r *AWSMachine) GetConditions() clusterv1.Conditions { +func (r *AWSMachine) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSMachine to the predescribed clusterv1.Conditions. -func (r *AWSMachine) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSMachine to the predescribed clusterv1beta1.Conditions. +func (r *AWSMachine) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachinetemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachinetemplate_types.go index 6e86295c6bb0..6e1a98fdbca4 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachinetemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/awsmachinetemplate_types.go @@ -20,7 +20,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AWSMachineTemplateStatus defines a status for an AWSMachineTemplate. @@ -65,7 +65,7 @@ type AWSMachineTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta clusterv1.ObjectMeta `json:"metadata,omitempty"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` // Spec is the specification of the desired behavior of the machine. Spec AWSMachineSpec `json:"spec"` diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/conditions_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/conditions_consts.go index ae5d761df1d1..534471947026 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/conditions_consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/conditions_consts.go @@ -16,19 +16,19 @@ limitations under the License. package v1beta1 -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" +import clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" const ( // PrincipalCredentialRetrievedCondition reports on whether Principal credentials could be retrieved successfully. // A possible scenario, where retrieval is unsuccessful, is when SourcePrincipal is not authorized for assume role. - PrincipalCredentialRetrievedCondition clusterv1.ConditionType = "PrincipalCredentialRetrieved" + PrincipalCredentialRetrievedCondition clusterv1beta1.ConditionType = "PrincipalCredentialRetrieved" // PrincipalCredentialRetrievalFailedReason used when errors occur during identity credential retrieval. PrincipalCredentialRetrievalFailedReason = "PrincipalCredentialRetrievalFailed" // CredentialProviderBuildFailedReason used when errors occur during building providers before trying credential retrieval. //nolint:gosec CredentialProviderBuildFailedReason = "CredentialProviderBuildFailed" // PrincipalUsageAllowedCondition reports on whether Principal and all the nested source identities are allowed to be used in the AWSCluster namespace. - PrincipalUsageAllowedCondition clusterv1.ConditionType = "PrincipalUsageAllowed" + PrincipalUsageAllowedCondition clusterv1beta1.ConditionType = "PrincipalUsageAllowed" // PrincipalUsageUnauthorizedReason used when AWSCluster namespace is not in the identity's allowed namespaces list. PrincipalUsageUnauthorizedReason = "PrincipalUsageUnauthorized" // SourcePrincipalUsageUnauthorizedReason used when AWSCluster is not in the intersection of source identity allowed namespaces @@ -38,7 +38,7 @@ const ( const ( // VpcReadyCondition reports on the successful reconciliation of a VPC. - VpcReadyCondition clusterv1.ConditionType = "VpcReady" + VpcReadyCondition clusterv1beta1.ConditionType = "VpcReady" // VpcCreationStartedReason used when attempting to create a VPC for a managed cluster. // Will not be applied to unmanaged clusters. VpcCreationStartedReason = "VpcCreationStarted" @@ -48,7 +48,7 @@ const ( const ( // SubnetsReadyCondition reports on the successful reconciliation of subnets. - SubnetsReadyCondition clusterv1.ConditionType = "SubnetsReady" + SubnetsReadyCondition clusterv1beta1.ConditionType = "SubnetsReady" // SubnetsReconciliationFailedReason used to report failures while reconciling subnets. SubnetsReconciliationFailedReason = "SubnetsReconciliationFailed" ) @@ -56,7 +56,7 @@ const ( const ( // InternetGatewayReadyCondition reports on the successful reconciliation of internet gateways. // Only applicable to managed clusters. - InternetGatewayReadyCondition clusterv1.ConditionType = "InternetGatewayReady" + InternetGatewayReadyCondition clusterv1beta1.ConditionType = "InternetGatewayReady" // InternetGatewayFailedReason used when errors occur during internet gateway reconciliation. InternetGatewayFailedReason = "InternetGatewayFailed" ) @@ -64,7 +64,7 @@ const ( const ( // EgressOnlyInternetGatewayReadyCondition reports on the successful reconciliation of egress only internet gateways. // Only applicable to managed clusters. - EgressOnlyInternetGatewayReadyCondition clusterv1.ConditionType = "EgressOnlyInternetGatewayReady" + EgressOnlyInternetGatewayReadyCondition clusterv1beta1.ConditionType = "EgressOnlyInternetGatewayReady" // EgressOnlyInternetGatewayFailedReason used when errors occur during egress only internet gateway reconciliation. EgressOnlyInternetGatewayFailedReason = "EgressOnlyInternetGatewayFailed" ) @@ -72,7 +72,7 @@ const ( const ( // NatGatewaysReadyCondition reports successful reconciliation of NAT gateways. // Only applicable to managed clusters. - NatGatewaysReadyCondition clusterv1.ConditionType = "NatGatewaysReady" + NatGatewaysReadyCondition clusterv1beta1.ConditionType = "NatGatewaysReady" // NatGatewaysCreationStartedReason set once when creating new NAT gateways. NatGatewaysCreationStartedReason = "NatGatewaysCreationStarted" // NatGatewaysReconciliationFailedReason used when any errors occur during reconciliation of NAT gateways. @@ -82,7 +82,7 @@ const ( const ( // RouteTablesReadyCondition reports successful reconciliation of route tables. // Only applicable to managed clusters. - RouteTablesReadyCondition clusterv1.ConditionType = "RouteTablesReady" + RouteTablesReadyCondition clusterv1beta1.ConditionType = "RouteTablesReady" // RouteTableReconciliationFailedReason used when any errors occur during reconciliation of route tables. RouteTableReconciliationFailedReason = "RouteTableReconciliationFailed" ) @@ -90,14 +90,14 @@ const ( const ( // SecondaryCidrsReadyCondition reports successful reconciliation of secondary CIDR blocks. // Only applicable to managed clusters. - SecondaryCidrsReadyCondition clusterv1.ConditionType = "SecondaryCidrsReady" + SecondaryCidrsReadyCondition clusterv1beta1.ConditionType = "SecondaryCidrsReady" // SecondaryCidrReconciliationFailedReason used when any errors occur during reconciliation of secondary CIDR blocks. SecondaryCidrReconciliationFailedReason = "SecondaryCidrReconciliationFailed" ) const ( // ClusterSecurityGroupsReadyCondition reports successful reconciliation of security groups. - ClusterSecurityGroupsReadyCondition clusterv1.ConditionType = "ClusterSecurityGroupsReady" + ClusterSecurityGroupsReadyCondition clusterv1beta1.ConditionType = "ClusterSecurityGroupsReady" // ClusterSecurityGroupReconciliationFailedReason used when any errors occur during reconciliation of security groups. ClusterSecurityGroupReconciliationFailedReason = "SecurityGroupReconciliationFailed" ) @@ -105,7 +105,7 @@ const ( const ( // BastionHostReadyCondition reports whether a bastion host is ready. Depending on the configuration, a cluster // may not require a bastion host and this condition will be skipped. - BastionHostReadyCondition clusterv1.ConditionType = "BastionHostReady" + BastionHostReadyCondition clusterv1beta1.ConditionType = "BastionHostReady" // BastionCreationStartedReason used when creating a new bastion host. BastionCreationStartedReason = "BastionCreationStarted" // BastionHostFailedReason used when an error occurs during the creation of a bastion host. @@ -114,7 +114,7 @@ const ( const ( // LoadBalancerReadyCondition reports on whether a control plane load balancer was successfully reconciled. - LoadBalancerReadyCondition clusterv1.ConditionType = "LoadBalancerReady" + LoadBalancerReadyCondition clusterv1beta1.ConditionType = "LoadBalancerReady" // WaitForDNSNameReason used while waiting for a DNS name for the API server to be populated. WaitForDNSNameReason = "WaitForDNSName" // WaitForDNSNameResolveReason used while waiting for DNS name to resolve. @@ -125,7 +125,7 @@ const ( const ( // InstanceReadyCondition reports on current status of the EC2 instance. Ready indicates the instance is in a Running state. - InstanceReadyCondition clusterv1.ConditionType = "InstanceReady" + InstanceReadyCondition clusterv1beta1.ConditionType = "InstanceReady" // InstanceNotFoundReason used when the instance couldn't be retrieved. InstanceNotFoundReason = "InstanceNotFound" @@ -147,7 +147,7 @@ const ( const ( // SecurityGroupsReadyCondition indicates the security groups are up to date on the AWSMachine. - SecurityGroupsReadyCondition clusterv1.ConditionType = "SecurityGroupsReady" + SecurityGroupsReadyCondition clusterv1beta1.ConditionType = "SecurityGroupsReady" // SecurityGroupsFailedReason used when the security groups could not be synced. SecurityGroupsFailedReason = "SecurityGroupsSyncFailed" @@ -158,7 +158,7 @@ const ( // When set to false, severity can be an Error if the subnet is not found or unavailable in the instance's AZ. // Note this is only applicable to control plane machines. // Only applicable to control plane machines. - ELBAttachedCondition clusterv1.ConditionType = "ELBAttached" + ELBAttachedCondition clusterv1beta1.ConditionType = "ELBAttached" // ELBAttachFailedReason used when a control plane node fails to attach to the ELB. ELBAttachFailedReason = "ELBAttachFailed" @@ -168,7 +168,7 @@ const ( const ( // S3BucketReadyCondition indicates an S3 bucket has been created successfully. - S3BucketReadyCondition clusterv1.ConditionType = "S3BucketCreated" + S3BucketReadyCondition clusterv1beta1.ConditionType = "S3BucketCreated" // S3BucketFailedReason is used when any errors occur during reconciliation of an S3 bucket. S3BucketFailedReason = "S3BucketCreationFailed" diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/conversion.go index 6247cfeab1c4..a2a895bfd18e 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/conversion.go @@ -103,3 +103,13 @@ func Convert_v1beta2_S3Bucket_To_v1beta1_S3Bucket(in *v1beta2.S3Bucket, out *S3B func Convert_v1beta2_Ignition_To_v1beta1_Ignition(in *v1beta2.Ignition, out *Ignition, s conversion.Scope) error { return autoConvert_v1beta2_Ignition_To_v1beta1_Ignition(in, out, s) } + +func Convert_v1beta2_AWSMachineStatus_To_v1beta1_AWSMachineStatus(in *v1beta2.AWSMachineStatus, out *AWSMachineStatus, s conversion.Scope) error { + // Note: DedicatedHostID is not present in v1beta1, so it will be dropped during conversion + return autoConvert_v1beta2_AWSMachineStatus_To_v1beta1_AWSMachineStatus(in, out, s) +} + +func Convert_v1beta2_AWSMachineTemplateStatus_To_v1beta1_AWSMachineTemplateStatus(in *v1beta2.AWSMachineTemplateStatus, out *AWSMachineTemplateStatus, s conversion.Scope) error { + // NodeInfo and Conditions fields are ignored (dropped) as they don't exist in v1beta1 + return autoConvert_v1beta2_AWSMachineTemplateStatus_To_v1beta1_AWSMachineTemplateStatus(in, out, s) +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/tags.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/tags.go index a727d39cf427..1d711937a002 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/tags.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/tags.go @@ -24,7 +24,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) // Tags defines a map of tags. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/types.go index fe6510380bef..55ec56b0c7f4 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/types.go @@ -19,7 +19,7 @@ package v1beta1 import ( "k8s.io/apimachinery/pkg/util/sets" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AWSResourceReference is a reference to a specific AWS resource by ID or filters. @@ -165,7 +165,7 @@ type Instance struct { IAMProfile string `json:"iamProfile,omitempty"` // Addresses contains the AWS instance associated addresses. - Addresses []clusterv1.MachineAddress `json:"addresses,omitempty"` + Addresses []clusterv1beta1.MachineAddress `json:"addresses,omitempty"` // The private IPv4 address assigned to the instance. PrivateIP *string `json:"privateIp,omitempty"` diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/zz_generated.conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/zz_generated.conversion.go index 2045a5af767d..44f2227f384d 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/zz_generated.conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/zz_generated.conversion.go @@ -29,7 +29,7 @@ import ( conversion "k8s.io/apimachinery/pkg/conversion" runtime "k8s.io/apimachinery/pkg/runtime" v1beta2 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) func init() { @@ -144,11 +144,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSClusterSpec)(nil), (*AWSClusterSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSClusterSpec_To_v1beta1_AWSClusterSpec(a.(*v1beta2.AWSClusterSpec), b.(*AWSClusterSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*AWSClusterStaticIdentity)(nil), (*v1beta2.AWSClusterStaticIdentity)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_AWSClusterStaticIdentity_To_v1beta2_AWSClusterStaticIdentity(a.(*AWSClusterStaticIdentity), b.(*v1beta2.AWSClusterStaticIdentity), scope) }); err != nil { @@ -244,11 +239,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSLoadBalancerSpec)(nil), (*AWSLoadBalancerSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSLoadBalancerSpec_To_v1beta1_AWSLoadBalancerSpec(a.(*v1beta2.AWSLoadBalancerSpec), b.(*AWSLoadBalancerSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*AWSMachine)(nil), (*v1beta2.AWSMachine)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_AWSMachine_To_v1beta2_AWSMachine(a.(*AWSMachine), b.(*v1beta2.AWSMachine), scope) }); err != nil { @@ -269,26 +259,11 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*AWSMachineSpec)(nil), (*v1beta2.AWSMachineSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_AWSMachineSpec_To_v1beta2_AWSMachineSpec(a.(*AWSMachineSpec), b.(*v1beta2.AWSMachineSpec), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSMachineSpec)(nil), (*AWSMachineSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSMachineSpec_To_v1beta1_AWSMachineSpec(a.(*v1beta2.AWSMachineSpec), b.(*AWSMachineSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*AWSMachineStatus)(nil), (*v1beta2.AWSMachineStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_AWSMachineStatus_To_v1beta2_AWSMachineStatus(a.(*AWSMachineStatus), b.(*v1beta2.AWSMachineStatus), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSMachineStatus)(nil), (*AWSMachineStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSMachineStatus_To_v1beta1_AWSMachineStatus(a.(*v1beta2.AWSMachineStatus), b.(*AWSMachineStatus), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*AWSMachineTemplate)(nil), (*v1beta2.AWSMachineTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_AWSMachineTemplate_To_v1beta2_AWSMachineTemplate(a.(*AWSMachineTemplate), b.(*v1beta2.AWSMachineTemplate), scope) }); err != nil { @@ -334,16 +309,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSMachineTemplateStatus)(nil), (*AWSMachineTemplateStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSMachineTemplateStatus_To_v1beta1_AWSMachineTemplateStatus(a.(*v1beta2.AWSMachineTemplateStatus), b.(*AWSMachineTemplateStatus), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*AWSResourceReference)(nil), (*v1beta2.AWSResourceReference)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta1_AWSResourceReference_To_v1beta2_AWSResourceReference(a.(*AWSResourceReference), b.(*v1beta2.AWSResourceReference), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*v1beta2.AWSResourceReference)(nil), (*AWSResourceReference)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta2_AWSResourceReference_To_v1beta1_AWSResourceReference(a.(*v1beta2.AWSResourceReference), b.(*AWSResourceReference), scope) }); err != nil { @@ -464,61 +429,31 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.IPv6)(nil), (*IPv6)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_IPv6_To_v1beta1_IPv6(a.(*v1beta2.IPv6), b.(*IPv6), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*Ignition)(nil), (*v1beta2.Ignition)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_Ignition_To_v1beta2_Ignition(a.(*Ignition), b.(*v1beta2.Ignition), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.Ignition)(nil), (*Ignition)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_Ignition_To_v1beta1_Ignition(a.(*v1beta2.Ignition), b.(*Ignition), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*IngressRule)(nil), (*v1beta2.IngressRule)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_IngressRule_To_v1beta2_IngressRule(a.(*IngressRule), b.(*v1beta2.IngressRule), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.IngressRule)(nil), (*IngressRule)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_IngressRule_To_v1beta1_IngressRule(a.(*v1beta2.IngressRule), b.(*IngressRule), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*Instance)(nil), (*v1beta2.Instance)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_Instance_To_v1beta2_Instance(a.(*Instance), b.(*v1beta2.Instance), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.Instance)(nil), (*Instance)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_Instance_To_v1beta1_Instance(a.(*v1beta2.Instance), b.(*Instance), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*NetworkSpec)(nil), (*v1beta2.NetworkSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_NetworkSpec_To_v1beta2_NetworkSpec(a.(*NetworkSpec), b.(*v1beta2.NetworkSpec), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.NetworkSpec)(nil), (*NetworkSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_NetworkSpec_To_v1beta1_NetworkSpec(a.(*v1beta2.NetworkSpec), b.(*NetworkSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*NetworkStatus)(nil), (*v1beta2.NetworkStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_NetworkStatus_To_v1beta2_NetworkStatus(a.(*NetworkStatus), b.(*v1beta2.NetworkStatus), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.NetworkStatus)(nil), (*NetworkStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_NetworkStatus_To_v1beta1_NetworkStatus(a.(*v1beta2.NetworkStatus), b.(*NetworkStatus), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*RouteTable)(nil), (*v1beta2.RouteTable)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_RouteTable_To_v1beta2_RouteTable(a.(*RouteTable), b.(*v1beta2.RouteTable), scope) }); err != nil { @@ -534,11 +469,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.S3Bucket)(nil), (*S3Bucket)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_S3Bucket_To_v1beta1_S3Bucket(a.(*v1beta2.S3Bucket), b.(*S3Bucket), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*SecurityGroup)(nil), (*v1beta2.SecurityGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_SecurityGroup_To_v1beta2_SecurityGroup(a.(*SecurityGroup), b.(*v1beta2.SecurityGroup), scope) }); err != nil { @@ -564,21 +494,11 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.SubnetSpec)(nil), (*SubnetSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_SubnetSpec_To_v1beta1_SubnetSpec(a.(*v1beta2.SubnetSpec), b.(*SubnetSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*VPCSpec)(nil), (*v1beta2.VPCSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_VPCSpec_To_v1beta2_VPCSpec(a.(*VPCSpec), b.(*v1beta2.VPCSpec), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.VPCSpec)(nil), (*VPCSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_VPCSpec_To_v1beta1_VPCSpec(a.(*v1beta2.VPCSpec), b.(*VPCSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*Volume)(nil), (*v1beta2.Volume)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_Volume_To_v1beta2_Volume(a.(*Volume), b.(*v1beta2.Volume), scope) }); err != nil { @@ -589,6 +509,96 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } + if err := s.AddConversionFunc((*AWSMachineSpec)(nil), (*v1beta2.AWSMachineSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_AWSMachineSpec_To_v1beta2_AWSMachineSpec(a.(*AWSMachineSpec), b.(*v1beta2.AWSMachineSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*AWSResourceReference)(nil), (*v1beta2.AWSResourceReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_AWSResourceReference_To_v1beta2_AWSResourceReference(a.(*AWSResourceReference), b.(*v1beta2.AWSResourceReference), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClassicELB)(nil), (*v1beta2.LoadBalancer)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClassicELB_To_v1beta2_LoadBalancer(a.(*ClassicELB), b.(*v1beta2.LoadBalancer), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AWSClusterSpec)(nil), (*AWSClusterSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSClusterSpec_To_v1beta1_AWSClusterSpec(a.(*v1beta2.AWSClusterSpec), b.(*AWSClusterSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AWSLoadBalancerSpec)(nil), (*AWSLoadBalancerSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSLoadBalancerSpec_To_v1beta1_AWSLoadBalancerSpec(a.(*v1beta2.AWSLoadBalancerSpec), b.(*AWSLoadBalancerSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AWSMachineSpec)(nil), (*AWSMachineSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSMachineSpec_To_v1beta1_AWSMachineSpec(a.(*v1beta2.AWSMachineSpec), b.(*AWSMachineSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AWSMachineStatus)(nil), (*AWSMachineStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSMachineStatus_To_v1beta1_AWSMachineStatus(a.(*v1beta2.AWSMachineStatus), b.(*AWSMachineStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AWSMachineTemplateStatus)(nil), (*AWSMachineTemplateStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSMachineTemplateStatus_To_v1beta1_AWSMachineTemplateStatus(a.(*v1beta2.AWSMachineTemplateStatus), b.(*AWSMachineTemplateStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.IPv6)(nil), (*IPv6)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_IPv6_To_v1beta1_IPv6(a.(*v1beta2.IPv6), b.(*IPv6), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.Ignition)(nil), (*Ignition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_Ignition_To_v1beta1_Ignition(a.(*v1beta2.Ignition), b.(*Ignition), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.IngressRule)(nil), (*IngressRule)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_IngressRule_To_v1beta1_IngressRule(a.(*v1beta2.IngressRule), b.(*IngressRule), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.Instance)(nil), (*Instance)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_Instance_To_v1beta1_Instance(a.(*v1beta2.Instance), b.(*Instance), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.LoadBalancer)(nil), (*ClassicELB)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_LoadBalancer_To_v1beta1_ClassicELB(a.(*v1beta2.LoadBalancer), b.(*ClassicELB), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.NetworkSpec)(nil), (*NetworkSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_NetworkSpec_To_v1beta1_NetworkSpec(a.(*v1beta2.NetworkSpec), b.(*NetworkSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.NetworkStatus)(nil), (*NetworkStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_NetworkStatus_To_v1beta1_NetworkStatus(a.(*v1beta2.NetworkStatus), b.(*NetworkStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.S3Bucket)(nil), (*S3Bucket)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_S3Bucket_To_v1beta1_S3Bucket(a.(*v1beta2.S3Bucket), b.(*S3Bucket), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.SubnetSpec)(nil), (*SubnetSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_SubnetSpec_To_v1beta1_SubnetSpec(a.(*v1beta2.SubnetSpec), b.(*SubnetSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.VPCSpec)(nil), (*VPCSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_VPCSpec_To_v1beta1_VPCSpec(a.(*v1beta2.VPCSpec), b.(*VPCSpec), scope) + }); err != nil { + return err + } return nil } @@ -615,7 +625,6 @@ func Convert_v1beta2_AMIReference_To_v1beta1_AMIReference(in *v1beta2.AMIReferen } func autoConvert_v1beta1_AWSCluster_To_v1beta2_AWSCluster(in *AWSCluster, out *v1beta2.AWSCluster, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSClusterSpec_To_v1beta2_AWSClusterSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -632,7 +641,6 @@ func Convert_v1beta1_AWSCluster_To_v1beta2_AWSCluster(in *AWSCluster, out *v1bet } func autoConvert_v1beta2_AWSCluster_To_v1beta1_AWSCluster(in *v1beta2.AWSCluster, out *AWSCluster, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSClusterSpec_To_v1beta1_AWSClusterSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -649,7 +657,6 @@ func Convert_v1beta2_AWSCluster_To_v1beta1_AWSCluster(in *v1beta2.AWSCluster, ou } func autoConvert_v1beta1_AWSClusterControllerIdentity_To_v1beta2_AWSClusterControllerIdentity(in *AWSClusterControllerIdentity, out *v1beta2.AWSClusterControllerIdentity, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSClusterControllerIdentitySpec_To_v1beta2_AWSClusterControllerIdentitySpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -663,7 +670,6 @@ func Convert_v1beta1_AWSClusterControllerIdentity_To_v1beta2_AWSClusterControlle } func autoConvert_v1beta2_AWSClusterControllerIdentity_To_v1beta1_AWSClusterControllerIdentity(in *v1beta2.AWSClusterControllerIdentity, out *AWSClusterControllerIdentity, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSClusterControllerIdentitySpec_To_v1beta1_AWSClusterControllerIdentitySpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -677,7 +683,6 @@ func Convert_v1beta2_AWSClusterControllerIdentity_To_v1beta1_AWSClusterControlle } func autoConvert_v1beta1_AWSClusterControllerIdentityList_To_v1beta2_AWSClusterControllerIdentityList(in *AWSClusterControllerIdentityList, out *v1beta2.AWSClusterControllerIdentityList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta out.Items = *(*[]v1beta2.AWSClusterControllerIdentity)(unsafe.Pointer(&in.Items)) return nil @@ -689,7 +694,6 @@ func Convert_v1beta1_AWSClusterControllerIdentityList_To_v1beta2_AWSClusterContr } func autoConvert_v1beta2_AWSClusterControllerIdentityList_To_v1beta1_AWSClusterControllerIdentityList(in *v1beta2.AWSClusterControllerIdentityList, out *AWSClusterControllerIdentityList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta out.Items = *(*[]AWSClusterControllerIdentity)(unsafe.Pointer(&in.Items)) return nil @@ -745,7 +749,6 @@ func Convert_v1beta2_AWSClusterIdentitySpec_To_v1beta1_AWSClusterIdentitySpec(in } func autoConvert_v1beta1_AWSClusterList_To_v1beta2_AWSClusterList(in *AWSClusterList, out *v1beta2.AWSClusterList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -767,7 +770,6 @@ func Convert_v1beta1_AWSClusterList_To_v1beta2_AWSClusterList(in *AWSClusterList } func autoConvert_v1beta2_AWSClusterList_To_v1beta1_AWSClusterList(in *v1beta2.AWSClusterList, out *AWSClusterList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -789,7 +791,6 @@ func Convert_v1beta2_AWSClusterList_To_v1beta1_AWSClusterList(in *v1beta2.AWSClu } func autoConvert_v1beta1_AWSClusterRoleIdentity_To_v1beta2_AWSClusterRoleIdentity(in *AWSClusterRoleIdentity, out *v1beta2.AWSClusterRoleIdentity, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSClusterRoleIdentitySpec_To_v1beta2_AWSClusterRoleIdentitySpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -803,7 +804,6 @@ func Convert_v1beta1_AWSClusterRoleIdentity_To_v1beta2_AWSClusterRoleIdentity(in } func autoConvert_v1beta2_AWSClusterRoleIdentity_To_v1beta1_AWSClusterRoleIdentity(in *v1beta2.AWSClusterRoleIdentity, out *AWSClusterRoleIdentity, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSClusterRoleIdentitySpec_To_v1beta1_AWSClusterRoleIdentitySpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -817,7 +817,6 @@ func Convert_v1beta2_AWSClusterRoleIdentity_To_v1beta1_AWSClusterRoleIdentity(in } func autoConvert_v1beta1_AWSClusterRoleIdentityList_To_v1beta2_AWSClusterRoleIdentityList(in *AWSClusterRoleIdentityList, out *v1beta2.AWSClusterRoleIdentityList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta out.Items = *(*[]v1beta2.AWSClusterRoleIdentity)(unsafe.Pointer(&in.Items)) return nil @@ -829,7 +828,6 @@ func Convert_v1beta1_AWSClusterRoleIdentityList_To_v1beta2_AWSClusterRoleIdentit } func autoConvert_v1beta2_AWSClusterRoleIdentityList_To_v1beta1_AWSClusterRoleIdentityList(in *v1beta2.AWSClusterRoleIdentityList, out *AWSClusterRoleIdentityList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta out.Items = *(*[]AWSClusterRoleIdentity)(unsafe.Pointer(&in.Items)) return nil @@ -954,7 +952,6 @@ func autoConvert_v1beta2_AWSClusterSpec_To_v1beta1_AWSClusterSpec(in *v1beta2.AW } func autoConvert_v1beta1_AWSClusterStaticIdentity_To_v1beta2_AWSClusterStaticIdentity(in *AWSClusterStaticIdentity, out *v1beta2.AWSClusterStaticIdentity, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSClusterStaticIdentitySpec_To_v1beta2_AWSClusterStaticIdentitySpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -968,7 +965,6 @@ func Convert_v1beta1_AWSClusterStaticIdentity_To_v1beta2_AWSClusterStaticIdentit } func autoConvert_v1beta2_AWSClusterStaticIdentity_To_v1beta1_AWSClusterStaticIdentity(in *v1beta2.AWSClusterStaticIdentity, out *AWSClusterStaticIdentity, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSClusterStaticIdentitySpec_To_v1beta1_AWSClusterStaticIdentitySpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -982,7 +978,6 @@ func Convert_v1beta2_AWSClusterStaticIdentity_To_v1beta1_AWSClusterStaticIdentit } func autoConvert_v1beta1_AWSClusterStaticIdentityList_To_v1beta2_AWSClusterStaticIdentityList(in *AWSClusterStaticIdentityList, out *v1beta2.AWSClusterStaticIdentityList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta out.Items = *(*[]v1beta2.AWSClusterStaticIdentity)(unsafe.Pointer(&in.Items)) return nil @@ -994,7 +989,6 @@ func Convert_v1beta1_AWSClusterStaticIdentityList_To_v1beta2_AWSClusterStaticIde } func autoConvert_v1beta2_AWSClusterStaticIdentityList_To_v1beta1_AWSClusterStaticIdentityList(in *v1beta2.AWSClusterStaticIdentityList, out *AWSClusterStaticIdentityList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta out.Items = *(*[]AWSClusterStaticIdentity)(unsafe.Pointer(&in.Items)) return nil @@ -1036,7 +1030,7 @@ func autoConvert_v1beta1_AWSClusterStatus_To_v1beta2_AWSClusterStatus(in *AWSClu if err := Convert_v1beta1_NetworkStatus_To_v1beta2_NetworkStatus(&in.Network, &out.Network, s); err != nil { return err } - out.FailureDomains = *(*apiv1beta1.FailureDomains)(unsafe.Pointer(&in.FailureDomains)) + out.FailureDomains = *(*corev1beta1.FailureDomains)(unsafe.Pointer(&in.FailureDomains)) if in.Bastion != nil { in, out := &in.Bastion, &out.Bastion *out = new(v1beta2.Instance) @@ -1046,7 +1040,7 @@ func autoConvert_v1beta1_AWSClusterStatus_To_v1beta2_AWSClusterStatus(in *AWSClu } else { out.Bastion = nil } - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } @@ -1060,7 +1054,7 @@ func autoConvert_v1beta2_AWSClusterStatus_To_v1beta1_AWSClusterStatus(in *v1beta if err := Convert_v1beta2_NetworkStatus_To_v1beta1_NetworkStatus(&in.Network, &out.Network, s); err != nil { return err } - out.FailureDomains = *(*apiv1beta1.FailureDomains)(unsafe.Pointer(&in.FailureDomains)) + out.FailureDomains = *(*corev1beta1.FailureDomains)(unsafe.Pointer(&in.FailureDomains)) if in.Bastion != nil { in, out := &in.Bastion, &out.Bastion *out = new(Instance) @@ -1070,7 +1064,7 @@ func autoConvert_v1beta2_AWSClusterStatus_To_v1beta1_AWSClusterStatus(in *v1beta } else { out.Bastion = nil } - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } @@ -1080,7 +1074,6 @@ func Convert_v1beta2_AWSClusterStatus_To_v1beta1_AWSClusterStatus(in *v1beta2.AW } func autoConvert_v1beta1_AWSClusterTemplate_To_v1beta2_AWSClusterTemplate(in *AWSClusterTemplate, out *v1beta2.AWSClusterTemplate, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSClusterTemplateSpec_To_v1beta2_AWSClusterTemplateSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -1094,7 +1087,6 @@ func Convert_v1beta1_AWSClusterTemplate_To_v1beta2_AWSClusterTemplate(in *AWSClu } func autoConvert_v1beta2_AWSClusterTemplate_To_v1beta1_AWSClusterTemplate(in *v1beta2.AWSClusterTemplate, out *AWSClusterTemplate, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSClusterTemplateSpec_To_v1beta1_AWSClusterTemplateSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -1108,7 +1100,6 @@ func Convert_v1beta2_AWSClusterTemplate_To_v1beta1_AWSClusterTemplate(in *v1beta } func autoConvert_v1beta1_AWSClusterTemplateList_To_v1beta2_AWSClusterTemplateList(in *AWSClusterTemplateList, out *v1beta2.AWSClusterTemplateList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -1130,7 +1121,6 @@ func Convert_v1beta1_AWSClusterTemplateList_To_v1beta2_AWSClusterTemplateList(in } func autoConvert_v1beta2_AWSClusterTemplateList_To_v1beta1_AWSClusterTemplateList(in *v1beta2.AWSClusterTemplateList, out *AWSClusterTemplateList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -1255,7 +1245,6 @@ func autoConvert_v1beta2_AWSLoadBalancerSpec_To_v1beta1_AWSLoadBalancerSpec(in * } func autoConvert_v1beta1_AWSMachine_To_v1beta2_AWSMachine(in *AWSMachine, out *v1beta2.AWSMachine, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSMachineSpec_To_v1beta2_AWSMachineSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -1272,7 +1261,6 @@ func Convert_v1beta1_AWSMachine_To_v1beta2_AWSMachine(in *AWSMachine, out *v1bet } func autoConvert_v1beta2_AWSMachine_To_v1beta1_AWSMachine(in *v1beta2.AWSMachine, out *AWSMachine, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSMachineSpec_To_v1beta1_AWSMachineSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -1289,7 +1277,6 @@ func Convert_v1beta2_AWSMachine_To_v1beta1_AWSMachine(in *v1beta2.AWSMachine, ou } func autoConvert_v1beta1_AWSMachineList_To_v1beta2_AWSMachineList(in *AWSMachineList, out *v1beta2.AWSMachineList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -1311,7 +1298,6 @@ func Convert_v1beta1_AWSMachineList_To_v1beta2_AWSMachineList(in *AWSMachineList } func autoConvert_v1beta2_AWSMachineList_To_v1beta1_AWSMachineList(in *v1beta2.AWSMachineList, out *AWSMachineList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -1399,6 +1385,7 @@ func autoConvert_v1beta2_AWSMachineSpec_To_v1beta1_AWSMachineSpec(in *v1beta2.AW out.ImageLookupOrg = in.ImageLookupOrg out.ImageLookupBaseOS = in.ImageLookupBaseOS out.InstanceType = in.InstanceType + // WARNING: in.CPUOptions requires manual conversion: does not exist in peer-type out.AdditionalTags = *(*Tags)(unsafe.Pointer(&in.AdditionalTags)) out.IAMInstanceProfile = in.IAMInstanceProfile out.PublicIP = (*bool)(unsafe.Pointer(in.PublicIP)) @@ -1451,6 +1438,7 @@ func autoConvert_v1beta2_AWSMachineSpec_To_v1beta1_AWSMachineSpec(in *v1beta2.AW // WARNING: in.MarketType requires manual conversion: does not exist in peer-type // WARNING: in.HostID requires manual conversion: does not exist in peer-type // WARNING: in.HostAffinity requires manual conversion: does not exist in peer-type + // WARNING: in.DynamicHostAllocation requires manual conversion: does not exist in peer-type // WARNING: in.CapacityReservationPreference requires manual conversion: does not exist in peer-type return nil } @@ -1458,11 +1446,11 @@ func autoConvert_v1beta2_AWSMachineSpec_To_v1beta1_AWSMachineSpec(in *v1beta2.AW func autoConvert_v1beta1_AWSMachineStatus_To_v1beta2_AWSMachineStatus(in *AWSMachineStatus, out *v1beta2.AWSMachineStatus, s conversion.Scope) error { out.Ready = in.Ready out.Interruptible = in.Interruptible - out.Addresses = *(*[]apiv1beta1.MachineAddress)(unsafe.Pointer(&in.Addresses)) + out.Addresses = *(*[]corev1beta1.MachineAddress)(unsafe.Pointer(&in.Addresses)) out.InstanceState = (*v1beta2.InstanceState)(unsafe.Pointer(in.InstanceState)) out.FailureReason = (*string)(unsafe.Pointer(in.FailureReason)) out.FailureMessage = (*string)(unsafe.Pointer(in.FailureMessage)) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } @@ -1474,21 +1462,16 @@ func Convert_v1beta1_AWSMachineStatus_To_v1beta2_AWSMachineStatus(in *AWSMachine func autoConvert_v1beta2_AWSMachineStatus_To_v1beta1_AWSMachineStatus(in *v1beta2.AWSMachineStatus, out *AWSMachineStatus, s conversion.Scope) error { out.Ready = in.Ready out.Interruptible = in.Interruptible - out.Addresses = *(*[]apiv1beta1.MachineAddress)(unsafe.Pointer(&in.Addresses)) + out.Addresses = *(*[]corev1beta1.MachineAddress)(unsafe.Pointer(&in.Addresses)) out.InstanceState = (*InstanceState)(unsafe.Pointer(in.InstanceState)) out.FailureReason = (*string)(unsafe.Pointer(in.FailureReason)) out.FailureMessage = (*string)(unsafe.Pointer(in.FailureMessage)) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + // WARNING: in.DedicatedHost requires manual conversion: does not exist in peer-type return nil } -// Convert_v1beta2_AWSMachineStatus_To_v1beta1_AWSMachineStatus is an autogenerated conversion function. -func Convert_v1beta2_AWSMachineStatus_To_v1beta1_AWSMachineStatus(in *v1beta2.AWSMachineStatus, out *AWSMachineStatus, s conversion.Scope) error { - return autoConvert_v1beta2_AWSMachineStatus_To_v1beta1_AWSMachineStatus(in, out, s) -} - func autoConvert_v1beta1_AWSMachineTemplate_To_v1beta2_AWSMachineTemplate(in *AWSMachineTemplate, out *v1beta2.AWSMachineTemplate, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSMachineTemplateSpec_To_v1beta2_AWSMachineTemplateSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -1505,7 +1488,6 @@ func Convert_v1beta1_AWSMachineTemplate_To_v1beta2_AWSMachineTemplate(in *AWSMac } func autoConvert_v1beta2_AWSMachineTemplate_To_v1beta1_AWSMachineTemplate(in *v1beta2.AWSMachineTemplate, out *AWSMachineTemplate, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSMachineTemplateSpec_To_v1beta1_AWSMachineTemplateSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -1522,7 +1504,6 @@ func Convert_v1beta2_AWSMachineTemplate_To_v1beta1_AWSMachineTemplate(in *v1beta } func autoConvert_v1beta1_AWSMachineTemplateList_To_v1beta2_AWSMachineTemplateList(in *AWSMachineTemplateList, out *v1beta2.AWSMachineTemplateList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -1544,7 +1525,6 @@ func Convert_v1beta1_AWSMachineTemplateList_To_v1beta2_AWSMachineTemplateList(in } func autoConvert_v1beta2_AWSMachineTemplateList_To_v1beta1_AWSMachineTemplateList(in *v1beta2.AWSMachineTemplateList, out *AWSMachineTemplateList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -1627,14 +1607,11 @@ func Convert_v1beta1_AWSMachineTemplateStatus_To_v1beta2_AWSMachineTemplateStatu func autoConvert_v1beta2_AWSMachineTemplateStatus_To_v1beta1_AWSMachineTemplateStatus(in *v1beta2.AWSMachineTemplateStatus, out *AWSMachineTemplateStatus, s conversion.Scope) error { out.Capacity = *(*v1.ResourceList)(unsafe.Pointer(&in.Capacity)) + // WARNING: in.NodeInfo requires manual conversion: does not exist in peer-type + // WARNING: in.Conditions requires manual conversion: does not exist in peer-type return nil } -// Convert_v1beta2_AWSMachineTemplateStatus_To_v1beta1_AWSMachineTemplateStatus is an autogenerated conversion function. -func Convert_v1beta2_AWSMachineTemplateStatus_To_v1beta1_AWSMachineTemplateStatus(in *v1beta2.AWSMachineTemplateStatus, out *AWSMachineTemplateStatus, s conversion.Scope) error { - return autoConvert_v1beta2_AWSMachineTemplateStatus_To_v1beta1_AWSMachineTemplateStatus(in, out, s) -} - func autoConvert_v1beta1_AWSResourceReference_To_v1beta2_AWSResourceReference(in *AWSResourceReference, out *v1beta2.AWSResourceReference, s conversion.Scope) error { out.ID = (*string)(unsafe.Pointer(in.ID)) // WARNING: in.ARN requires manual conversion: does not exist in peer-type @@ -2008,7 +1985,7 @@ func autoConvert_v1beta1_Instance_To_v1beta2_Instance(in *Instance, out *v1beta2 out.SecurityGroupIDs = *(*[]string)(unsafe.Pointer(&in.SecurityGroupIDs)) out.UserData = (*string)(unsafe.Pointer(in.UserData)) out.IAMProfile = in.IAMProfile - out.Addresses = *(*[]apiv1beta1.MachineAddress)(unsafe.Pointer(&in.Addresses)) + out.Addresses = *(*[]corev1beta1.MachineAddress)(unsafe.Pointer(&in.Addresses)) out.PrivateIP = (*string)(unsafe.Pointer(in.PrivateIP)) out.PublicIP = (*string)(unsafe.Pointer(in.PublicIP)) out.ENASupport = (*bool)(unsafe.Pointer(in.ENASupport)) @@ -2039,7 +2016,7 @@ func autoConvert_v1beta2_Instance_To_v1beta1_Instance(in *v1beta2.Instance, out out.SecurityGroupIDs = *(*[]string)(unsafe.Pointer(&in.SecurityGroupIDs)) out.UserData = (*string)(unsafe.Pointer(in.UserData)) out.IAMProfile = in.IAMProfile - out.Addresses = *(*[]apiv1beta1.MachineAddress)(unsafe.Pointer(&in.Addresses)) + out.Addresses = *(*[]corev1beta1.MachineAddress)(unsafe.Pointer(&in.Addresses)) out.PrivateIP = (*string)(unsafe.Pointer(in.PrivateIP)) out.PublicIP = (*string)(unsafe.Pointer(in.PublicIP)) out.ENASupport = (*bool)(unsafe.Pointer(in.ENASupport)) @@ -2062,7 +2039,9 @@ func autoConvert_v1beta2_Instance_To_v1beta1_Instance(in *v1beta2.Instance, out // WARNING: in.MarketType requires manual conversion: does not exist in peer-type // WARNING: in.HostAffinity requires manual conversion: does not exist in peer-type // WARNING: in.HostID requires manual conversion: does not exist in peer-type + // WARNING: in.DynamicHostAllocation requires manual conversion: does not exist in peer-type // WARNING: in.CapacityReservationPreference requires manual conversion: does not exist in peer-type + // WARNING: in.CPUOptions requires manual conversion: does not exist in peer-type return nil } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/zz_generated.deepcopy.go index b3f9c154cf4b..28f0fe8907a7 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1/zz_generated.deepcopy.go @@ -23,7 +23,7 @@ package v1beta1 import ( "k8s.io/api/core/v1" runtime "k8s.io/apimachinery/pkg/runtime" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -409,7 +409,7 @@ func (in *AWSClusterStatus) DeepCopyInto(out *AWSClusterStatus) { in.Network.DeepCopyInto(&out.Network) if in.FailureDomains != nil { in, out := &in.FailureDomains, &out.FailureDomains - *out = make(apiv1beta1.FailureDomains, len(*in)) + *out = make(corev1beta1.FailureDomains, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -421,7 +421,7 @@ func (in *AWSClusterStatus) DeepCopyInto(out *AWSClusterStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -741,7 +741,7 @@ func (in *AWSMachineStatus) DeepCopyInto(out *AWSMachineStatus) { *out = *in if in.Addresses != nil { in, out := &in.Addresses, &out.Addresses - *out = make([]apiv1beta1.MachineAddress, len(*in)) + *out = make([]corev1beta1.MachineAddress, len(*in)) copy(*out, *in) } if in.InstanceState != nil { @@ -761,7 +761,7 @@ func (in *AWSMachineStatus) DeepCopyInto(out *AWSMachineStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -1305,7 +1305,7 @@ func (in *Instance) DeepCopyInto(out *Instance) { } if in.Addresses != nil { in, out := &in.Addresses, &out.Addresses - *out = make([]apiv1beta1.MachineAddress, len(*in)) + *out = make([]corev1beta1.MachineAddress, len(*in)) copy(*out, *in) } if in.PrivateIP != nil { diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awscluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awscluster_types.go index 213ad99c56a9..184ef9de4317 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awscluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awscluster_types.go @@ -19,7 +19,7 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -49,7 +49,7 @@ type AWSClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` // AdditionalTags is an optional set of tags to add to AWS resources managed by the AWS provider, in addition to the // ones added by default. @@ -276,11 +276,11 @@ type AdditionalListenerSpec struct { // AWSClusterStatus defines the observed state of AWSCluster. type AWSClusterStatus struct { // +kubebuilder:default=false - Ready bool `json:"ready"` - Network NetworkStatus `json:"networkStatus,omitempty"` - FailureDomains clusterv1.FailureDomains `json:"failureDomains,omitempty"` - Bastion *Instance `json:"bastion,omitempty"` - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Ready bool `json:"ready"` + Network NetworkStatus `json:"networkStatus,omitempty"` + FailureDomains clusterv1beta1.FailureDomains `json:"failureDomains,omitempty"` + Bastion *Instance `json:"bastion,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // S3Bucket defines a supporting S3 bucket for the cluster, currently can be optionally used for Ignition. @@ -346,12 +346,12 @@ type AWSClusterList struct { } // GetConditions returns the observations of the operational state of the AWSCluster resource. -func (r *AWSCluster) GetConditions() clusterv1.Conditions { +func (r *AWSCluster) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSCluster to the predescribed clusterv1.Conditions. -func (r *AWSCluster) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSCluster to the predescribed clusterv1beta1.Conditions. +func (r *AWSCluster) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awscluster_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awscluster_webhook.go index ec4fac40afc1..ddef7446bf11 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awscluster_webhook.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awscluster_webhook.go @@ -30,7 +30,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/cluster-api/util/annotations" ) @@ -130,7 +130,7 @@ func (*awsClusterWebhook) ValidateUpdate(_ context.Context, oldObj, newObj runti allErrs = append(allErrs, r.validateControlPlaneLoadBalancerUpdate(oldLB, newLB)...) } - if !cmp.Equal(oldC.Spec.ControlPlaneEndpoint, clusterv1.APIEndpoint{}) && + if !cmp.Equal(oldC.Spec.ControlPlaneEndpoint, clusterv1beta1.APIEndpoint{}) && !cmp.Equal(r.Spec.ControlPlaneEndpoint, oldC.Spec.ControlPlaneEndpoint) { allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "controlPlaneEndpoint"), r.Spec.ControlPlaneEndpoint, "field is immutable"), diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsclustertemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsclustertemplate_types.go index e0a827fa3dd1..2f81400eef21 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsclustertemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsclustertemplate_types.go @@ -19,7 +19,7 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AWSClusterTemplateSpec defines the desired state of AWSClusterTemplate. @@ -59,6 +59,6 @@ type AWSClusterTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta clusterv1.ObjectMeta `json:"metadata,omitempty"` - Spec AWSClusterSpec `json:"spec"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` + Spec AWSClusterSpec `json:"spec"` } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachine_types.go index 16f85dbe15b7..2ff52d71e076 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachine_types.go @@ -19,7 +19,7 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -116,6 +116,11 @@ type AWSMachineSpec struct { // +kubebuilder:validation:MinLength:=2 InstanceType string `json:"instanceType"` + // CPUOptions defines CPU-related settings for the instance, including the confidential computing policy. + // When omitted, this means no opinion and the AWS platform is left to choose a reasonable default. + // +optional + CPUOptions CPUOptions `json:"cpuOptions,omitempty,omitzero"` + // AdditionalTags is an optional set of tags to add to an instance, in addition to the ones added by default by the // AWS provider. If both the AWSCluster and the AWSMachine specify the same tag name with different values, the // AWSMachine's value takes precedence. @@ -213,6 +218,10 @@ type AWSMachineSpec struct { PlacementGroupPartition int64 `json:"placementGroupPartition,omitempty"` // Tenancy indicates if instance should run on shared or single-tenant hardware. + // When Tenancy=host, AWS will attempt to find a suitable host from: + // - Preexisting allocated hosts that have auto-placement enabled + // - A specific host ID, if configured + // - Allocating a new dedicated host if DynamicHostAllocation is configured // +optional // +kubebuilder:validation:Enum:=default;dedicated;host Tenancy string `json:"tenancy,omitempty"` @@ -235,26 +244,45 @@ type AWSMachineSpec struct { MarketType MarketType `json:"marketType,omitempty"` // HostID specifies the Dedicated Host on which the instance must be started. + // This field is mutually exclusive with DynamicHostAllocation. + // +kubebuilder:validation:Pattern=`^h-[0-9a-f]{17}$` + // +kubebuilder:validation:MaxLength=19 // +optional HostID *string `json:"hostID,omitempty"` // HostAffinity specifies the dedicated host affinity setting for the instance. - // When hostAffinity is set to host, an instance started onto a specific host always restarts on the same host if stopped. - // When hostAffinity is set to default, and you stop and restart the instance, it can be restarted on any available host. + // When HostAffinity is set to host, an instance started onto a specific host always restarts on the same host if stopped. + // When HostAffinity is set to default, and you stop and restart the instance, it can be restarted on any available host. // When HostAffinity is defined, HostID is required. // +optional // +kubebuilder:validation:Enum:=default;host + // +kubebuilder:default=host HostAffinity *string `json:"hostAffinity,omitempty"` + // DynamicHostAllocation enables automatic allocation of a single dedicated host. + // This field is mutually exclusive with HostID and always allocates exactly one host. + // Cost effectiveness of allocating a single instance on a dedicated host may vary + // depending on the instance type and the region. + // +optional + DynamicHostAllocation *DynamicHostAllocationSpec `json:"dynamicHostAllocation,omitempty"` + // CapacityReservationPreference specifies the preference for use of Capacity Reservations by the instance. Valid values include: // "Open": The instance may make use of open Capacity Reservations that match its AZ and InstanceType // "None": The instance may not make use of any Capacity Reservations. This is to conserve open reservations for desired workloads - // "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation + // "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation. Note that this is incompatible with a MarketType of `Spot` // +kubebuilder:validation:Enum="";None;CapacityReservationsOnly;Open // +optional CapacityReservationPreference CapacityReservationPreference `json:"capacityReservationPreference,omitempty"` } +// DynamicHostAllocationSpec defines the configuration for dynamic dedicated host allocation. +// This specification always allocates exactly one dedicated host per machine. +type DynamicHostAllocationSpec struct { + // Tags to apply to the allocated dedicated host. + // +optional + Tags map[string]string `json:"tags,omitempty"` +} + // CloudInit defines options related to the bootstrapping systems where // CloudInit is used. type CloudInit struct { @@ -286,9 +314,10 @@ type CloudInit struct { // For more information on Ignition configuration, see https://coreos.github.io/butane/specs/ type Ignition struct { // Version defines which version of Ignition will be used to generate bootstrap data. + // Defaults to `2.3` if storageType is set to `ClusterObjectStore`. + // It will be ignored if storageType is set to `UnencryptedUserData`, as the userdata defines its own version. // // +optional - // +kubebuilder:default="2.3" // +kubebuilder:validation:Enum="2.3";"3.0";"3.1";"3.2";"3.3";"3.4" Version string `json:"version,omitempty"` @@ -385,7 +414,7 @@ type AWSMachineStatus struct { Interruptible bool `json:"interruptible,omitempty"` // Addresses contains the AWS instance associated addresses. - Addresses []clusterv1.MachineAddress `json:"addresses,omitempty"` + Addresses []clusterv1beta1.MachineAddress `json:"addresses,omitempty"` // InstanceState is the state of the AWS instance for this machine. // +optional @@ -431,7 +460,21 @@ type AWSMachineStatus struct { // Conditions defines current service state of the AWSMachine. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` + + // DedicatedHost tracks the dynamically allocated dedicated host. + // This field is populated when DynamicHostAllocation is used. + // +optional + DedicatedHost *DedicatedHostStatus `json:"dedicatedHost,omitempty"` +} + +// DedicatedHostStatus defines the observed state of a dynamically allocated dedicated host +// associated with an AWSMachine. This struct is used to track the ID of the dedicated host. +type DedicatedHostStatus struct { + // ID tracks the dynamically allocated dedicated host ID. + // This field is populated when DynamicHostAllocation is used. + // +optional + ID *string `json:"id,omitempty"` } // +kubebuilder:object:root=true @@ -455,12 +498,12 @@ type AWSMachine struct { } // GetConditions returns the observations of the operational state of the AWSMachine resource. -func (r *AWSMachine) GetConditions() clusterv1.Conditions { +func (r *AWSMachine) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSMachine to the predescribed clusterv1.Conditions. -func (r *AWSMachine) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSMachine to the predescribed clusterv1beta1.Conditions. +func (r *AWSMachine) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachine_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachine_webhook.go index ae905fcdd28f..9c271c69392f 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachine_webhook.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachine_webhook.go @@ -75,11 +75,11 @@ func (*awsMachineWebhook) ValidateCreate(_ context.Context, obj runtime.Object) allErrs = append(allErrs, r.validateNonRootVolumes()...) allErrs = append(allErrs, r.validateSSHKeyName()...) allErrs = append(allErrs, r.validateAdditionalSecurityGroups()...) - allErrs = append(allErrs, r.validateHostAffinity()...) allErrs = append(allErrs, r.Spec.AdditionalTags.Validate()...) allErrs = append(allErrs, r.validateNetworkElasticIPPool()...) allErrs = append(allErrs, r.validateInstanceMarketType()...) allErrs = append(allErrs, r.validateCapacityReservation()...) + allErrs = append(allErrs, r.validateHostAllocation()...) return nil, aggregateObjErrors(r.GroupVersionKind().GroupKind(), r.Name, allErrs) } @@ -109,7 +109,7 @@ func (*awsMachineWebhook) ValidateUpdate(ctx context.Context, oldObj, newObj run allErrs = append(allErrs, r.validateCloudInitSecret()...) allErrs = append(allErrs, r.validateAdditionalSecurityGroups()...) allErrs = append(allErrs, r.Spec.AdditionalTags.Validate()...) - allErrs = append(allErrs, r.validateHostAffinity()...) + allErrs = append(allErrs, r.validateHostAllocation()...) newAWSMachineSpec := newAWSMachine["spec"].(map[string]interface{}) oldAWSMachineSpec := oldAWSMachine["spec"].(map[string]interface{}) @@ -384,7 +384,13 @@ func (r *AWSMachine) validateNetworkElasticIPPool() field.ErrorList { func (r *AWSMachine) validateCapacityReservation() field.ErrorList { var allErrs field.ErrorList if r.Spec.CapacityReservationID != nil && r.Spec.CapacityReservationPreference != CapacityReservationPreferenceOnly && r.Spec.CapacityReservationPreference != "" { - allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "capacityReservationPreference"), "when a reservation ID is specified, capacityReservationPreference may only be `capacity-reservations-only` or empty")) + allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "capacityReservationPreference"), "when capacityReservationId is specified, capacityReservationPreference may only be 'CapacityReservationsOnly' or empty")) + } + if r.Spec.CapacityReservationPreference == CapacityReservationPreferenceOnly && r.Spec.MarketType == MarketTypeSpot { + allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "capacityReservationPreference"), "when marketType is set to 'Spot', capacityReservationPreference cannot be set to 'CapacityReservationsOnly'")) + } + if r.Spec.CapacityReservationPreference == CapacityReservationPreferenceOnly && r.Spec.SpotMarketOptions != nil { + allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "capacityReservationPreference"), "when capacityReservationPreference is 'CapacityReservationsOnly', spotMarketOptions cannot be set (which implies marketType: 'Spot')")) } return allErrs } @@ -445,12 +451,14 @@ func (*awsMachineWebhook) Default(_ context.Context, obj runtime.Object) error { r.Spec.CloudInit.SecureSecretsBackend = SecretBackendSecretsManager } - if r.ignitionEnabled() && r.Spec.Ignition.Version == "" { - r.Spec.Ignition.Version = DefaultIgnitionVersion - } if r.ignitionEnabled() && r.Spec.Ignition.StorageType == "" { r.Spec.Ignition.StorageType = DefaultIgnitionStorageType } + // Defaults the version field if StorageType is not set to `UnencryptedUserData`. + // When using `UnencryptedUserData` the version field is ignored because the userdata defines its version itself. + if r.ignitionEnabled() && r.Spec.Ignition.Version == "" && r.Spec.Ignition.StorageType != IgnitionStorageTypeOptionUnencryptedUserData { + r.Spec.Ignition.Version = DefaultIgnitionVersion + } return nil } @@ -466,14 +474,17 @@ func (r *AWSMachine) validateAdditionalSecurityGroups() field.ErrorList { return allErrs } -func (r *AWSMachine) validateHostAffinity() field.ErrorList { +func (r *AWSMachine) validateHostAllocation() field.ErrorList { var allErrs field.ErrorList - if r.Spec.HostAffinity != nil { - if r.Spec.HostID == nil || len(*r.Spec.HostID) == 0 { - allErrs = append(allErrs, field.Required(field.NewPath("spec.hostID"), "hostID must be set when hostAffinity is configured")) - } + // Check if both hostID and dynamicHostAllocation are specified + hasHostID := r.Spec.HostID != nil && len(*r.Spec.HostID) > 0 + hasDynamicHostAllocation := r.Spec.DynamicHostAllocation != nil + + if hasHostID && hasDynamicHostAllocation { + allErrs = append(allErrs, field.Forbidden(field.NewPath("spec.hostID"), "hostID and dynamicHostAllocation are mutually exclusive"), field.Forbidden(field.NewPath("spec.dynamicHostAllocation"), "hostID and dynamicHostAllocation are mutually exclusive")) } + return allErrs } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachinetemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachinetemplate_types.go index 50d8dda22d30..12829090f2fa 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachinetemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachinetemplate_types.go @@ -20,9 +20,45 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) +// Architecture represents the CPU architecture of the node. +// Its underlying type is a string and its value can be any of amd64, arm64. +type Architecture string + +// Architecture constants. +const ( + ArchitectureAmd64 Architecture = "amd64" + ArchitectureArm64 Architecture = "arm64" +) + +// OperatingSystem represents the operating system of the node. +// Its underlying type is a string and its value can be any of linux, windows. +type OperatingSystem string + +// Operating system constants. +const ( + // OperatingSystemLinux represents the Linux operating system. + OperatingSystemLinux OperatingSystem = "linux" + // OperatingSystemWindows represents the Windows operating system. + OperatingSystemWindows OperatingSystem = "windows" +) + +// NodeInfo contains information about the node's architecture and operating system. +type NodeInfo struct { + // Architecture is the CPU architecture of the node. + // Its underlying type is a string and its value can be any of amd64, arm64. + // +kubebuilder:validation:Enum=amd64;arm64 + // +optional + Architecture Architecture `json:"architecture,omitempty"` + // OperatingSystem is the operating system of the node. + // Its underlying type is a string and its value can be any of linux, windows. + // +kubebuilder:validation:Enum=linux;windows + // +optional + OperatingSystem OperatingSystem `json:"operatingSystem,omitempty"` +} + // AWSMachineTemplateStatus defines a status for an AWSMachineTemplate. type AWSMachineTemplateStatus struct { // Capacity defines the resource capacity for this machine. @@ -30,6 +66,16 @@ type AWSMachineTemplateStatus struct { // https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20210310-opt-in-autoscaling-from-zero.md // +optional Capacity corev1.ResourceList `json:"capacity,omitempty"` + + // NodeInfo contains information about the node's architecture and operating system. + // This value is used for autoscaling from zero operations as defined in: + // https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20210310-opt-in-autoscaling-from-zero.md + // +optional + NodeInfo *NodeInfo `json:"nodeInfo,omitempty"` + + // Conditions defines current service state of the AWSMachineTemplate. + // +optional + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // AWSMachineTemplateSpec defines the desired state of AWSMachineTemplate. @@ -40,6 +86,7 @@ type AWSMachineTemplateSpec struct { // +kubebuilder:object:root=true // +kubebuilder:resource:path=awsmachinetemplates,scope=Namespaced,categories=cluster-api,shortName=awsmt // +kubebuilder:storageversion +// +kubebuilder:subresource:status // +k8s:defaulter-gen=true // AWSMachineTemplate is the schema for the Amazon EC2 Machine Templates API. @@ -65,12 +112,22 @@ type AWSMachineTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta clusterv1.ObjectMeta `json:"metadata,omitempty"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` // Spec is the specification of the desired behavior of the machine. Spec AWSMachineSpec `json:"spec"` } +// GetConditions returns the observations of the operational state of the AWSMachineTemplate resource. +func (r *AWSMachineTemplate) GetConditions() clusterv1beta1.Conditions { + return r.Status.Conditions +} + +// SetConditions sets the underlying service state of the AWSMachineTemplate to the predescribed clusterv1beta1.Conditions. +func (r *AWSMachineTemplate) SetConditions(conditions clusterv1beta1.Conditions) { + r.Status.Conditions = conditions +} + func init() { SchemeBuilder.Register(&AWSMachineTemplate{}, &AWSMachineTemplateList{}) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachinetemplate_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachinetemplate_webhook.go index 65e4e0ca3200..7180939d5360 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachinetemplate_webhook.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmachinetemplate_webhook.go @@ -172,6 +172,23 @@ func (r *AWSMachineTemplate) validateIgnitionAndCloudInit() field.ErrorList { return allErrs } + +func (r *AWSMachineTemplate) validateHostAllocation() field.ErrorList { + var allErrs field.ErrorList + + spec := r.Spec.Template.Spec + + // Check if both hostID and dynamicHostAllocation are specified + hasHostID := spec.HostID != nil && len(*spec.HostID) > 0 + hasDynamicHostAllocation := spec.DynamicHostAllocation != nil + + if hasHostID && hasDynamicHostAllocation { + allErrs = append(allErrs, field.Forbidden(field.NewPath("spec.template.spec.hostID"), "hostID and dynamicHostAllocation are mutually exclusive"), field.Forbidden(field.NewPath("spec.template.spec.dynamicHostAllocation"), "hostID and dynamicHostAllocation are mutually exclusive")) + } + + return allErrs +} + func (r *AWSMachineTemplate) validateSSHKeyName() field.ErrorList { return validateSSHKeyName(r.Spec.Template.Spec.SSHKeyName) } @@ -205,6 +222,7 @@ func (r *AWSMachineTemplateWebhook) ValidateCreate(_ context.Context, raw runtim allErrs = append(allErrs, obj.validateSSHKeyName()...) allErrs = append(allErrs, obj.validateAdditionalSecurityGroups()...) allErrs = append(allErrs, obj.Spec.Template.Spec.AdditionalTags.Validate()...) + allErrs = append(allErrs, obj.validateHostAllocation()...) return nil, aggregateObjErrors(obj.GroupVersionKind().GroupKind(), obj.Name, allErrs) } @@ -227,7 +245,7 @@ func (r *AWSMachineTemplateWebhook) ValidateUpdate(ctx context.Context, oldRaw r var allErrs field.ErrorList - if !topology.ShouldSkipImmutabilityChecks(req, newAWSMachineTemplate) && !cmp.Equal(newAWSMachineTemplate.Spec, oldAWSMachineTemplate.Spec) { + if !topology.IsDryRunRequest(req, newAWSMachineTemplate) && !cmp.Equal(newAWSMachineTemplate.Spec, oldAWSMachineTemplate.Spec) { if oldAWSMachineTemplate.Spec.Template.Spec.InstanceMetadataOptions == nil { oldAWSMachineTemplate.Spec.Template.Spec.InstanceMetadataOptions = newAWSMachineTemplate.Spec.Template.Spec.InstanceMetadataOptions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmanagedcluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmanagedcluster_types.go index 67d9b2fc924e..ce04e1866933 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmanagedcluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmanagedcluster_types.go @@ -19,14 +19,14 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AWSManagedClusterSpec defines the desired state of AWSManagedCluster type AWSManagedClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` } // AWSManagedClusterStatus defines the observed state of AWSManagedCluster @@ -37,11 +37,11 @@ type AWSManagedClusterStatus struct { // FailureDomains specifies a list fo available availability zones that can be used // +optional - FailureDomains clusterv1.FailureDomains `json:"failureDomains,omitempty"` + FailureDomains clusterv1beta1.FailureDomains `json:"failureDomains,omitempty"` // Conditions defines current service state of the AWSManagedCluster. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +kubebuilder:object:root=true @@ -76,12 +76,12 @@ func init() { // GetConditions returns the observations of the operational state of the // AWSManagedCluster resource. -func (r *AWSManagedCluster) GetConditions() clusterv1.Conditions { +func (r *AWSManagedCluster) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } // SetConditions sets the underlying service state of the AWSManagedCluster to -// the predescribed clusterv1.Conditions. -func (r *AWSManagedCluster) SetConditions(conditions clusterv1.Conditions) { +// the predescribed clusterv1beta1.Conditions. +func (r *AWSManagedCluster) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmanagedclustertemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmanagedclustertemplate_types.go index 266ccf400fbb..28ab2bea9e87 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmanagedclustertemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/awsmanagedclustertemplate_types.go @@ -26,7 +26,7 @@ type AWSManagedClusterTemplateSpec struct { } // +kubebuilder:object:root=true -// +kubebuilder:resource:path=awsmanagedclustertemplates,scope=Namespaced,categories=cluster-api,shortName=amct +// +kubebuilder:resource:path=awsmanagedclustertemplates,scope=Namespaced,categories=cluster-api,shortName=awsmct // +kubebuilder:storageversion // AWSManagedClusterTemplate is the Schema for the AWSManagedClusterTemplates API. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/conditions_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/conditions_consts.go index 604ef8e1d5aa..1175ac9916df 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/conditions_consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/conditions_consts.go @@ -16,19 +16,19 @@ limitations under the License. package v1beta2 -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" +import clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" const ( // PrincipalCredentialRetrievedCondition reports on whether Principal credentials could be retrieved successfully. // A possible scenario, where retrieval is unsuccessful, is when SourcePrincipal is not authorized for assume role. - PrincipalCredentialRetrievedCondition clusterv1.ConditionType = "PrincipalCredentialRetrieved" + PrincipalCredentialRetrievedCondition clusterv1beta1.ConditionType = "PrincipalCredentialRetrieved" // PrincipalCredentialRetrievalFailedReason used when errors occur during identity credential retrieval. PrincipalCredentialRetrievalFailedReason = "PrincipalCredentialRetrievalFailed" // CredentialProviderBuildFailedReason used when errors occur during building providers before trying credential retrieval. //nolint:gosec CredentialProviderBuildFailedReason = "CredentialProviderBuildFailed" // PrincipalUsageAllowedCondition reports on whether Principal and all the nested source identities are allowed to be used in the AWSCluster namespace. - PrincipalUsageAllowedCondition clusterv1.ConditionType = "PrincipalUsageAllowed" + PrincipalUsageAllowedCondition clusterv1beta1.ConditionType = "PrincipalUsageAllowed" // PrincipalUsageUnauthorizedReason used when AWSCluster namespace is not in the identity's allowed namespaces list. PrincipalUsageUnauthorizedReason = "PrincipalUsageUnauthorized" // SourcePrincipalUsageUnauthorizedReason used when AWSCluster is not in the intersection of source identity allowed namespaces @@ -38,7 +38,7 @@ const ( const ( // VpcReadyCondition reports on the successful reconciliation of a VPC. - VpcReadyCondition clusterv1.ConditionType = "VpcReady" + VpcReadyCondition clusterv1beta1.ConditionType = "VpcReady" // VpcCreationStartedReason used when attempting to create a VPC for a managed cluster. // Will not be applied to unmanaged clusters. VpcCreationStartedReason = "VpcCreationStarted" @@ -48,7 +48,7 @@ const ( const ( // SubnetsReadyCondition reports on the successful reconciliation of subnets. - SubnetsReadyCondition clusterv1.ConditionType = "SubnetsReady" + SubnetsReadyCondition clusterv1beta1.ConditionType = "SubnetsReady" // SubnetsReconciliationFailedReason used to report failures while reconciling subnets. SubnetsReconciliationFailedReason = "SubnetsReconciliationFailed" ) @@ -56,7 +56,7 @@ const ( const ( // InternetGatewayReadyCondition reports on the successful reconciliation of internet gateways. // Only applicable to managed clusters. - InternetGatewayReadyCondition clusterv1.ConditionType = "InternetGatewayReady" + InternetGatewayReadyCondition clusterv1beta1.ConditionType = "InternetGatewayReady" // InternetGatewayFailedReason used when errors occur during internet gateway reconciliation. InternetGatewayFailedReason = "InternetGatewayFailed" ) @@ -64,7 +64,7 @@ const ( const ( // EgressOnlyInternetGatewayReadyCondition reports on the successful reconciliation of egress only internet gateways. // Only applicable to managed clusters. - EgressOnlyInternetGatewayReadyCondition clusterv1.ConditionType = "EgressOnlyInternetGatewayReady" + EgressOnlyInternetGatewayReadyCondition clusterv1beta1.ConditionType = "EgressOnlyInternetGatewayReady" // EgressOnlyInternetGatewayFailedReason used when errors occur during egress only internet gateway reconciliation. EgressOnlyInternetGatewayFailedReason = "EgressOnlyInternetGatewayFailed" ) @@ -72,7 +72,7 @@ const ( const ( // CarrierGatewayReadyCondition reports on the successful reconciliation of carrier gateways. // Only applicable to managed clusters. - CarrierGatewayReadyCondition clusterv1.ConditionType = "CarrierGatewayReady" + CarrierGatewayReadyCondition clusterv1beta1.ConditionType = "CarrierGatewayReady" // CarrierGatewayFailedReason used when errors occur during carrier gateway reconciliation. CarrierGatewayFailedReason = "CarrierGatewayFailed" ) @@ -80,7 +80,7 @@ const ( const ( // NatGatewaysReadyCondition reports successful reconciliation of NAT gateways. // Only applicable to managed clusters. - NatGatewaysReadyCondition clusterv1.ConditionType = "NatGatewaysReady" + NatGatewaysReadyCondition clusterv1beta1.ConditionType = "NatGatewaysReady" // NatGatewaysCreationStartedReason set once when creating new NAT gateways. NatGatewaysCreationStartedReason = "NatGatewaysCreationStarted" // NatGatewaysReconciliationFailedReason used when any errors occur during reconciliation of NAT gateways. @@ -90,7 +90,7 @@ const ( const ( // RouteTablesReadyCondition reports successful reconciliation of route tables. // Only applicable to managed clusters. - RouteTablesReadyCondition clusterv1.ConditionType = "RouteTablesReady" + RouteTablesReadyCondition clusterv1beta1.ConditionType = "RouteTablesReady" // RouteTableReconciliationFailedReason used when any errors occur during reconciliation of route tables. RouteTableReconciliationFailedReason = "RouteTableReconciliationFailed" ) @@ -98,7 +98,7 @@ const ( const ( // VpcEndpointsReadyCondition reports successful reconciliation of vpc endpoints. // Only applicable to managed clusters. - VpcEndpointsReadyCondition clusterv1.ConditionType = "VpcEndpointsReadyCondition" + VpcEndpointsReadyCondition clusterv1beta1.ConditionType = "VpcEndpointsReadyCondition" // VpcEndpointsReconciliationFailedReason used when any errors occur during reconciliation of vpc endpoints. VpcEndpointsReconciliationFailedReason = "VpcEndpointsReconciliationFailed" ) @@ -106,14 +106,14 @@ const ( const ( // SecondaryCidrsReadyCondition reports successful reconciliation of secondary CIDR blocks. // Only applicable to managed clusters. - SecondaryCidrsReadyCondition clusterv1.ConditionType = "SecondaryCidrsReady" + SecondaryCidrsReadyCondition clusterv1beta1.ConditionType = "SecondaryCidrsReady" // SecondaryCidrReconciliationFailedReason used when any errors occur during reconciliation of secondary CIDR blocks. SecondaryCidrReconciliationFailedReason = "SecondaryCidrReconciliationFailed" ) const ( // ClusterSecurityGroupsReadyCondition reports successful reconciliation of security groups. - ClusterSecurityGroupsReadyCondition clusterv1.ConditionType = "ClusterSecurityGroupsReady" + ClusterSecurityGroupsReadyCondition clusterv1beta1.ConditionType = "ClusterSecurityGroupsReady" // ClusterSecurityGroupReconciliationFailedReason used when any errors occur during reconciliation of security groups. ClusterSecurityGroupReconciliationFailedReason = "SecurityGroupReconciliationFailed" ) @@ -121,7 +121,7 @@ const ( const ( // BastionHostReadyCondition reports whether a bastion host is ready. Depending on the configuration, a cluster // may not require a bastion host and this condition will be skipped. - BastionHostReadyCondition clusterv1.ConditionType = "BastionHostReady" + BastionHostReadyCondition clusterv1beta1.ConditionType = "BastionHostReady" // BastionCreationStartedReason used when creating a new bastion host. BastionCreationStartedReason = "BastionCreationStarted" // BastionHostFailedReason used when an error occurs during the creation of a bastion host. @@ -130,7 +130,7 @@ const ( const ( // LoadBalancerReadyCondition reports on whether a control plane load balancer was successfully reconciled. - LoadBalancerReadyCondition clusterv1.ConditionType = "LoadBalancerReady" + LoadBalancerReadyCondition clusterv1beta1.ConditionType = "LoadBalancerReady" // WaitForDNSNameReason used while waiting for a DNS name for the API server to be populated. WaitForDNSNameReason = "WaitForDNSName" // WaitForExternalControlPlaneEndpointReason is available when the AWS Cluster is waiting for an externally managed @@ -144,7 +144,11 @@ const ( const ( // InstanceReadyCondition reports on current status of the EC2 instance. Ready indicates the instance is in a Running state. - InstanceReadyCondition clusterv1.ConditionType = "InstanceReady" + InstanceReadyCondition clusterv1beta1.ConditionType = "InstanceReady" + + // DedicatedHostReleaseCondition reports on the status of dedicated host release operations. + // This condition tracks whether the dedicated host has been successfully released or if there are failures. + DedicatedHostReleaseCondition clusterv1beta1.ConditionType = "DedicatedHostRelease" // InstanceNotFoundReason used when the instance couldn't be retrieved. InstanceNotFoundReason = "InstanceNotFound" @@ -166,7 +170,7 @@ const ( const ( // SecurityGroupsReadyCondition indicates the security groups are up to date on the AWSMachine. - SecurityGroupsReadyCondition clusterv1.ConditionType = "SecurityGroupsReady" + SecurityGroupsReadyCondition clusterv1beta1.ConditionType = "SecurityGroupsReady" // SecurityGroupsFailedReason used when the security groups could not be synced. SecurityGroupsFailedReason = "SecurityGroupsSyncFailed" @@ -177,7 +181,7 @@ const ( // When set to false, severity can be an Error if the subnet is not found or unavailable in the instance's AZ. // Note this is only applicable to control plane machines. // Only applicable to control plane machines. - ELBAttachedCondition clusterv1.ConditionType = "ELBAttached" + ELBAttachedCondition clusterv1beta1.ConditionType = "ELBAttached" // ELBAttachFailedReason used when a control plane node fails to attach to the ELB. ELBAttachFailedReason = "ELBAttachFailed" @@ -187,8 +191,11 @@ const ( const ( // S3BucketReadyCondition indicates an S3 bucket has been created successfully. - S3BucketReadyCondition clusterv1.ConditionType = "S3BucketCreated" + S3BucketReadyCondition clusterv1beta1.ConditionType = "S3BucketCreated" // S3BucketFailedReason is used when any errors occur during reconciliation of an S3 bucket. S3BucketFailedReason = "S3BucketCreationFailed" + + // DedicatedHostReleaseFailedReason used when the dedicated host release fails. + DedicatedHostReleaseFailedReason = "DedicatedHostReleaseFailed" ) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/tags.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/tags.go index 45bc371a4949..764d06f73d0d 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/tags.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/tags.go @@ -23,7 +23,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) // Tags defines a map of tags. @@ -78,7 +78,7 @@ func (t Tags) Validate() []*field.Error { // Defines the maximum number of user tags which can be created for a specific resource const maxUserTagsAllowed = 50 var errs field.ErrorList - var userTagCount = len(t) + userTagCount := len(t) re := regexp.MustCompile(`^[a-zA-Z0-9\s\_\.\:\=\+\-\@\/]*$`) for k, v := range t { diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/types.go index 0f8d155515b1..81a3be6db35b 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/types.go @@ -21,7 +21,7 @@ import ( "k8s.io/apimachinery/pkg/util/sets" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -192,7 +192,7 @@ type Instance struct { IAMProfile string `json:"iamProfile,omitempty"` // Addresses contains the AWS instance associated addresses. - Addresses []clusterv1.MachineAddress `json:"addresses,omitempty"` + Addresses []clusterv1beta1.MachineAddress `json:"addresses,omitempty"` // The private IPv4 address assigned to the instance. PrivateIP *string `json:"privateIp,omitempty"` @@ -286,13 +286,23 @@ type Instance struct { // +optional HostID *string `json:"hostID,omitempty"` + // DynamicHostAllocation enables automatic allocation of dedicated hosts. + // This field is mutually exclusive with HostID. + // +optional + DynamicHostAllocation *DynamicHostAllocationSpec `json:"dynamicHostAllocation,omitempty"` + // CapacityReservationPreference specifies the preference for use of Capacity Reservations by the instance. Valid values include: // "Open": The instance may make use of open Capacity Reservations that match its AZ and InstanceType // "None": The instance may not make use of any Capacity Reservations. This is to conserve open reservations for desired workloads - // "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation + // "CapacityReservationsOnly": The instance will only run if matched or targeted to a Capacity Reservation. Note that this is incompatible with a MarketType of `Spot` // +kubebuilder:validation:Enum="";None;CapacityReservationsOnly;Open // +optional CapacityReservationPreference CapacityReservationPreference `json:"capacityReservationPreference,omitempty"` + + // CPUOptions defines CPU-related settings for the instance, including the confidential computing policy. + // When omitted, this means no opinion and the AWS platform is left to choose a reasonable default. + // +optional + CPUOptions CPUOptions `json:"cpuOptions,omitempty,omitzero"` } // CapacityReservationPreference describes the preferred use of capacity reservations @@ -304,13 +314,40 @@ const ( // CapacityReservationPreferenceNone the instance may not make use of any Capacity Reservations. This is to conserve open reservations for desired workloads CapacityReservationPreferenceNone CapacityReservationPreference = "None" - // CapacityReservationPreferenceOnly the instance will only run if matched or targeted to a Capacity Reservation + // CapacityReservationPreferenceOnly the instance will only run if matched or targeted to a Capacity Reservation. Note that this is incompatible with a MarketType of `Spot` CapacityReservationPreferenceOnly CapacityReservationPreference = "CapacityReservationsOnly" // CapacityReservationPreferenceOpen the instance may make use of open Capacity Reservations that match its AZ and InstanceType. CapacityReservationPreferenceOpen CapacityReservationPreference = "Open" ) +// DedicatedHostInfo contains information about a dedicated host. +type DedicatedHostInfo struct { + // HostID is the ID of the dedicated host. + HostID string `json:"hostID"` + + // InstanceFamily is the instance family supported by the host. + InstanceFamily string `json:"instanceFamily"` + + // InstanceType is the instance type supported by the host. + InstanceType string `json:"instanceType"` + + // AvailabilityZone is the AZ where the host is located. + AvailabilityZone string `json:"availabilityZone"` + + // State is the current state of the dedicated host. + State string `json:"state"` + + // TotalCapacity is the total number of instances that can be launched on the host. + TotalCapacity int32 `json:"totalCapacity"` + + // AvailableCapacity is the number of instances that can still be launched on the host. + AvailableCapacity int32 `json:"availableCapacity"` + + // Tags associated with the dedicated host. + Tags map[string]string `json:"tags,omitempty"` +} + // MarketType describes the market type of an Instance // +kubebuilder:validation:Enum:=OnDemand;Spot;CapacityBlock type MarketType string @@ -534,3 +571,33 @@ var ( // SubnetSchemaPreferPublic allocates more subnets in the VPC to public subnets. SubnetSchemaPreferPublic = SubnetSchemaType("PreferPublic") ) + +// AWSConfidentialComputePolicy represents the confidential compute configuration for the instance. +// +kubebuilder:validation:Enum=Disabled;AMDEncryptedVirtualizationNestedPaging +type AWSConfidentialComputePolicy string + +const ( + // AWSConfidentialComputePolicyDisabled disables confidential computing for the instance. + AWSConfidentialComputePolicyDisabled AWSConfidentialComputePolicy = "Disabled" + // AWSConfidentialComputePolicySEVSNP enables AMD SEV-SNP as the confidential computing technology for the instance. + AWSConfidentialComputePolicySEVSNP AWSConfidentialComputePolicy = "AMDEncryptedVirtualizationNestedPaging" +) + +// CPUOptions defines CPU-related settings for the instance, including the confidential computing policy. +// +kubebuilder:validation:MinProperties=1 +type CPUOptions struct { + // ConfidentialCompute specifies whether confidential computing should be enabled for the instance, + // and, if so, which confidential computing technology to use. + // Valid values are: Disabled, AMDEncryptedVirtualizationNestedPaging + // When set to Disabled, confidential computing will be disabled for the instance. + // When set to AMDEncryptedVirtualizationNestedPaging, AMD SEV-SNP will be used as the confidential computing technology for the instance. + // In this case, ensure the following conditions are met: + // 1) The selected instance type supports AMD SEV-SNP. + // 2) The selected AWS region supports AMD SEV-SNP. + // 3) The selected AMI supports AMD SEV-SNP. + // More details can be checked at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sev-snp.html + // When omitted, this means no opinion and the AWS platform is left to choose a reasonable default, + // which is subject to change without notice. The current default is Disabled. + // +optional + ConfidentialCompute AWSConfidentialComputePolicy `json:"confidentialCompute,omitempty"` +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/zz_generated.deepcopy.go index 5c21fefeb9c6..1293074cb56d 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2/zz_generated.deepcopy.go @@ -24,7 +24,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/cluster-api/api/v1beta1" + "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -687,6 +687,7 @@ func (in *AWSMachineSpec) DeepCopyInto(out *AWSMachineSpec) { **out = **in } in.AMI.DeepCopyInto(&out.AMI) + out.CPUOptions = in.CPUOptions if in.AdditionalTags != nil { in, out := &in.AdditionalTags, &out.AdditionalTags *out = make(Tags, len(*in)) @@ -781,6 +782,11 @@ func (in *AWSMachineSpec) DeepCopyInto(out *AWSMachineSpec) { *out = new(string) **out = **in } + if in.DynamicHostAllocation != nil { + in, out := &in.DynamicHostAllocation, &out.DynamicHostAllocation + *out = new(DynamicHostAllocationSpec) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSMachineSpec. @@ -823,6 +829,11 @@ func (in *AWSMachineStatus) DeepCopyInto(out *AWSMachineStatus) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.DedicatedHost != nil { + in, out := &in.DedicatedHost, &out.DedicatedHost + *out = new(DedicatedHostStatus) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSMachineStatus. @@ -937,6 +948,18 @@ func (in *AWSMachineTemplateStatus) DeepCopyInto(out *AWSMachineTemplateStatus) (*out)[key] = val.DeepCopy() } } + if in.NodeInfo != nil { + in, out := &in.NodeInfo, &out.NodeInfo + *out = new(NodeInfo) + **out = **in + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(v1beta1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSMachineTemplateStatus. @@ -1337,6 +1360,21 @@ func (in *CNISpec) DeepCopy() *CNISpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CPUOptions) DeepCopyInto(out *CPUOptions) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CPUOptions. +func (in *CPUOptions) DeepCopy() *CPUOptions { + if in == nil { + return nil + } + out := new(CPUOptions) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClassicELBAttributes) DeepCopyInto(out *ClassicELBAttributes) { *out = *in @@ -1397,6 +1435,70 @@ func (in *CloudInit) DeepCopy() *CloudInit { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DedicatedHostInfo) DeepCopyInto(out *DedicatedHostInfo) { + *out = *in + if in.Tags != nil { + in, out := &in.Tags, &out.Tags + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DedicatedHostInfo. +func (in *DedicatedHostInfo) DeepCopy() *DedicatedHostInfo { + if in == nil { + return nil + } + out := new(DedicatedHostInfo) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DedicatedHostStatus) DeepCopyInto(out *DedicatedHostStatus) { + *out = *in + if in.ID != nil { + in, out := &in.ID, &out.ID + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DedicatedHostStatus. +func (in *DedicatedHostStatus) DeepCopy() *DedicatedHostStatus { + if in == nil { + return nil + } + out := new(DedicatedHostStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DynamicHostAllocationSpec) DeepCopyInto(out *DynamicHostAllocationSpec) { + *out = *in + if in.Tags != nil { + in, out := &in.Tags, &out.Tags + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DynamicHostAllocationSpec. +func (in *DynamicHostAllocationSpec) DeepCopy() *DynamicHostAllocationSpec { + if in == nil { + return nil + } + out := new(DynamicHostAllocationSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ElasticIPPool) DeepCopyInto(out *ElasticIPPool) { *out = *in @@ -1720,6 +1822,12 @@ func (in *Instance) DeepCopyInto(out *Instance) { *out = new(string) **out = **in } + if in.DynamicHostAllocation != nil { + in, out := &in.DynamicHostAllocation, &out.DynamicHostAllocation + *out = new(DynamicHostAllocationSpec) + (*in).DeepCopyInto(*out) + } + out.CPUOptions = in.CPUOptions } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Instance. @@ -1917,6 +2025,21 @@ func (in *NetworkStatus) DeepCopy() *NetworkStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeInfo) DeepCopyInto(out *NodeInfo) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeInfo. +func (in *NodeInfo) DeepCopy() *NodeInfo { + if in == nil { + return nil + } + out := new(NodeInfo) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PrivateDNSName) DeepCopyInto(out *PrivateDNSName) { *out = *in diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/conditions_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/conditions_consts.go new file mode 100644 index 000000000000..4229bedb8152 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/conditions_consts.go @@ -0,0 +1,51 @@ +/* +Copyright 2022 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" + +const ( + // ROSAControlPlaneReadyCondition condition reports on the successful reconciliation of ROSAControlPlane. + ROSAControlPlaneReadyCondition clusterv1beta1.ConditionType = "ROSAControlPlaneReady" + + // ROSAControlPlaneValidCondition condition reports whether ROSAControlPlane configuration is valid. + ROSAControlPlaneValidCondition clusterv1beta1.ConditionType = "ROSAControlPlaneValid" + + // ROSAControlPlaneUpgradingCondition condition reports whether ROSAControlPlane is upgrading or not. + ROSAControlPlaneUpgradingCondition clusterv1beta1.ConditionType = "ROSAControlPlaneUpgrading" + + // ExternalAuthConfiguredCondition condition reports whether external auth has beed correctly configured. + ExternalAuthConfiguredCondition clusterv1beta1.ConditionType = "ExternalAuthConfigured" + + // ROSARoleConfigReadyCondition condition reports whether the referenced RosaRoleConfig is ready. + ROSARoleConfigReadyCondition clusterv1beta1.ConditionType = "ROSARoleConfigReady" + + // ReconciliationFailedReason used to report reconciliation failures. + ReconciliationFailedReason = "ReconciliationFailed" + + // ROSAControlPlaneDeletionFailedReason used to report failures while deleting ROSAControlPlane. + ROSAControlPlaneDeletionFailedReason = "DeletionFailed" + + // ROSAControlPlaneInvalidConfigurationReason used to report invalid user input. + ROSAControlPlaneInvalidConfigurationReason = "InvalidConfiguration" + + // ROSARoleConfigNotReadyReason used to report when referenced RosaRoleConfig is not ready. + ROSARoleConfigNotReadyReason = "ROSARoleConfigNotReady" + + // ROSARoleConfigNotFoundReason used to report when referenced RosaRoleConfig is not found. + ROSARoleConfigNotFoundReason = "ROSARoleConfigNotFound" +) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/defaults.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/defaults.go new file mode 100644 index 000000000000..a2006137c1e6 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/defaults.go @@ -0,0 +1,13 @@ +package v1beta2 + +import "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" + +// SetDefaults_RosaControlPlaneSpec is used by defaulter-gen. +func SetDefaults_RosaControlPlaneSpec(s *RosaControlPlaneSpec) { //nolint:golint,stylecheck + if s.IdentityRef == nil { + s.IdentityRef = &v1beta2.AWSIdentityReference{ + Kind: v1beta2.ControllerIdentityKind, + Name: v1beta2.AWSClusterControllerIdentityName, + } + } +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/doc.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/doc.go new file mode 100644 index 000000000000..9308d1fb621b --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/doc.go @@ -0,0 +1,21 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package v1beta2 contains API Schema definitions for the controlplane v1beta2 API group +// +gencrdrefdocs:force +// +groupName=controlplane.cluster.x-k8s.io +// +k8s:defaulter-gen=TypeMeta +package v1beta2 diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/external_auth_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/external_auth_types.go new file mode 100644 index 000000000000..7bd16d4585fd --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/external_auth_types.go @@ -0,0 +1,249 @@ +package v1beta2 + +// ExternalAuthProvider is an external OIDC identity provider that can issue tokens for this cluster +type ExternalAuthProvider struct { + // Name of the OIDC provider + // + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:Required + // +required + Name string `json:"name"` + // Issuer describes attributes of the OIDC token issuer + // + // +kubebuilder:validation:Required + // +required + Issuer TokenIssuer `json:"issuer"` + + // OIDCClients contains configuration for the platform's clients that + // need to request tokens from the issuer + // + // +listType=map + // +listMapKey=componentNamespace + // +listMapKey=componentName + // +kubebuilder:validation:MaxItems=20 + // +optional + OIDCClients []OIDCClientConfig `json:"oidcClients,omitempty"` + + // ClaimMappings describes rules on how to transform information from an + // ID token into a cluster identity + // +optional + ClaimMappings *TokenClaimMappings `json:"claimMappings,omitempty"` + + // ClaimValidationRules are rules that are applied to validate token claims to authenticate users. + // + // +listType=atomic + ClaimValidationRules []TokenClaimValidationRule `json:"claimValidationRules,omitempty"` +} + +// TokenAudience is the audience that the token was issued for. +// +// +kubebuilder:validation:MinLength=1 +type TokenAudience string + +// TokenIssuer describes attributes of the OIDC token issuer +type TokenIssuer struct { + // URL is the serving URL of the token issuer. + // Must use the https:// scheme. + // + // +kubebuilder:validation:Pattern=`^https:\/\/[^\s]` + // +kubebuilder:validation:Required + // +required + URL string `json:"issuerURL"` + + // Audiences is an array of audiences that the token was issued for. + // Valid tokens must include at least one of these values in their + // "aud" claim. + // Must be set to exactly one value. + // + // +listType=set + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=10 + // +required + Audiences []TokenAudience `json:"audiences"` + + // CertificateAuthority is a reference to a config map in the + // configuration namespace. The .data of the configMap must contain + // the "ca-bundle.crt" key. + // If unset, system trust is used instead. + CertificateAuthority *LocalObjectReference `json:"issuerCertificateAuthority,omitempty"` +} + +// OIDCClientConfig contains configuration for the platform's client that +// need to request tokens from the issuer. +type OIDCClientConfig struct { + // ComponentName is the name of the component that is supposed to consume this + // client configuration + // + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + // +kubebuilder:validation:Required + // +required + ComponentName string `json:"componentName"` + + // ComponentNamespace is the namespace of the component that is supposed to consume this + // client configuration + // + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Required + // +required + ComponentNamespace string `json:"componentNamespace"` + + // ClientID is the identifier of the OIDC client from the OIDC provider + // + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:Required + // +required + ClientID string `json:"clientID"` + + // ClientSecret refers to a secret that + // contains the client secret in the `clientSecret` key of the `.data` field + ClientSecret LocalObjectReference `json:"clientSecret"` + + // ExtraScopes is an optional set of scopes to request tokens with. + // + // +listType=set + // +optional + ExtraScopes []string `json:"extraScopes,omitempty"` +} + +// TokenClaimMappings describes rules on how to transform information from an +// ID token into a cluster identity. +type TokenClaimMappings struct { + // Username is a name of the claim that should be used to construct + // usernames for the cluster identity. + // + // Default value: "sub" + // +optional + Username *UsernameClaimMapping `json:"username,omitempty"` + + // Groups is a name of the claim that should be used to construct + // groups for the cluster identity. + // The referenced claim must use array of strings values. + // +optional + Groups *PrefixedClaimMapping `json:"groups,omitempty"` +} + +// PrefixedClaimMapping defines claims with a prefix. +type PrefixedClaimMapping struct { + // Claim is a JWT token claim to be used in the mapping + // + // +kubebuilder:validation:Required + // +required + Claim string `json:"claim"` + + // Prefix is a string to prefix the value from the token in the result of the + // claim mapping. + // + // By default, no prefixing occurs. + // + // Example: if `prefix` is set to "myoidc:"" and the `claim` in JWT contains + // an array of strings "a", "b" and "c", the mapping will result in an + // array of string "myoidc:a", "myoidc:b" and "myoidc:c". + Prefix string `json:"prefix,omitempty"` +} + +// UsernameClaimMapping defines the claim that should be used to construct usernames for the cluster identity. +// +// +kubebuilder:validation:XValidation:rule="self.prefixPolicy == 'Prefix' ? has(self.prefix) : !has(self.prefix)",message="prefix must be set if prefixPolicy is 'Prefix', but must remain unset otherwise" +type UsernameClaimMapping struct { + // Claim is a JWT token claim to be used in the mapping + // + // +kubebuilder:validation:Required + // +required + Claim string `json:"claim"` + + // PrefixPolicy specifies how a prefix should apply. + // + // By default, claims other than `email` will be prefixed with the issuer URL to + // prevent naming clashes with other plugins. + // + // Set to "NoPrefix" to disable prefixing. + // + // Example: + // (1) `prefix` is set to "myoidc:" and `claim` is set to "username". + // If the JWT claim `username` contains value `userA`, the resulting + // mapped value will be "myoidc:userA". + // (2) `prefix` is set to "myoidc:" and `claim` is set to "email". If the + // JWT `email` claim contains value "userA@myoidc.tld", the resulting + // mapped value will be "myoidc:userA@myoidc.tld". + // (3) `prefix` is unset, `issuerURL` is set to `https://myoidc.tld`, + // the JWT claims include "username":"userA" and "email":"userA@myoidc.tld", + // and `claim` is set to: + // (a) "username": the mapped value will be "https://myoidc.tld#userA" + // (b) "email": the mapped value will be "userA@myoidc.tld" + // + // +kubebuilder:validation:Enum={"", "NoPrefix", "Prefix"} + // +optional + PrefixPolicy UsernamePrefixPolicy `json:"prefixPolicy,omitempty"` + + // Prefix is prepended to claim to prevent clashes with existing names. + // + // +kubebuilder:validation:MinLength=1 + // +optional + Prefix *string `json:"prefix,omitempty"` +} + +// UsernamePrefixPolicy specifies how a prefix should apply. +type UsernamePrefixPolicy string + +const ( + // NoOpinion let's the cluster assign prefixes. If the username claim is email, there is no prefix + // If the username claim is anything else, it is prefixed by the issuerURL + NoOpinion UsernamePrefixPolicy = "" + + // NoPrefix means the username claim value will not have any prefix + NoPrefix UsernamePrefixPolicy = "NoPrefix" + + // Prefix means the prefix value must be specified. It cannot be empty + Prefix UsernamePrefixPolicy = "Prefix" +) + +// TokenValidationRuleType defines the type of the validation rule. +type TokenValidationRuleType string + +const ( + // TokenValidationRuleTypeRequiredClaim defines the type for RequiredClaim. + TokenValidationRuleTypeRequiredClaim TokenValidationRuleType = "RequiredClaim" +) + +// TokenClaimValidationRule validates token claims to authenticate users. +type TokenClaimValidationRule struct { + // Type sets the type of the validation rule + // + // +kubebuilder:validation:Enum={"RequiredClaim"} + // +kubebuilder:default="RequiredClaim" + Type TokenValidationRuleType `json:"type"` + + // RequiredClaim allows configuring a required claim name and its expected value + // +kubebuilder:validation:Required + RequiredClaim TokenRequiredClaim `json:"requiredClaim"` +} + +// TokenRequiredClaim allows configuring a required claim name and its expected value. +type TokenRequiredClaim struct { + // Claim is a name of a required claim. Only claims with string values are + // supported. + // + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:Required + // +required + Claim string `json:"claim"` + + // RequiredValue is the required value for the claim. + // + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:Required + // +required + RequiredValue string `json:"requiredValue"` +} + +// LocalObjectReference references an object in the same namespace. +type LocalObjectReference struct { + // Name is the metadata.name of the referenced object. + // + // +kubebuilder:validation:Required + // +required + Name string `json:"name"` +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/groupversion_info.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/groupversion_info.go new file mode 100644 index 000000000000..ea4ec8f78411 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/groupversion_info.go @@ -0,0 +1,36 @@ +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package v1beta2 contains API Schema definitions for the controlplane v1beta2 API group. +// +kubebuilder:object:generate=true +// +groupName=controlplane.cluster.x-k8s.io +package v1beta2 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +var ( + // GroupVersion is group version used to register these objects. + GroupVersion = schema.GroupVersion{Group: "controlplane.cluster.x-k8s.io", Version: "v1beta2"} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. + SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} + + // AddToScheme adds the types in this group-version to the given scheme. + AddToScheme = SchemeBuilder.AddToScheme +) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/rosacontrolplane_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/rosacontrolplane_types.go new file mode 100644 index 000000000000..4be22a8decf8 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/rosacontrolplane_types.go @@ -0,0 +1,864 @@ +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" +) + +// RosaEndpointAccessType specifies the publishing scope of cluster endpoints. +type RosaEndpointAccessType string + +const ( + // Public endpoint access allows public API server access and + // private node communication with the control plane. + Public RosaEndpointAccessType = "Public" + + // Private endpoint access allows only private API server access and private + // node communication with the control plane. + Private RosaEndpointAccessType = "Private" +) + +// VersionGateAckType specifies the version gate acknowledgment. +type VersionGateAckType string + +const ( + // Acknowledge if acknowledgment is required and proceed with the upgrade. + Acknowledge VersionGateAckType = "Acknowledge" + + // WaitForAcknowledge if acknowledgment is required, wait not to proceed with the upgrade. + WaitForAcknowledge VersionGateAckType = "WaitForAcknowledge" + + // AlwaysAcknowledge always acknowledg if required and proceed with the upgrade. + AlwaysAcknowledge VersionGateAckType = "AlwaysAcknowledge" +) + +// ChannelGroupType specifies the OpenShift version channel group. +type ChannelGroupType string + +const ( + // Stable channel group is the default channel group for stable releases. + Stable ChannelGroupType = "stable" + + // Eus channel group is for eus channel releases. + Eus ChannelGroupType = "eus" + + // Fast channel group is for fast channel releases. + Fast ChannelGroupType = "fast" + + // Candidate channel group is for testing candidate builds. + Candidate ChannelGroupType = "candidate" + + // Nightly channel group is for testing nigtly builds. + Nightly ChannelGroupType = "nightly" +) + +// AutoNodeMode specifies the AutoNode mode for the ROSA Control Plane. +type AutoNodeMode string + +const ( + // AutoNodeModeEnabled enable AutoNode + AutoNodeModeEnabled AutoNodeMode = "Enabled" + + // AutoNodeModeDisabled Disabled AutoNode + AutoNodeModeDisabled AutoNodeMode = "Disabled" +) + +// RosaControlPlaneSpec defines the desired state of ROSAControlPlane. +type RosaControlPlaneSpec struct { //nolint: maligned + // Cluster name must be valid DNS-1035 label, so it must consist of lower case alphanumeric + // characters or '-', start with an alphabetic character, end with an alphanumeric character + // and have a max length of 54 characters. + // + // +immutable + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="rosaClusterName is immutable" + // +kubebuilder:validation:MaxLength:=54 + // +kubebuilder:validation:Pattern:=`^[a-z]([-a-z0-9]*[a-z0-9])?$` + RosaClusterName string `json:"rosaClusterName"` + + // DomainPrefix is an optional prefix added to the cluster's domain name. It will be used + // when generating a sub-domain for the cluster on openshiftapps domain. It must be valid DNS-1035 label + // consisting of lower case alphanumeric characters or '-', start with an alphabetic character + // end with an alphanumeric character and have a max length of 15 characters. + // + // +immutable + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="domainPrefix is immutable" + // +kubebuilder:validation:MaxLength:=15 + // +kubebuilder:validation:Pattern:=`^[a-z]([-a-z0-9]*[a-z0-9])?$` + // +optional + DomainPrefix string `json:"domainPrefix,omitempty"` + + // The Subnet IDs to use when installing the cluster. + // SubnetIDs should come in pairs; two per availability zone, one private and one public. + // +optional + Subnets []string `json:"subnets,omitempty"` + + // AvailabilityZones describe AWS AvailabilityZones of the worker nodes. + // should match the AvailabilityZones of the provided Subnets. + // a machinepool will be created for each availabilityZone. + // +optional + AvailabilityZones []string `json:"availabilityZones,omitempty"` + + // The AWS Region the cluster lives in. + Region string `json:"region"` + + // OpenShift semantic version, for example "4.14.5". + Version string `json:"version"` + + // OpenShift version channel group, default is stable. + // + // +kubebuilder:validation:Enum=stable;eus;fast;candidate;nightly + // +kubebuilder:default=stable + ChannelGroup ChannelGroupType `json:"channelGroup"` + + // VersionGate requires acknowledgment when upgrading ROSA-HCP y-stream versions (e.g., from 4.15 to 4.16). + // Default is WaitForAcknowledge. + // WaitForAcknowledge: If acknowledgment is required, the upgrade will not proceed until VersionGate is set to Acknowledge or AlwaysAcknowledge. + // Acknowledge: If acknowledgment is required, apply it for the upgrade. After upgrade is done set the version gate to WaitForAcknowledge. + // AlwaysAcknowledge: If acknowledgment is required, apply it and proceed with the upgrade. + // + // +kubebuilder:validation:Enum=Acknowledge;WaitForAcknowledge;AlwaysAcknowledge + // +kubebuilder:default=WaitForAcknowledge + VersionGate VersionGateAckType `json:"versionGate"` + + // RosaRoleConfigRef is a reference to a RosaRoleConfig resource that contains account roles, operator roles and OIDC configuration. + // RosaRoleConfigRef and role fields such as installerRoleARN, supportRoleARN, workerRoleARN, rolesRef and oidcID are mutually exclusive. + // + // +optional + RosaRoleConfigRef *corev1.LocalObjectReference `json:"rosaRoleConfigRef,omitempty"` + + // AWS IAM roles used to perform credential requests by the openshift operators. + // Required if RosaRoleConfigRef is not specified. + // +optional + RolesRef AWSRolesRef `json:"rolesRef,omitempty"` + + // The ID of the internal OpenID Connect Provider. + // Required if RosaRoleConfigRef is not specified. + // + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="oidcID is immutable" + // +optional + OIDCID string `json:"oidcID,omitempty"` + + // EnableExternalAuthProviders enables external authentication configuration for the cluster. + // + // +kubebuilder:default=false + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="enableExternalAuthProviders is immutable" + // +optional + EnableExternalAuthProviders bool `json:"enableExternalAuthProviders,omitempty"` + + // ExternalAuthProviders are external OIDC identity providers that can issue tokens for this cluster. + // Can only be set if "enableExternalAuthProviders" is set to "True". + // + // At most one provider can be configured. + // + // +listType=map + // +listMapKey=name + // +kubebuilder:validation:MaxItems=1 + ExternalAuthProviders []ExternalAuthProvider `json:"externalAuthProviders,omitempty"` + + // InstallerRoleARN is an AWS IAM role that OpenShift Cluster Manager will assume to create the cluster. + // Required if RosaRoleConfigRef is not specified. + // +optional + InstallerRoleARN string `json:"installerRoleARN,omitempty"` + // SupportRoleARN is an AWS IAM role used by Red Hat SREs to enable + // access to the cluster account in order to provide support. + // Required if RosaRoleConfigRef is not specified. + // +optional + SupportRoleARN string `json:"supportRoleARN,omitempty"` + // WorkerRoleARN is an AWS IAM role that will be attached to worker instances. + // Required if RosaRoleConfigRef is not specified. + // +optional + WorkerRoleARN string `json:"workerRoleARN,omitempty"` + + // BillingAccount is an optional AWS account to use for billing the subscription fees for ROSA HCP clusters. + // The cost of running each ROSA HCP cluster will be billed to the infrastructure account in which the cluster + // is running. + // + // +kubebuilder:validation:Optional + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="billingAccount is immutable" + // +kubebuilder:validation:XValidation:rule="self.matches('^[0-9]{12}$')", message="billingAccount must be a valid AWS account ID" + // +immutable + // +optional + BillingAccount string `json:"billingAccount,omitempty"` + + // DefaultMachinePoolSpec defines the configuration for the default machinepool(s) provisioned as part of the cluster creation. + // One MachinePool will be created with this configuration per AvailabilityZone. Those default machinepools are required for openshift cluster operators + // to work properly. + // As these machinepool not created using ROSAMachinePool CR, they will not be visible/managed by ROSA CAPI provider. + // `rosa list machinepools -c ` can be used to view those machinepools. + // + // This field will be removed in the future once the current limitation is resolved. + // + // +optional + DefaultMachinePoolSpec DefaultMachinePoolSpec `json:"defaultMachinePoolSpec,omitempty"` + + // Network config for the ROSA HCP cluster. + // +optional + Network *NetworkSpec `json:"network,omitempty"` + + // EndpointAccess specifies the publishing scope of cluster endpoints. The + // default is Public. + // + // +kubebuilder:validation:Enum=Public;Private + // +kubebuilder:default=Public + // +optional + EndpointAccess RosaEndpointAccessType `json:"endpointAccess,omitempty"` + + // AdditionalTags are user-defined tags to be added on the AWS resources associated with the control plane. + // +optional + AdditionalTags infrav1.Tags `json:"additionalTags,omitempty"` + + // EtcdEncryptionKMSARN is the ARN of the KMS key used to encrypt etcd. The key itself needs to be + // created out-of-band by the user and tagged with `red-hat:true`. + // +optional + EtcdEncryptionKMSARN string `json:"etcdEncryptionKMSARN,omitempty"` + + // AuditLogRoleARN defines the role that is used to forward audit logs to AWS CloudWatch. + // If not set, audit log forwarding is disabled. + // +optional + AuditLogRoleARN string `json:"auditLogRoleARN,omitempty"` + + // ProvisionShardID defines the shard where ROSA hosted control plane components will be hosted. + // + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="provisionShardID is immutable" + // +optional + ProvisionShardID string `json:"provisionShardID,omitempty"` + + // CredentialsSecretRef references a secret with necessary credentials to connect to the OCM API. + // The secret should contain the following data keys: + // - ocmToken: eyJhbGciOiJIUzI1NiIsI.... + // - ocmApiUrl: Optional, defaults to 'https://api.openshift.com' + // +optional + CredentialsSecretRef *corev1.LocalObjectReference `json:"credentialsSecretRef,omitempty"` + + // IdentityRef is a reference to an identity to be used when reconciling the managed control plane. + // If no identity is specified, the default identity for this controller will be used. + // + // +optional + IdentityRef *infrav1.AWSIdentityReference `json:"identityRef,omitempty"` + + // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. + // +optional + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` + + // ClusterRegistryConfig represents registry config used with the cluster. + // +optional + ClusterRegistryConfig *RegistryConfig `json:"clusterRegistryConfig,omitempty"` + + // autoNode set the autoNode mode and roleARN. + // +optional + AutoNode *AutoNode `json:"autoNode,omitempty"` + + // ROSANetworkRef references ROSANetwork custom resource that contains the networking infrastructure + // for the ROSA HCP cluster. + // +optional + ROSANetworkRef *corev1.LocalObjectReference `json:"rosaNetworkRef,omitempty"` +} + +// AutoNode set the AutoNode mode and AutoNode role ARN. +type AutoNode struct { + // mode specifies the mode for the AutoNode. Setting Enable/Disable mode will allows/disallow karpenter AutoNode scaling. + // +kubebuilder:validation:Enum=Enabled;Disabled + // +kubebuilder:default=Disabled + // +optional + Mode AutoNodeMode `json:"mode,omitempty"` + + // roleARN sets the autoNode role ARN, which includes the IAM policy and cluster-specific role that grant the necessary permissions to the Karpenter controller. + // The role must be attached with the same OIDC-ID that is used with the ROSA-HCP cluster. + // +kubebuilder:validation:MaxLength:=2048 + // +optional + RoleARN string `json:"roleARN,omitempty"` +} + +// RegistryConfig for ROSA-HCP cluster +type RegistryConfig struct { + // AdditionalTrustedCAs containing the registry hostname as the key, and the PEM-encoded certificate as the value, + // for each additional registry CA to trust. + // +optional + AdditionalTrustedCAs map[string]string `json:"additionalTrustedCAs,omitempty"` + + // AllowedRegistriesForImport limits the container image registries that normal users may import + // images from. Set this list to the registries that you trust to contain valid Docker + // images and that you want applications to be able to import from. + // +optional + AllowedRegistriesForImport []RegistryLocation `json:"allowedRegistriesForImport,omitempty"` + + // RegistrySources contains configuration that determines how the container runtime + // should treat individual registries when accessing images. It does not contain configuration + // for the internal cluster registry. AllowedRegistries, BlockedRegistries are mutually exclusive. + // +optional + RegistrySources *RegistrySources `json:"registrySources,omitempty"` +} + +// RegistryLocation contains a location of the registry specified by the registry domain name. +type RegistryLocation struct { + // domainName specifies a domain name for the registry. The domain name might include wildcards, like '*' or '??'. + // In case the registry use non-standard (80 or 443) port, the port should be included in the domain name as well. + // +optional + DomainName string `json:"domainName,omitempty"` + + // insecure indicates whether the registry is secure (https) or insecure (http), default is secured. + // +kubebuilder:default=false + // +optional + Insecure bool `json:"insecure,omitempty"` +} + +// RegistrySources contains registries configuration. +type RegistrySources struct { + // AllowedRegistries are the registries for which image pull and push actions are allowed. + // To specify all subdomains, add the asterisk (*) wildcard character as a prefix to the domain name, + // For example, *.example.com. + // You can specify an individual repository within a registry, For example: reg1.io/myrepo/myapp:latest. + // All other registries are blocked. + // +optional + AllowedRegistries []string `json:"allowedRegistries,omitempty"` + + // BlockedRegistries are the registries for which image pull and push actions are denied. + // To specify all subdomains, add the asterisk (*) wildcard character as a prefix to the domain name, + // For example, *.example.com. + // You can specify an individual repository within a registry, For example: reg1.io/myrepo/myapp:latest. + // All other registries are allowed. + // +optional + BlockedRegistries []string `json:"blockedRegistries,omitempty"` + + // InsecureRegistries are registries which do not have a valid TLS certificate or only support HTTP connections. + // To specify all subdomains, add the asterisk (*) wildcard character as a prefix to the domain name, + // For example, *.example.com. + // You can specify an individual repository within a registry, For example: reg1.io/myrepo/myapp:latest. + // +optional + InsecureRegistries []string `json:"insecureRegistries,omitempty"` +} + +// NetworkSpec for ROSA-HCP. +type NetworkSpec struct { + // IP addresses block used by OpenShift while installing the cluster, for example "10.0.0.0/16". + // +kubebuilder:validation:Format=cidr + // +optional + MachineCIDR string `json:"machineCIDR,omitempty"` + + // IP address block from which to assign pod IP addresses, for example `10.128.0.0/14`. + // +kubebuilder:validation:Format=cidr + // +optional + PodCIDR string `json:"podCIDR,omitempty"` + + // IP address block from which to assign service IP addresses, for example `172.30.0.0/16`. + // +kubebuilder:validation:Format=cidr + // +optional + ServiceCIDR string `json:"serviceCIDR,omitempty"` + + // Network host prefix which is defaulted to `23` if not specified. + // +kubebuilder:default=23 + // +optional + HostPrefix int `json:"hostPrefix,omitempty"` + + // The CNI network type default is OVNKubernetes. + // +kubebuilder:validation:Enum=OVNKubernetes;Other + // +kubebuilder:default=OVNKubernetes + // +optional + NetworkType string `json:"networkType,omitempty"` +} + +// DefaultMachinePoolSpec defines the configuration for the required worker nodes provisioned as part of the cluster creation. +type DefaultMachinePoolSpec struct { + // The instance type to use, for example `r5.xlarge`. Instance type ref; https://aws.amazon.com/ec2/instance-types/ + // +optional + InstanceType string `json:"instanceType,omitempty"` + + // Autoscaling specifies auto scaling behaviour for the default MachinePool. Autoscaling min/max value + // must be equal or multiple of the availability zones count. + // +optional + Autoscaling *AutoScaling `json:"autoscaling,omitempty"` + + // VolumeSize set the disk volume size for the default workers machine pool in Gib. The default is 300 GiB. + // +kubebuilder:validation:Minimum=75 + // +kubebuilder:validation:Maximum=16384 + // +immutable + // +optional + VolumeSize int `json:"volumeSize,omitempty"` +} + +// AutoScaling specifies scaling options. +type AutoScaling struct { + // +kubebuilder:validation:Minimum=1 + MinReplicas int `json:"minReplicas,omitempty"` + // +kubebuilder:validation:Minimum=1 + MaxReplicas int `json:"maxReplicas,omitempty"` +} + +// AWSRolesRef contains references to various AWS IAM roles required for operators to make calls against the AWS API. +type AWSRolesRef struct { + // The referenced role must have a trust relationship that allows it to be assumed via web identity. + // https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html. + // Example: + // { + // "Version": "2012-10-17", + // "Statement": [ + // { + // "Effect": "Allow", + // "Principal": { + // "Federated": "{{ .ProviderARN }}" + // }, + // "Action": "sts:AssumeRoleWithWebIdentity", + // "Condition": { + // "StringEquals": { + // "{{ .ProviderName }}:sub": {{ .ServiceAccounts }} + // } + // } + // } + // ] + // } + // + // IngressARN is an ARN value referencing a role appropriate for the Ingress Operator. + // + // The following is an example of a valid policy document: + // + // { + // "Version": "2012-10-17", + // "Statement": [ + // { + // "Effect": "Allow", + // "Action": [ + // "elasticloadbalancing:DescribeLoadBalancers", + // "tag:GetResources", + // "route53:ListHostedZones" + // ], + // "Resource": "*" + // }, + // { + // "Effect": "Allow", + // "Action": [ + // "route53:ChangeResourceRecordSets" + // ], + // "Resource": [ + // "arn:aws:route53:::PUBLIC_ZONE_ID", + // "arn:aws:route53:::PRIVATE_ZONE_ID" + // ] + // } + // ] + // } + IngressARN string `json:"ingressARN"` + + // ImageRegistryARN is an ARN value referencing a role appropriate for the Image Registry Operator. + // + // The following is an example of a valid policy document: + // + // { + // "Version": "2012-10-17", + // "Statement": [ + // { + // "Effect": "Allow", + // "Action": [ + // "s3:CreateBucket", + // "s3:DeleteBucket", + // "s3:PutBucketTagging", + // "s3:GetBucketTagging", + // "s3:PutBucketPublicAccessBlock", + // "s3:GetBucketPublicAccessBlock", + // "s3:PutEncryptionConfiguration", + // "s3:GetEncryptionConfiguration", + // "s3:PutLifecycleConfiguration", + // "s3:GetLifecycleConfiguration", + // "s3:GetBucketLocation", + // "s3:ListBucket", + // "s3:GetObject", + // "s3:PutObject", + // "s3:DeleteObject", + // "s3:ListBucketMultipartUploads", + // "s3:AbortMultipartUpload", + // "s3:ListMultipartUploadParts" + // ], + // "Resource": "*" + // } + // ] + // } + ImageRegistryARN string `json:"imageRegistryARN"` + + // StorageARN is an ARN value referencing a role appropriate for the Storage Operator. + // + // The following is an example of a valid policy document: + // + // { + // "Version": "2012-10-17", + // "Statement": [ + // { + // "Effect": "Allow", + // "Action": [ + // "ec2:AttachVolume", + // "ec2:CreateSnapshot", + // "ec2:CreateTags", + // "ec2:CreateVolume", + // "ec2:DeleteSnapshot", + // "ec2:DeleteTags", + // "ec2:DeleteVolume", + // "ec2:DescribeInstances", + // "ec2:DescribeSnapshots", + // "ec2:DescribeTags", + // "ec2:DescribeVolumes", + // "ec2:DescribeVolumesModifications", + // "ec2:DetachVolume", + // "ec2:ModifyVolume" + // ], + // "Resource": "*" + // } + // ] + // } + StorageARN string `json:"storageARN"` + + // NetworkARN is an ARN value referencing a role appropriate for the Network Operator. + // + // The following is an example of a valid policy document: + // + // { + // "Version": "2012-10-17", + // "Statement": [ + // { + // "Effect": "Allow", + // "Action": [ + // "ec2:DescribeInstances", + // "ec2:DescribeInstanceStatus", + // "ec2:DescribeInstanceTypes", + // "ec2:UnassignPrivateIpAddresses", + // "ec2:AssignPrivateIpAddresses", + // "ec2:UnassignIpv6Addresses", + // "ec2:AssignIpv6Addresses", + // "ec2:DescribeSubnets", + // "ec2:DescribeNetworkInterfaces" + // ], + // "Resource": "*" + // } + // ] + // } + NetworkARN string `json:"networkARN"` + + // KubeCloudControllerARN is an ARN value referencing a role appropriate for the KCM/KCC. + // Source: https://cloud-provider-aws.sigs.k8s.io/prerequisites/#iam-policies + // + // The following is an example of a valid policy document: + // + // { + // "Version": "2012-10-17", + // "Statement": [ + // { + // "Action": [ + // "autoscaling:DescribeAutoScalingGroups", + // "autoscaling:DescribeLaunchConfigurations", + // "autoscaling:DescribeTags", + // "ec2:DescribeAvailabilityZones", + // "ec2:DescribeInstances", + // "ec2:DescribeImages", + // "ec2:DescribeRegions", + // "ec2:DescribeRouteTables", + // "ec2:DescribeSecurityGroups", + // "ec2:DescribeSubnets", + // "ec2:DescribeVolumes", + // "ec2:CreateSecurityGroup", + // "ec2:CreateTags", + // "ec2:CreateVolume", + // "ec2:ModifyInstanceAttribute", + // "ec2:ModifyVolume", + // "ec2:AttachVolume", + // "ec2:AuthorizeSecurityGroupIngress", + // "ec2:CreateRoute", + // "ec2:DeleteRoute", + // "ec2:DeleteSecurityGroup", + // "ec2:DeleteVolume", + // "ec2:DetachVolume", + // "ec2:RevokeSecurityGroupIngress", + // "ec2:DescribeVpcs", + // "elasticloadbalancing:AddTags", + // "elasticloadbalancing:AttachLoadBalancerToSubnets", + // "elasticloadbalancing:ApplySecurityGroupsToLoadBalancer", + // "elasticloadbalancing:CreateLoadBalancer", + // "elasticloadbalancing:CreateLoadBalancerPolicy", + // "elasticloadbalancing:CreateLoadBalancerListeners", + // "elasticloadbalancing:ConfigureHealthCheck", + // "elasticloadbalancing:DeleteLoadBalancer", + // "elasticloadbalancing:DeleteLoadBalancerListeners", + // "elasticloadbalancing:DescribeLoadBalancers", + // "elasticloadbalancing:DescribeLoadBalancerAttributes", + // "elasticloadbalancing:DetachLoadBalancerFromSubnets", + // "elasticloadbalancing:DeregisterInstancesFromLoadBalancer", + // "elasticloadbalancing:ModifyLoadBalancerAttributes", + // "elasticloadbalancing:RegisterInstancesWithLoadBalancer", + // "elasticloadbalancing:SetLoadBalancerPoliciesForBackendServer", + // "elasticloadbalancing:AddTags", + // "elasticloadbalancing:CreateListener", + // "elasticloadbalancing:CreateTargetGroup", + // "elasticloadbalancing:DeleteListener", + // "elasticloadbalancing:DeleteTargetGroup", + // "elasticloadbalancing:DeregisterTargets", + // "elasticloadbalancing:DescribeListeners", + // "elasticloadbalancing:DescribeLoadBalancerPolicies", + // "elasticloadbalancing:DescribeTargetGroups", + // "elasticloadbalancing:DescribeTargetHealth", + // "elasticloadbalancing:ModifyListener", + // "elasticloadbalancing:ModifyTargetGroup", + // "elasticloadbalancing:RegisterTargets", + // "elasticloadbalancing:SetLoadBalancerPoliciesOfListener", + // "iam:CreateServiceLinkedRole", + // "kms:DescribeKey" + // ], + // "Resource": [ + // "*" + // ], + // "Effect": "Allow" + // } + // ] + // } + // +immutable + KubeCloudControllerARN string `json:"kubeCloudControllerARN"` + + // NodePoolManagementARN is an ARN value referencing a role appropriate for the CAPI Controller. + // + // The following is an example of a valid policy document: + // + // { + // "Version": "2012-10-17", + // "Statement": [ + // { + // "Action": [ + // "ec2:AssociateRouteTable", + // "ec2:AttachInternetGateway", + // "ec2:AuthorizeSecurityGroupIngress", + // "ec2:CreateInternetGateway", + // "ec2:CreateNatGateway", + // "ec2:CreateRoute", + // "ec2:CreateRouteTable", + // "ec2:CreateSecurityGroup", + // "ec2:CreateSubnet", + // "ec2:CreateTags", + // "ec2:DeleteInternetGateway", + // "ec2:DeleteNatGateway", + // "ec2:DeleteRouteTable", + // "ec2:DeleteSecurityGroup", + // "ec2:DeleteSubnet", + // "ec2:DeleteTags", + // "ec2:DescribeAccountAttributes", + // "ec2:DescribeAddresses", + // "ec2:DescribeAvailabilityZones", + // "ec2:DescribeImages", + // "ec2:DescribeInstances", + // "ec2:DescribeInternetGateways", + // "ec2:DescribeNatGateways", + // "ec2:DescribeNetworkInterfaces", + // "ec2:DescribeNetworkInterfaceAttribute", + // "ec2:DescribeRouteTables", + // "ec2:DescribeSecurityGroups", + // "ec2:DescribeSubnets", + // "ec2:DescribeVpcs", + // "ec2:DescribeVpcAttribute", + // "ec2:DescribeVolumes", + // "ec2:DetachInternetGateway", + // "ec2:DisassociateRouteTable", + // "ec2:DisassociateAddress", + // "ec2:ModifyInstanceAttribute", + // "ec2:ModifyNetworkInterfaceAttribute", + // "ec2:ModifySubnetAttribute", + // "ec2:RevokeSecurityGroupIngress", + // "ec2:RunInstances", + // "ec2:TerminateInstances", + // "tag:GetResources", + // "ec2:CreateLaunchTemplate", + // "ec2:CreateLaunchTemplateVersion", + // "ec2:DescribeLaunchTemplates", + // "ec2:DescribeLaunchTemplateVersions", + // "ec2:DeleteLaunchTemplate", + // "ec2:DeleteLaunchTemplateVersions" + // ], + // "Resource": [ + // "*" + // ], + // "Effect": "Allow" + // }, + // { + // "Condition": { + // "StringLike": { + // "iam:AWSServiceName": "elasticloadbalancing.amazonaws.com" + // } + // }, + // "Action": [ + // "iam:CreateServiceLinkedRole" + // ], + // "Resource": [ + // "arn:*:iam::*:role/aws-service-role/elasticloadbalancing.amazonaws.com/AWSServiceRoleForElasticLoadBalancing" + // ], + // "Effect": "Allow" + // }, + // { + // "Action": [ + // "iam:PassRole" + // ], + // "Resource": [ + // "arn:*:iam::*:role/*-worker-role" + // ], + // "Effect": "Allow" + // }, + // { + // "Effect": "Allow", + // "Action": [ + // "kms:Decrypt", + // "kms:ReEncrypt", + // "kms:GenerateDataKeyWithoutPlainText", + // "kms:DescribeKey" + // ], + // "Resource": "*" + // }, + // { + // "Effect": "Allow", + // "Action": [ + // "kms:CreateGrant" + // ], + // "Resource": "*", + // "Condition": { + // "Bool": { + // "kms:GrantIsForAWSResource": true + // } + // } + // } + // ] + // } + // + // +immutable + NodePoolManagementARN string `json:"nodePoolManagementARN"` + + // ControlPlaneOperatorARN is an ARN value referencing a role appropriate for the Control Plane Operator. + // + // The following is an example of a valid policy document: + // + // { + // "Version": "2012-10-17", + // "Statement": [ + // { + // "Effect": "Allow", + // "Action": [ + // "ec2:CreateVpcEndpoint", + // "ec2:DescribeVpcEndpoints", + // "ec2:ModifyVpcEndpoint", + // "ec2:DeleteVpcEndpoints", + // "ec2:CreateTags", + // "route53:ListHostedZones", + // "ec2:CreateSecurityGroup", + // "ec2:AuthorizeSecurityGroupIngress", + // "ec2:AuthorizeSecurityGroupEgress", + // "ec2:DeleteSecurityGroup", + // "ec2:RevokeSecurityGroupIngress", + // "ec2:RevokeSecurityGroupEgress", + // "ec2:DescribeSecurityGroups", + // "ec2:DescribeVpcs", + // ], + // "Resource": "*" + // }, + // { + // "Effect": "Allow", + // "Action": [ + // "route53:ChangeResourceRecordSets", + // "route53:ListResourceRecordSets" + // ], + // "Resource": "arn:aws:route53:::%s" + // } + // ] + // } + // +immutable + ControlPlaneOperatorARN string `json:"controlPlaneOperatorARN"` + KMSProviderARN string `json:"kmsProviderARN"` +} + +// RosaControlPlaneStatus defines the observed state of ROSAControlPlane. +type RosaControlPlaneStatus struct { + // ExternalManagedControlPlane indicates to cluster-api that the control plane + // is managed by an external service such as AKS, EKS, GKE, etc. + // +kubebuilder:default=true + ExternalManagedControlPlane *bool `json:"externalManagedControlPlane,omitempty"` + // Initialized denotes whether or not the control plane has the + // uploaded kubernetes config-map. + // +optional + Initialized bool `json:"initialized"` + // Ready denotes that the ROSAControlPlane API Server is ready to receive requests. + // +kubebuilder:default=false + Ready bool `json:"ready"` + // FailureMessage will be set in the event that there is a terminal problem + // reconciling the state and will be set to a descriptive error message. + // + // This field should not be set for transitive errors that a controller + // faces that are expected to be fixed automatically over + // time (like service outages), but instead indicate that something is + // fundamentally wrong with the spec or the configuration of + // the controller, and that manual intervention is required. + // + // +optional + FailureMessage *string `json:"failureMessage,omitempty"` + // Conditions specifies the conditions for the managed control plane + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` + + // ID is the cluster ID given by ROSA. + ID string `json:"id,omitempty"` + // ConsoleURL is the url for the openshift console. + ConsoleURL string `json:"consoleURL,omitempty"` + // OIDCEndpointURL is the endpoint url for the managed OIDC provider. + OIDCEndpointURL string `json:"oidcEndpointURL,omitempty"` + + // OpenShift semantic version, for example "4.14.5". + // +optional + Version string `json:"version"` + + // Available upgrades for the ROSA hosted control plane. + AvailableUpgrades []string `json:"availableUpgrades,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=rosacontrolplanes,shortName=rosacp,scope=Namespaced,categories=cluster-api +// +kubebuilder:storageversion +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".metadata.labels.cluster\\.x-k8s\\.io/cluster-name",description="Cluster to which this RosaControl belongs" +// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.ready",description="Control plane infrastructure is ready for worker nodes" +// +k8s:defaulter-gen=true + +// ROSAControlPlane is the Schema for the ROSAControlPlanes API. +type ROSAControlPlane struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec RosaControlPlaneSpec `json:"spec,omitempty"` + Status RosaControlPlaneStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// ROSAControlPlaneList contains a list of ROSAControlPlane. +type ROSAControlPlaneList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ROSAControlPlane `json:"items"` +} + +// GetConditions returns the control planes conditions. +func (r *ROSAControlPlane) GetConditions() clusterv1beta1.Conditions { + return r.Status.Conditions +} + +// SetConditions sets the status conditions for the AWSManagedControlPlane. +func (r *ROSAControlPlane) SetConditions(conditions clusterv1beta1.Conditions) { + r.Status.Conditions = conditions +} + +func init() { + SchemeBuilder.Register(&ROSAControlPlane{}, &ROSAControlPlaneList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/rosacontrolplane_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/rosacontrolplane_webhook.go new file mode 100644 index 000000000000..21618bcec355 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/rosacontrolplane_webhook.go @@ -0,0 +1,292 @@ +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "context" + "fmt" + "net" + + "github.com/blang/semver" + kmsArnRegexpValidator "github.com/openshift-online/ocm-common/pkg/resource/validations" + apierrors "k8s.io/apimachinery/pkg/api/errors" + runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// SetupWebhookWithManager will setup the webhooks for the ROSAControlPlane. +func (r *ROSAControlPlane) SetupWebhookWithManager(mgr ctrl.Manager) error { + w := new(rosaControlPlaneWebhook) + return ctrl.NewWebhookManagedBy(mgr). + For(r). + WithValidator(w). + WithDefaulter(w). + Complete() +} + +// +kubebuilder:webhook:verbs=create;update,path=/validate-controlplane-cluster-x-k8s-io-v1beta2-rosacontrolplane,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=controlplane.cluster.x-k8s.io,resources=rosacontrolplanes,versions=v1beta2,name=validation.rosacontrolplanes.controlplane.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 +// +kubebuilder:webhook:verbs=create;update,path=/mutate-controlplane-cluster-x-k8s-io-v1beta2-rosacontrolplane,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=controlplane.cluster.x-k8s.io,resources=rosacontrolplanes,versions=v1beta2,name=default.rosacontrolplanes.controlplane.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 + +type rosaControlPlaneWebhook struct{} + +var _ webhook.CustomDefaulter = &rosaControlPlaneWebhook{} +var _ webhook.CustomValidator = &rosaControlPlaneWebhook{} + +// ValidateCreate implements admission.Validator. +func (*rosaControlPlaneWebhook) ValidateCreate(_ context.Context, obj runtime.Object) (warnings admission.Warnings, err error) { + r, ok := obj.(*ROSAControlPlane) + if !ok { + return nil, fmt.Errorf("expected an ROSAControlPlane object but got %T", r) + } + + var allErrs field.ErrorList + + if err := r.validateVersion(); err != nil { + allErrs = append(allErrs, err) + } + + if err := r.validateEtcdEncryptionKMSArn(); err != nil { + allErrs = append(allErrs, err) + } + + if err := r.validateExternalAuthProviders(); err != nil { + allErrs = append(allErrs, err) + } + + if err := r.validateClusterRegistryConfig(); err != nil { + allErrs = append(allErrs, err) + } + + if err := r.validateRosaRoleConfig(); err != nil { + allErrs = append(allErrs, err) + } + + allErrs = append(allErrs, r.validateNetwork()...) + allErrs = append(allErrs, r.Spec.AdditionalTags.Validate()...) + + if err := r.validateROSANetwork(); err != nil { + allErrs = append(allErrs, err) + } + + if len(allErrs) == 0 { + return nil, nil + } + + return nil, apierrors.NewInvalid( + r.GroupVersionKind().GroupKind(), + r.Name, + allErrs, + ) +} + +func (r *ROSAControlPlane) validateClusterRegistryConfig() *field.Error { + if r.Spec.ClusterRegistryConfig != nil { + if r.Spec.ClusterRegistryConfig.RegistrySources != nil { + if len(r.Spec.ClusterRegistryConfig.RegistrySources.AllowedRegistries) > 0 && len(r.Spec.ClusterRegistryConfig.RegistrySources.BlockedRegistries) > 0 { + return field.Invalid(field.NewPath("spec.clusterRegistryConfig.registrySources"), r.Spec.ClusterRegistryConfig.RegistrySources, "allowedRegistries and blockedRegistries are mutually exclusive fields") + } + } + } + + return nil +} + +// ValidateUpdate implements admission.Validator. +func (*rosaControlPlaneWebhook) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (warnings admission.Warnings, err error) { + r, ok := newObj.(*ROSAControlPlane) + if !ok { + return nil, fmt.Errorf("expected an ROSAControlPlane object but got %T", r) + } + + var allErrs field.ErrorList + + if err := r.validateVersion(); err != nil { + allErrs = append(allErrs, err) + } + + if err := r.validateEtcdEncryptionKMSArn(); err != nil { + allErrs = append(allErrs, err) + } + + if err := r.validateRosaRoleConfig(); err != nil { + allErrs = append(allErrs, err) + } + + allErrs = append(allErrs, r.validateNetwork()...) + allErrs = append(allErrs, r.Spec.AdditionalTags.Validate()...) + + if len(allErrs) == 0 { + return nil, nil + } + + return nil, apierrors.NewInvalid( + r.GroupVersionKind().GroupKind(), + r.Name, + allErrs, + ) +} + +// ValidateDelete implements admission.Validator. +func (*rosaControlPlaneWebhook) ValidateDelete(_ context.Context, obj runtime.Object) (warnings admission.Warnings, err error) { + return nil, nil +} + +func (r *ROSAControlPlane) validateVersion() *field.Error { + _, err := semver.Parse(r.Spec.Version) + if err != nil { + return field.Invalid(field.NewPath("spec.version"), r.Spec.Version, "must be a valid semantic version") + } + + return nil +} + +func (r *ROSAControlPlane) validateNetwork() field.ErrorList { + var allErrs field.ErrorList + if r.Spec.Network == nil { + return allErrs + } + + rootPath := field.NewPath("spec", "network") + + if r.Spec.Network.MachineCIDR != "" { + _, _, err := net.ParseCIDR(r.Spec.Network.MachineCIDR) + if err != nil { + allErrs = append(allErrs, field.Invalid(rootPath.Child("machineCIDR"), r.Spec.Network.MachineCIDR, "must be valid CIDR block")) + } + } + + if r.Spec.Network.PodCIDR != "" { + _, _, err := net.ParseCIDR(r.Spec.Network.PodCIDR) + if err != nil { + allErrs = append(allErrs, field.Invalid(rootPath.Child("podCIDR"), r.Spec.Network.PodCIDR, "must be valid CIDR block")) + } + } + + if r.Spec.Network.ServiceCIDR != "" { + _, _, err := net.ParseCIDR(r.Spec.Network.ServiceCIDR) + if err != nil { + allErrs = append(allErrs, field.Invalid(rootPath.Child("serviceCIDR"), r.Spec.Network.ServiceCIDR, "must be valid CIDR block")) + } + } + + return allErrs +} + +func (r *ROSAControlPlane) validateEtcdEncryptionKMSArn() *field.Error { + err := kmsArnRegexpValidator.ValidateKMSKeyARN(&r.Spec.EtcdEncryptionKMSARN) + if err != nil { + return field.Invalid(field.NewPath("spec.etcdEncryptionKMSARN"), r.Spec.EtcdEncryptionKMSARN, err.Error()) + } + + return nil +} + +func (r *ROSAControlPlane) validateExternalAuthProviders() *field.Error { + if !r.Spec.EnableExternalAuthProviders && len(r.Spec.ExternalAuthProviders) > 0 { + return field.Invalid(field.NewPath("spec.ExternalAuthProviders"), r.Spec.ExternalAuthProviders, + "can only be set if spec.EnableExternalAuthProviders is set to 'True'") + } + + return nil +} + +func (r *ROSAControlPlane) validateRosaRoleConfig() *field.Error { + hasRoleFields := r.Spec.OIDCID != "" || r.Spec.InstallerRoleARN != "" || r.Spec.SupportRoleARN != "" || r.Spec.WorkerRoleARN != "" || + r.Spec.RolesRef.IngressARN != "" || r.Spec.RolesRef.ImageRegistryARN != "" || r.Spec.RolesRef.StorageARN != "" || + r.Spec.RolesRef.NetworkARN != "" || r.Spec.RolesRef.KubeCloudControllerARN != "" || r.Spec.RolesRef.NodePoolManagementARN != "" || + r.Spec.RolesRef.ControlPlaneOperatorARN != "" || r.Spec.RolesRef.KMSProviderARN != "" + + if r.Spec.RosaRoleConfigRef != nil { + if hasRoleFields { + return field.Invalid(field.NewPath("spec.rosaRoleConfigRef"), r.Spec.RosaRoleConfigRef, "RosaRoleConfigRef and role fields such as installerRoleARN, supportRoleARN, workerRoleARN, rolesRef and oidcID are mutually exclusive") + } + return nil + } + + if r.Spec.OIDCID == "" { + return field.Invalid(field.NewPath("spec.oidcID"), r.Spec.OIDCID, "must be specified") + } + if r.Spec.InstallerRoleARN == "" { + return field.Invalid(field.NewPath("spec.installerRoleARN"), r.Spec.InstallerRoleARN, "must be specified") + } + if r.Spec.SupportRoleARN == "" { + return field.Invalid(field.NewPath("spec.supportRoleARN"), r.Spec.SupportRoleARN, "must be specified") + } + if r.Spec.WorkerRoleARN == "" { + return field.Invalid(field.NewPath("spec.workerRoleARN"), r.Spec.WorkerRoleARN, "must be specified") + } + if r.Spec.RolesRef.IngressARN == "" { + return field.Invalid(field.NewPath("spec.rolesRef.ingressARN"), r.Spec.RolesRef.IngressARN, "must be specified") + } + if r.Spec.RolesRef.ImageRegistryARN == "" { + return field.Invalid(field.NewPath("spec.rolesRef.imageRegistryARN"), r.Spec.RolesRef.ImageRegistryARN, "must be specified") + } + if r.Spec.RolesRef.StorageARN == "" { + return field.Invalid(field.NewPath("spec.rolesRef.storageARN"), r.Spec.RolesRef.StorageARN, "must be specified") + } + if r.Spec.RolesRef.NetworkARN == "" { + return field.Invalid(field.NewPath("spec.rolesRef.networkARN"), r.Spec.RolesRef.NetworkARN, "must be specified") + } + if r.Spec.RolesRef.KubeCloudControllerARN == "" { + return field.Invalid(field.NewPath("spec.rolesRef.kubeCloudControllerARN"), r.Spec.RolesRef.KubeCloudControllerARN, "must be specified") + } + if r.Spec.RolesRef.NodePoolManagementARN == "" { + return field.Invalid(field.NewPath("spec.rolesRef.nodePoolManagementARN"), r.Spec.RolesRef.NodePoolManagementARN, "must be specified") + } + if r.Spec.RolesRef.ControlPlaneOperatorARN == "" { + return field.Invalid(field.NewPath("spec.rolesRef.controlPlaneOperatorARN"), r.Spec.RolesRef.ControlPlaneOperatorARN, "must be specified") + } + if r.Spec.RolesRef.KMSProviderARN == "" { + return field.Invalid(field.NewPath("spec.rolesRef.kmsProviderARN"), r.Spec.RolesRef.KMSProviderARN, "must be specified") + } + return nil +} + +func (r *ROSAControlPlane) validateROSANetwork() *field.Error { + if r.Spec.ROSANetworkRef != nil { + if r.Spec.Subnets != nil { + return field.Forbidden(field.NewPath("spec.rosaNetworkRef"), "spec.subnets and spec.rosaNetworkRef are mutually exclusive") + } + if r.Spec.AvailabilityZones != nil { + return field.Forbidden(field.NewPath("spec.rosaNetworkRef"), "spec.availabilityZones and spec.rosaNetworkRef are mutually exclusive") + } + } + + if r.Spec.ROSANetworkRef == nil && r.Spec.Subnets == nil { + return field.Required(field.NewPath("spec.subnets"), "spec.subnets cannot be empty when spec.rosaNetworkRef is unspecified") + } + + if r.Spec.ROSANetworkRef == nil && r.Spec.AvailabilityZones == nil { + return field.Required(field.NewPath("spec.availabilityZones"), "spec.availabilityZones cannot be empty when spec.rosaNetworkRef is unspecified") + } + + return nil +} + +// Default implements admission.Defaulter. +func (*rosaControlPlaneWebhook) Default(_ context.Context, obj runtime.Object) error { + r, ok := obj.(*ROSAControlPlane) + if !ok { + return fmt.Errorf("expected an ROSAControlPlane object but got %T", r) + } + + SetObjectDefaults_ROSAControlPlane(r) + return nil +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/zz_generated.deepcopy.go new file mode 100644 index 000000000000..8c6e718edb20 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/zz_generated.deepcopy.go @@ -0,0 +1,543 @@ +//go:build !ignore_autogenerated + +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by controller-gen. DO NOT EDIT. + +package v1beta2 + +import ( + "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" + apiv1beta2 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" + "sigs.k8s.io/cluster-api/api/core/v1beta1" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AWSRolesRef) DeepCopyInto(out *AWSRolesRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSRolesRef. +func (in *AWSRolesRef) DeepCopy() *AWSRolesRef { + if in == nil { + return nil + } + out := new(AWSRolesRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AutoNode) DeepCopyInto(out *AutoNode) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AutoNode. +func (in *AutoNode) DeepCopy() *AutoNode { + if in == nil { + return nil + } + out := new(AutoNode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AutoScaling) DeepCopyInto(out *AutoScaling) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AutoScaling. +func (in *AutoScaling) DeepCopy() *AutoScaling { + if in == nil { + return nil + } + out := new(AutoScaling) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DefaultMachinePoolSpec) DeepCopyInto(out *DefaultMachinePoolSpec) { + *out = *in + if in.Autoscaling != nil { + in, out := &in.Autoscaling, &out.Autoscaling + *out = new(AutoScaling) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DefaultMachinePoolSpec. +func (in *DefaultMachinePoolSpec) DeepCopy() *DefaultMachinePoolSpec { + if in == nil { + return nil + } + out := new(DefaultMachinePoolSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExternalAuthProvider) DeepCopyInto(out *ExternalAuthProvider) { + *out = *in + in.Issuer.DeepCopyInto(&out.Issuer) + if in.OIDCClients != nil { + in, out := &in.OIDCClients, &out.OIDCClients + *out = make([]OIDCClientConfig, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.ClaimMappings != nil { + in, out := &in.ClaimMappings, &out.ClaimMappings + *out = new(TokenClaimMappings) + (*in).DeepCopyInto(*out) + } + if in.ClaimValidationRules != nil { + in, out := &in.ClaimValidationRules, &out.ClaimValidationRules + *out = make([]TokenClaimValidationRule, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalAuthProvider. +func (in *ExternalAuthProvider) DeepCopy() *ExternalAuthProvider { + if in == nil { + return nil + } + out := new(ExternalAuthProvider) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LocalObjectReference) DeepCopyInto(out *LocalObjectReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LocalObjectReference. +func (in *LocalObjectReference) DeepCopy() *LocalObjectReference { + if in == nil { + return nil + } + out := new(LocalObjectReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NetworkSpec) DeepCopyInto(out *NetworkSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkSpec. +func (in *NetworkSpec) DeepCopy() *NetworkSpec { + if in == nil { + return nil + } + out := new(NetworkSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *OIDCClientConfig) DeepCopyInto(out *OIDCClientConfig) { + *out = *in + out.ClientSecret = in.ClientSecret + if in.ExtraScopes != nil { + in, out := &in.ExtraScopes, &out.ExtraScopes + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OIDCClientConfig. +func (in *OIDCClientConfig) DeepCopy() *OIDCClientConfig { + if in == nil { + return nil + } + out := new(OIDCClientConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PrefixedClaimMapping) DeepCopyInto(out *PrefixedClaimMapping) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PrefixedClaimMapping. +func (in *PrefixedClaimMapping) DeepCopy() *PrefixedClaimMapping { + if in == nil { + return nil + } + out := new(PrefixedClaimMapping) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSAControlPlane) DeepCopyInto(out *ROSAControlPlane) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSAControlPlane. +func (in *ROSAControlPlane) DeepCopy() *ROSAControlPlane { + if in == nil { + return nil + } + out := new(ROSAControlPlane) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ROSAControlPlane) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSAControlPlaneList) DeepCopyInto(out *ROSAControlPlaneList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ROSAControlPlane, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSAControlPlaneList. +func (in *ROSAControlPlaneList) DeepCopy() *ROSAControlPlaneList { + if in == nil { + return nil + } + out := new(ROSAControlPlaneList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ROSAControlPlaneList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RegistryConfig) DeepCopyInto(out *RegistryConfig) { + *out = *in + if in.AdditionalTrustedCAs != nil { + in, out := &in.AdditionalTrustedCAs, &out.AdditionalTrustedCAs + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.AllowedRegistriesForImport != nil { + in, out := &in.AllowedRegistriesForImport, &out.AllowedRegistriesForImport + *out = make([]RegistryLocation, len(*in)) + copy(*out, *in) + } + if in.RegistrySources != nil { + in, out := &in.RegistrySources, &out.RegistrySources + *out = new(RegistrySources) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RegistryConfig. +func (in *RegistryConfig) DeepCopy() *RegistryConfig { + if in == nil { + return nil + } + out := new(RegistryConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RegistryLocation) DeepCopyInto(out *RegistryLocation) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RegistryLocation. +func (in *RegistryLocation) DeepCopy() *RegistryLocation { + if in == nil { + return nil + } + out := new(RegistryLocation) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RegistrySources) DeepCopyInto(out *RegistrySources) { + *out = *in + if in.AllowedRegistries != nil { + in, out := &in.AllowedRegistries, &out.AllowedRegistries + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.BlockedRegistries != nil { + in, out := &in.BlockedRegistries, &out.BlockedRegistries + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.InsecureRegistries != nil { + in, out := &in.InsecureRegistries, &out.InsecureRegistries + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RegistrySources. +func (in *RegistrySources) DeepCopy() *RegistrySources { + if in == nil { + return nil + } + out := new(RegistrySources) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RosaControlPlaneSpec) DeepCopyInto(out *RosaControlPlaneSpec) { + *out = *in + if in.Subnets != nil { + in, out := &in.Subnets, &out.Subnets + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.AvailabilityZones != nil { + in, out := &in.AvailabilityZones, &out.AvailabilityZones + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.RosaRoleConfigRef != nil { + in, out := &in.RosaRoleConfigRef, &out.RosaRoleConfigRef + *out = new(v1.LocalObjectReference) + **out = **in + } + out.RolesRef = in.RolesRef + if in.ExternalAuthProviders != nil { + in, out := &in.ExternalAuthProviders, &out.ExternalAuthProviders + *out = make([]ExternalAuthProvider, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + in.DefaultMachinePoolSpec.DeepCopyInto(&out.DefaultMachinePoolSpec) + if in.Network != nil { + in, out := &in.Network, &out.Network + *out = new(NetworkSpec) + **out = **in + } + if in.AdditionalTags != nil { + in, out := &in.AdditionalTags, &out.AdditionalTags + *out = make(apiv1beta2.Tags, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.CredentialsSecretRef != nil { + in, out := &in.CredentialsSecretRef, &out.CredentialsSecretRef + *out = new(v1.LocalObjectReference) + **out = **in + } + if in.IdentityRef != nil { + in, out := &in.IdentityRef, &out.IdentityRef + *out = new(apiv1beta2.AWSIdentityReference) + **out = **in + } + out.ControlPlaneEndpoint = in.ControlPlaneEndpoint + if in.ClusterRegistryConfig != nil { + in, out := &in.ClusterRegistryConfig, &out.ClusterRegistryConfig + *out = new(RegistryConfig) + (*in).DeepCopyInto(*out) + } + if in.AutoNode != nil { + in, out := &in.AutoNode, &out.AutoNode + *out = new(AutoNode) + **out = **in + } + if in.ROSANetworkRef != nil { + in, out := &in.ROSANetworkRef, &out.ROSANetworkRef + *out = new(v1.LocalObjectReference) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RosaControlPlaneSpec. +func (in *RosaControlPlaneSpec) DeepCopy() *RosaControlPlaneSpec { + if in == nil { + return nil + } + out := new(RosaControlPlaneSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RosaControlPlaneStatus) DeepCopyInto(out *RosaControlPlaneStatus) { + *out = *in + if in.ExternalManagedControlPlane != nil { + in, out := &in.ExternalManagedControlPlane, &out.ExternalManagedControlPlane + *out = new(bool) + **out = **in + } + if in.FailureMessage != nil { + in, out := &in.FailureMessage, &out.FailureMessage + *out = new(string) + **out = **in + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(v1beta1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.AvailableUpgrades != nil { + in, out := &in.AvailableUpgrades, &out.AvailableUpgrades + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RosaControlPlaneStatus. +func (in *RosaControlPlaneStatus) DeepCopy() *RosaControlPlaneStatus { + if in == nil { + return nil + } + out := new(RosaControlPlaneStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TokenClaimMappings) DeepCopyInto(out *TokenClaimMappings) { + *out = *in + if in.Username != nil { + in, out := &in.Username, &out.Username + *out = new(UsernameClaimMapping) + (*in).DeepCopyInto(*out) + } + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = new(PrefixedClaimMapping) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TokenClaimMappings. +func (in *TokenClaimMappings) DeepCopy() *TokenClaimMappings { + if in == nil { + return nil + } + out := new(TokenClaimMappings) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TokenClaimValidationRule) DeepCopyInto(out *TokenClaimValidationRule) { + *out = *in + out.RequiredClaim = in.RequiredClaim +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TokenClaimValidationRule. +func (in *TokenClaimValidationRule) DeepCopy() *TokenClaimValidationRule { + if in == nil { + return nil + } + out := new(TokenClaimValidationRule) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TokenIssuer) DeepCopyInto(out *TokenIssuer) { + *out = *in + if in.Audiences != nil { + in, out := &in.Audiences, &out.Audiences + *out = make([]TokenAudience, len(*in)) + copy(*out, *in) + } + if in.CertificateAuthority != nil { + in, out := &in.CertificateAuthority, &out.CertificateAuthority + *out = new(LocalObjectReference) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TokenIssuer. +func (in *TokenIssuer) DeepCopy() *TokenIssuer { + if in == nil { + return nil + } + out := new(TokenIssuer) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TokenRequiredClaim) DeepCopyInto(out *TokenRequiredClaim) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TokenRequiredClaim. +func (in *TokenRequiredClaim) DeepCopy() *TokenRequiredClaim { + if in == nil { + return nil + } + out := new(TokenRequiredClaim) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *UsernameClaimMapping) DeepCopyInto(out *UsernameClaimMapping) { + *out = *in + if in.Prefix != nil { + in, out := &in.Prefix, &out.Prefix + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UsernameClaimMapping. +func (in *UsernameClaimMapping) DeepCopy() *UsernameClaimMapping { + if in == nil { + return nil + } + out := new(UsernameClaimMapping) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/zz_generated.defaults.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/zz_generated.defaults.go new file mode 100644 index 000000000000..60d82ff4d78d --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2/zz_generated.defaults.go @@ -0,0 +1,46 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by defaulter-gen. DO NOT EDIT. + +package v1beta2 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// RegisterDefaults adds defaulters functions to the given scheme. +// Public to allow building arbitrary schemes. +// All generated defaulters are covering - they call all nested defaulters. +func RegisterDefaults(scheme *runtime.Scheme) error { + scheme.AddTypeDefaultingFunc(&ROSAControlPlane{}, func(obj interface{}) { SetObjectDefaults_ROSAControlPlane(obj.(*ROSAControlPlane)) }) + scheme.AddTypeDefaultingFunc(&ROSAControlPlaneList{}, func(obj interface{}) { SetObjectDefaults_ROSAControlPlaneList(obj.(*ROSAControlPlaneList)) }) + return nil +} + +func SetObjectDefaults_ROSAControlPlane(in *ROSAControlPlane) { + SetDefaults_RosaControlPlaneSpec(&in.Spec) +} + +func SetObjectDefaults_ROSAControlPlaneList(in *ROSAControlPlaneList) { + for i := range in.Items { + a := &in.Items[i] + SetObjectDefaults_ROSAControlPlane(a) + } +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsfargateprofile_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsfargateprofile_types.go index 155ab4915a35..3bdcc0f5eb94 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsfargateprofile_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsfargateprofile_types.go @@ -23,15 +23,13 @@ import ( infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" iamv1 "sigs.k8s.io/cluster-api-provider-aws/v2/iam/api/v1beta1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) -var ( - // DefaultEKSFargateRole is the name of the default IAM role to use for fargate - // profiles if no other role is supplied in the spec and if iam role creation - // is not enabled. The default can be created using clusterawsadm or created manually. - DefaultEKSFargateRole = fmt.Sprintf("eks-fargate%s", iamv1.DefaultNameSuffix) -) +// DefaultEKSFargateRole is the name of the default IAM role to use for fargate +// profiles if no other role is supplied in the spec and if iam role creation +// is not enabled. The default can be created using clusterawsadm or created manually. +var DefaultEKSFargateRole = fmt.Sprintf("eks-fargate%s", iamv1.DefaultNameSuffix) // FargateProfileSpec defines the desired state of FargateProfile. type FargateProfileSpec struct { @@ -118,7 +116,7 @@ type FargateProfileStatus struct { // Conditions defines current state of the Fargate profile. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +kubebuilder:object:root=true @@ -139,12 +137,12 @@ type AWSFargateProfile struct { } // GetConditions returns the observations of the operational state of the AWSFargateProfile resource. -func (r *AWSFargateProfile) GetConditions() clusterv1.Conditions { +func (r *AWSFargateProfile) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSFargateProfile to the predescribed clusterv1.Conditions. -func (r *AWSFargateProfile) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSFargateProfile to the predescribed clusterv1betav1.Conditions. +func (r *AWSFargateProfile) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsmachinepool_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsmachinepool_types.go index fc70422c03a6..c4061baf12fb 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsmachinepool_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsmachinepool_types.go @@ -21,7 +21,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // Constants block. @@ -116,7 +116,7 @@ type AWSMachinePoolStatus struct { // Conditions defines current service state of the AWSMachinePool. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // Instances contains the status for each instance in the pool // +optional @@ -215,12 +215,12 @@ func init() { } // GetConditions returns the observations of the operational state of the AWSMachinePool resource. -func (r *AWSMachinePool) GetConditions() clusterv1.Conditions { +func (r *AWSMachinePool) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSMachinePool to the predescribed clusterv1.Conditions. -func (r *AWSMachinePool) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSMachinePool to the predescribed clusterv1beta1.Conditions. +func (r *AWSMachinePool) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsmanagedmachinepool_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsmanagedmachinepool_types.go index bd9632f95bc4..08fdd1d0c97f 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsmanagedmachinepool_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/awsmanagedmachinepool_types.go @@ -23,7 +23,7 @@ import ( infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" iamv1 "sigs.k8s.io/cluster-api-provider-aws/v2/iam/api/v1beta1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // ManagedMachineAMIType specifies which AWS AMI to use for a managed MachinePool. @@ -52,12 +52,10 @@ const ( ManagedMachinePoolCapacityTypeSpot ManagedMachinePoolCapacityType = "spot" ) -var ( - // DefaultEKSNodegroupRole is the name of the default IAM role to use for EKS nodegroups - // if no other role is supplied in the spec and if iam role creation is not enabled. The default - // can be created using clusterawsadm or created manually. - DefaultEKSNodegroupRole = fmt.Sprintf("eks-nodegroup%s", iamv1.DefaultNameSuffix) -) +// DefaultEKSNodegroupRole is the name of the default IAM role to use for EKS nodegroups +// if no other role is supplied in the spec and if iam role creation is not enabled. The default +// can be created using clusterawsadm or created manually. +var DefaultEKSNodegroupRole = fmt.Sprintf("eks-nodegroup%s", iamv1.DefaultNameSuffix) // AWSManagedMachinePoolSpec defines the desired state of AWSManagedMachinePool. type AWSManagedMachinePoolSpec struct { @@ -233,7 +231,7 @@ type AWSManagedMachinePoolStatus struct { // Conditions defines current service state of the managed machine pool // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +kubebuilder:object:root=true @@ -253,12 +251,12 @@ type AWSManagedMachinePool struct { } // GetConditions returns the observations of the operational state of the AWSManagedMachinePool resource. -func (r *AWSManagedMachinePool) GetConditions() clusterv1.Conditions { +func (r *AWSManagedMachinePool) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSManagedMachinePool to the predescribed clusterv1.Conditions. -func (r *AWSManagedMachinePool) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSManagedMachinePool to the predescribed clusterv1beta1.Conditions. +func (r *AWSManagedMachinePool) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/conditions_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/conditions_consts.go index 534ebb2bf987..0a9f7de1d08a 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/conditions_consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/conditions_consts.go @@ -16,11 +16,11 @@ limitations under the License. package v1beta1 -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" +import clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" const ( // ASGReadyCondition reports on current status of the autoscaling group. Ready indicates the group is provisioned. - ASGReadyCondition clusterv1.ConditionType = "ASGReady" + ASGReadyCondition clusterv1beta1.ConditionType = "ASGReady" // ASGNotFoundReason used when the autoscaling group couldn't be retrieved. ASGNotFoundReason = "ASGNotFound" // ASGProvisionFailedReason used for failures during autoscaling group provisioning. @@ -29,7 +29,7 @@ const ( ASGDeletionInProgress = "ASGDeletionInProgress" // LaunchTemplateReadyCondition represents the status of an AWSMachinePool's associated Launch Template. - LaunchTemplateReadyCondition clusterv1.ConditionType = "LaunchTemplateReady" + LaunchTemplateReadyCondition clusterv1beta1.ConditionType = "LaunchTemplateReady" // LaunchTemplateNotFoundReason is used when an associated Launch Template can't be found. LaunchTemplateNotFoundReason = "LaunchTemplateNotFound" // LaunchTemplateCreateFailedReason used for failures during Launch Template creation. @@ -38,9 +38,9 @@ const ( LaunchTemplateReconcileFailedReason = "LaunchTemplateReconcileFailed" // PreLaunchTemplateUpdateCheckCondition reports if all prerequisite are met for launch template update. - PreLaunchTemplateUpdateCheckCondition clusterv1.ConditionType = "PreLaunchTemplateUpdateCheckSuccess" + PreLaunchTemplateUpdateCheckCondition clusterv1beta1.ConditionType = "PreLaunchTemplateUpdateCheckSuccess" // PostLaunchTemplateUpdateOperationCondition reports on successfully completes post launch template update operation. - PostLaunchTemplateUpdateOperationCondition clusterv1.ConditionType = "PostLaunchTemplateUpdateOperationSuccess" + PostLaunchTemplateUpdateOperationCondition clusterv1beta1.ConditionType = "PostLaunchTemplateUpdateOperationSuccess" // PreLaunchTemplateUpdateCheckFailedReason used to report when not all prerequisite are met for launch template update. PreLaunchTemplateUpdateCheckFailedReason = "PreLaunchTemplateUpdateCheckFailed" @@ -48,7 +48,7 @@ const ( PostLaunchTemplateUpdateOperationFailedReason = "PostLaunchTemplateUpdateOperationFailed" // InstanceRefreshStartedCondition reports on successfully starting instance refresh. - InstanceRefreshStartedCondition clusterv1.ConditionType = "InstanceRefreshStarted" + InstanceRefreshStartedCondition clusterv1beta1.ConditionType = "InstanceRefreshStarted" // InstanceRefreshNotReadyReason used to report instance refresh is not initiated. // If there are instance refreshes that are in progress, then a new instance refresh request will fail. InstanceRefreshNotReadyReason = "InstanceRefreshNotReady" @@ -58,7 +58,7 @@ const ( const ( // EKSNodegroupReadyCondition condition reports on the successful reconciliation of eks control plane. - EKSNodegroupReadyCondition clusterv1.ConditionType = "EKSNodegroupReady" + EKSNodegroupReadyCondition clusterv1beta1.ConditionType = "EKSNodegroupReady" // EKSNodegroupReconciliationFailedReason used to report failures while reconciling EKS control plane. EKSNodegroupReconciliationFailedReason = "EKSNodegroupReconciliationFailed" // WaitingForEKSControlPlaneReason used when the machine pool is waiting for @@ -68,10 +68,10 @@ const ( const ( // EKSFargateProfileReadyCondition condition reports on the successful reconciliation of eks control plane. - EKSFargateProfileReadyCondition clusterv1.ConditionType = "EKSFargateProfileReady" + EKSFargateProfileReadyCondition clusterv1beta1.ConditionType = "EKSFargateProfileReady" // EKSFargateCreatingCondition condition reports on whether the fargate // profile is creating. - EKSFargateCreatingCondition clusterv1.ConditionType = "EKSFargateCreating" + EKSFargateCreatingCondition clusterv1beta1.ConditionType = "EKSFargateCreating" // EKSFargateDeletingCondition used to report that the profile is deleting. EKSFargateDeletingCondition = "EKSFargateDeleting" // EKSFargateReconciliationFailedReason used to report failures while reconciling EKS control plane. @@ -91,13 +91,13 @@ const ( const ( // IAMNodegroupRolesReadyCondition condition reports on the successful // reconciliation of EKS nodegroup iam roles. - IAMNodegroupRolesReadyCondition clusterv1.ConditionType = "IAMNodegroupRolesReady" + IAMNodegroupRolesReadyCondition clusterv1beta1.ConditionType = "IAMNodegroupRolesReady" // IAMNodegroupRolesReconciliationFailedReason used to report failures while // reconciling EKS nodegroup iam roles. IAMNodegroupRolesReconciliationFailedReason = "IAMNodegroupRolesReconciliationFailed" // IAMFargateRolesReadyCondition condition reports on the successful // reconciliation of EKS nodegroup iam roles. - IAMFargateRolesReadyCondition clusterv1.ConditionType = "IAMFargateRolesReady" + IAMFargateRolesReadyCondition clusterv1beta1.ConditionType = "IAMFargateRolesReady" // IAMFargateRolesReconciliationFailedReason used to report failures while // reconciling EKS nodegroup iam roles. IAMFargateRolesReconciliationFailedReason = "IAMFargateRolesReconciliationFailed" diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/conversion.go index cf4040a4567e..7b49ed9f64f1 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/conversion.go @@ -20,8 +20,6 @@ import ( apiconversion "k8s.io/apimachinery/pkg/conversion" "sigs.k8s.io/controller-runtime/pkg/conversion" - infrav1beta1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1" - infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" expinfrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2" utilconversion "sigs.k8s.io/cluster-api/util/conversion" ) @@ -149,6 +147,10 @@ func (src *AWSManagedMachinePool) ConvertTo(dstRaw conversion.Hub) error { dst.Spec.RolePath = restored.Spec.RolePath dst.Spec.RolePermissionsBoundary = restored.Spec.RolePermissionsBoundary + if restored.Spec.NodeRepairConfig != nil { + dst.Spec.NodeRepairConfig = restored.Spec.NodeRepairConfig + } + return nil } @@ -230,26 +232,6 @@ func (r *AWSFargateProfileList) ConvertFrom(srcRaw conversion.Hub) error { return Convert_v1beta2_AWSFargateProfileList_To_v1beta1_AWSFargateProfileList(src, r, nil) } -// Convert_v1beta1_AMIReference_To_v1beta2_AMIReference converts the v1beta1 AMIReference receiver to a v1beta2 AMIReference. -func Convert_v1beta1_AMIReference_To_v1beta2_AMIReference(in *infrav1beta1.AMIReference, out *infrav1.AMIReference, s apiconversion.Scope) error { - return infrav1beta1.Convert_v1beta1_AMIReference_To_v1beta2_AMIReference(in, out, s) -} - -// Convert_v1beta2_AMIReference_To_v1beta1_AMIReference converts the v1beta2 AMIReference receiver to a v1beta1 AMIReference. -func Convert_v1beta2_AMIReference_To_v1beta1_AMIReference(in *infrav1.AMIReference, out *infrav1beta1.AMIReference, s apiconversion.Scope) error { - return infrav1beta1.Convert_v1beta2_AMIReference_To_v1beta1_AMIReference(in, out, s) -} - -// Convert_v1beta2_Instance_To_v1beta1_Instance is a conversion function. -func Convert_v1beta2_Instance_To_v1beta1_Instance(in *infrav1.Instance, out *infrav1beta1.Instance, s apiconversion.Scope) error { - return infrav1beta1.Convert_v1beta2_Instance_To_v1beta1_Instance(in, out, s) -} - -// Convert_v1beta1_Instance_To_v1beta2_Instance is a conversion function. -func Convert_v1beta1_Instance_To_v1beta2_Instance(in *infrav1beta1.Instance, out *infrav1.Instance, s apiconversion.Scope) error { - return infrav1beta1.Convert_v1beta1_Instance_To_v1beta2_Instance(in, out, s) -} - // Convert_v1beta2_AWSLaunchTemplate_To_v1beta1_AWSLaunchTemplate converts the v1beta2 AWSLaunchTemplate receiver to a v1beta1 AWSLaunchTemplate. func Convert_v1beta2_AWSLaunchTemplate_To_v1beta1_AWSLaunchTemplate(in *expinfrav1.AWSLaunchTemplate, out *AWSLaunchTemplate, s apiconversion.Scope) error { return autoConvert_v1beta2_AWSLaunchTemplate_To_v1beta1_AWSLaunchTemplate(in, out, s) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/zz_generated.conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/zz_generated.conversion.go index 933a08f71655..e825e20a31d0 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/zz_generated.conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/zz_generated.conversion.go @@ -28,7 +28,7 @@ import ( runtime "k8s.io/apimachinery/pkg/runtime" apiv1beta2 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" v1beta2 "sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) func init() { @@ -63,11 +63,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSLaunchTemplate)(nil), (*AWSLaunchTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSLaunchTemplate_To_v1beta1_AWSLaunchTemplate(a.(*v1beta2.AWSLaunchTemplate), b.(*AWSLaunchTemplate), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*AWSMachinePool)(nil), (*v1beta2.AWSMachinePool)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_AWSMachinePool_To_v1beta2_AWSMachinePool(a.(*AWSMachinePool), b.(*v1beta2.AWSMachinePool), scope) }); err != nil { @@ -103,21 +98,11 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSMachinePoolSpec)(nil), (*AWSMachinePoolSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSMachinePoolSpec_To_v1beta1_AWSMachinePoolSpec(a.(*v1beta2.AWSMachinePoolSpec), b.(*AWSMachinePoolSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*AWSMachinePoolStatus)(nil), (*v1beta2.AWSMachinePoolStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_AWSMachinePoolStatus_To_v1beta2_AWSMachinePoolStatus(a.(*AWSMachinePoolStatus), b.(*v1beta2.AWSMachinePoolStatus), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSMachinePoolStatus)(nil), (*AWSMachinePoolStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSMachinePoolStatus_To_v1beta1_AWSMachinePoolStatus(a.(*v1beta2.AWSMachinePoolStatus), b.(*AWSMachinePoolStatus), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*AWSManagedMachinePool)(nil), (*v1beta2.AWSManagedMachinePool)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_AWSManagedMachinePool_To_v1beta2_AWSManagedMachinePool(a.(*AWSManagedMachinePool), b.(*v1beta2.AWSManagedMachinePool), scope) }); err != nil { @@ -143,11 +128,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AWSManagedMachinePoolSpec)(nil), (*AWSManagedMachinePoolSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AWSManagedMachinePoolSpec_To_v1beta1_AWSManagedMachinePoolSpec(a.(*v1beta2.AWSManagedMachinePoolSpec), b.(*AWSManagedMachinePoolSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*AWSManagedMachinePoolStatus)(nil), (*v1beta2.AWSManagedMachinePoolStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_AWSManagedMachinePoolStatus_To_v1beta2_AWSManagedMachinePoolStatus(a.(*AWSManagedMachinePoolStatus), b.(*v1beta2.AWSManagedMachinePoolStatus), scope) }); err != nil { @@ -163,11 +143,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.AutoScalingGroup)(nil), (*AutoScalingGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_AutoScalingGroup_To_v1beta1_AutoScalingGroup(a.(*v1beta2.AutoScalingGroup), b.(*AutoScalingGroup), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*BlockDeviceMapping)(nil), (*v1beta2.BlockDeviceMapping)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_BlockDeviceMapping_To_v1beta2_BlockDeviceMapping(a.(*BlockDeviceMapping), b.(*v1beta2.BlockDeviceMapping), scope) }); err != nil { @@ -193,11 +168,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.FargateProfileSpec)(nil), (*FargateProfileSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_FargateProfileSpec_To_v1beta1_FargateProfileSpec(a.(*v1beta2.FargateProfileSpec), b.(*FargateProfileSpec), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*FargateProfileStatus)(nil), (*v1beta2.FargateProfileStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_FargateProfileStatus_To_v1beta2_FargateProfileStatus(a.(*FargateProfileStatus), b.(*v1beta2.FargateProfileStatus), scope) }); err != nil { @@ -273,11 +243,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.RefreshPreferences)(nil), (*RefreshPreferences)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_RefreshPreferences_To_v1beta1_RefreshPreferences(a.(*v1beta2.RefreshPreferences), b.(*RefreshPreferences), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*Taint)(nil), (*v1beta2.Taint)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_Taint_To_v1beta2_Taint(a.(*Taint), b.(*v1beta2.Taint), scope) }); err != nil { @@ -298,11 +263,45 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } + if err := s.AddConversionFunc((*v1beta2.AWSLaunchTemplate)(nil), (*AWSLaunchTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSLaunchTemplate_To_v1beta1_AWSLaunchTemplate(a.(*v1beta2.AWSLaunchTemplate), b.(*AWSLaunchTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AWSMachinePoolSpec)(nil), (*AWSMachinePoolSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSMachinePoolSpec_To_v1beta1_AWSMachinePoolSpec(a.(*v1beta2.AWSMachinePoolSpec), b.(*AWSMachinePoolSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AWSMachinePoolStatus)(nil), (*AWSMachinePoolStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSMachinePoolStatus_To_v1beta1_AWSMachinePoolStatus(a.(*v1beta2.AWSMachinePoolStatus), b.(*AWSMachinePoolStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AWSManagedMachinePoolSpec)(nil), (*AWSManagedMachinePoolSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AWSManagedMachinePoolSpec_To_v1beta1_AWSManagedMachinePoolSpec(a.(*v1beta2.AWSManagedMachinePoolSpec), b.(*AWSManagedMachinePoolSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.AutoScalingGroup)(nil), (*AutoScalingGroup)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_AutoScalingGroup_To_v1beta1_AutoScalingGroup(a.(*v1beta2.AutoScalingGroup), b.(*AutoScalingGroup), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.FargateProfileSpec)(nil), (*FargateProfileSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_FargateProfileSpec_To_v1beta1_FargateProfileSpec(a.(*v1beta2.FargateProfileSpec), b.(*FargateProfileSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.RefreshPreferences)(nil), (*RefreshPreferences)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_RefreshPreferences_To_v1beta1_RefreshPreferences(a.(*v1beta2.RefreshPreferences), b.(*RefreshPreferences), scope) + }); err != nil { + return err + } return nil } func autoConvert_v1beta1_AWSFargateProfile_To_v1beta2_AWSFargateProfile(in *AWSFargateProfile, out *v1beta2.AWSFargateProfile, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_FargateProfileSpec_To_v1beta2_FargateProfileSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -319,7 +318,6 @@ func Convert_v1beta1_AWSFargateProfile_To_v1beta2_AWSFargateProfile(in *AWSFarga } func autoConvert_v1beta2_AWSFargateProfile_To_v1beta1_AWSFargateProfile(in *v1beta2.AWSFargateProfile, out *AWSFargateProfile, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_FargateProfileSpec_To_v1beta1_FargateProfileSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -336,7 +334,6 @@ func Convert_v1beta2_AWSFargateProfile_To_v1beta1_AWSFargateProfile(in *v1beta2. } func autoConvert_v1beta1_AWSFargateProfileList_To_v1beta2_AWSFargateProfileList(in *AWSFargateProfileList, out *v1beta2.AWSFargateProfileList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -358,7 +355,6 @@ func Convert_v1beta1_AWSFargateProfileList_To_v1beta2_AWSFargateProfileList(in * } func autoConvert_v1beta2_AWSFargateProfileList_To_v1beta1_AWSFargateProfileList(in *v1beta2.AWSFargateProfileList, out *AWSFargateProfileList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -423,7 +419,6 @@ func autoConvert_v1beta2_AWSLaunchTemplate_To_v1beta1_AWSLaunchTemplate(in *v1be } func autoConvert_v1beta1_AWSMachinePool_To_v1beta2_AWSMachinePool(in *AWSMachinePool, out *v1beta2.AWSMachinePool, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSMachinePoolSpec_To_v1beta2_AWSMachinePoolSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -440,7 +435,6 @@ func Convert_v1beta1_AWSMachinePool_To_v1beta2_AWSMachinePool(in *AWSMachinePool } func autoConvert_v1beta2_AWSMachinePool_To_v1beta1_AWSMachinePool(in *v1beta2.AWSMachinePool, out *AWSMachinePool, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSMachinePoolSpec_To_v1beta1_AWSMachinePoolSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -479,7 +473,6 @@ func Convert_v1beta2_AWSMachinePoolInstanceStatus_To_v1beta1_AWSMachinePoolInsta } func autoConvert_v1beta1_AWSMachinePoolList_To_v1beta2_AWSMachinePoolList(in *AWSMachinePoolList, out *v1beta2.AWSMachinePoolList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -501,7 +494,6 @@ func Convert_v1beta1_AWSMachinePoolList_To_v1beta2_AWSMachinePoolList(in *AWSMac } func autoConvert_v1beta2_AWSMachinePoolList_To_v1beta1_AWSMachinePoolList(in *v1beta2.AWSMachinePoolList, out *AWSMachinePoolList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -587,7 +579,7 @@ func autoConvert_v1beta2_AWSMachinePoolSpec_To_v1beta1_AWSMachinePoolSpec(in *v1 func autoConvert_v1beta1_AWSMachinePoolStatus_To_v1beta2_AWSMachinePoolStatus(in *AWSMachinePoolStatus, out *v1beta2.AWSMachinePoolStatus, s conversion.Scope) error { out.Ready = in.Ready out.Replicas = in.Replicas - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) out.Instances = *(*[]v1beta2.AWSMachinePoolInstanceStatus)(unsafe.Pointer(&in.Instances)) out.LaunchTemplateID = in.LaunchTemplateID out.LaunchTemplateVersion = (*string)(unsafe.Pointer(in.LaunchTemplateVersion)) @@ -605,7 +597,7 @@ func Convert_v1beta1_AWSMachinePoolStatus_To_v1beta2_AWSMachinePoolStatus(in *AW func autoConvert_v1beta2_AWSMachinePoolStatus_To_v1beta1_AWSMachinePoolStatus(in *v1beta2.AWSMachinePoolStatus, out *AWSMachinePoolStatus, s conversion.Scope) error { out.Ready = in.Ready out.Replicas = in.Replicas - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) out.Instances = *(*[]AWSMachinePoolInstanceStatus)(unsafe.Pointer(&in.Instances)) out.LaunchTemplateID = in.LaunchTemplateID out.LaunchTemplateVersion = (*string)(unsafe.Pointer(in.LaunchTemplateVersion)) @@ -617,7 +609,6 @@ func autoConvert_v1beta2_AWSMachinePoolStatus_To_v1beta1_AWSMachinePoolStatus(in } func autoConvert_v1beta1_AWSManagedMachinePool_To_v1beta2_AWSManagedMachinePool(in *AWSManagedMachinePool, out *v1beta2.AWSManagedMachinePool, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_AWSManagedMachinePoolSpec_To_v1beta2_AWSManagedMachinePoolSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -634,7 +625,6 @@ func Convert_v1beta1_AWSManagedMachinePool_To_v1beta2_AWSManagedMachinePool(in * } func autoConvert_v1beta2_AWSManagedMachinePool_To_v1beta1_AWSManagedMachinePool(in *v1beta2.AWSManagedMachinePool, out *AWSManagedMachinePool, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta2_AWSManagedMachinePoolSpec_To_v1beta1_AWSManagedMachinePoolSpec(&in.Spec, &out.Spec, s); err != nil { return err @@ -651,7 +641,6 @@ func Convert_v1beta2_AWSManagedMachinePool_To_v1beta1_AWSManagedMachinePool(in * } func autoConvert_v1beta1_AWSManagedMachinePoolList_To_v1beta2_AWSManagedMachinePoolList(in *AWSManagedMachinePoolList, out *v1beta2.AWSManagedMachinePoolList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -673,7 +662,6 @@ func Convert_v1beta1_AWSManagedMachinePoolList_To_v1beta2_AWSManagedMachinePoolL } func autoConvert_v1beta2_AWSManagedMachinePoolList_To_v1beta1_AWSManagedMachinePoolList(in *v1beta2.AWSManagedMachinePoolList, out *AWSManagedMachinePoolList, s conversion.Scope) error { - out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items @@ -760,6 +748,7 @@ func autoConvert_v1beta2_AWSManagedMachinePoolSpec_To_v1beta1_AWSManagedMachineP out.AWSLaunchTemplate = nil } // WARNING: in.AWSLifecycleHooks requires manual conversion: does not exist in peer-type + // WARNING: in.NodeRepairConfig requires manual conversion: does not exist in peer-type return nil } @@ -770,7 +759,7 @@ func autoConvert_v1beta1_AWSManagedMachinePoolStatus_To_v1beta2_AWSManagedMachin out.LaunchTemplateVersion = (*string)(unsafe.Pointer(in.LaunchTemplateVersion)) out.FailureReason = (*string)(unsafe.Pointer(in.FailureReason)) out.FailureMessage = (*string)(unsafe.Pointer(in.FailureMessage)) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } @@ -786,7 +775,7 @@ func autoConvert_v1beta2_AWSManagedMachinePoolStatus_To_v1beta1_AWSManagedMachin out.LaunchTemplateVersion = (*string)(unsafe.Pointer(in.LaunchTemplateVersion)) out.FailureReason = (*string)(unsafe.Pointer(in.FailureReason)) out.FailureMessage = (*string)(unsafe.Pointer(in.FailureMessage)) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } @@ -917,7 +906,7 @@ func autoConvert_v1beta1_FargateProfileStatus_To_v1beta2_FargateProfileStatus(in out.Ready = in.Ready out.FailureReason = (*string)(unsafe.Pointer(in.FailureReason)) out.FailureMessage = (*string)(unsafe.Pointer(in.FailureMessage)) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } @@ -930,7 +919,7 @@ func autoConvert_v1beta2_FargateProfileStatus_To_v1beta1_FargateProfileStatus(in out.Ready = in.Ready out.FailureReason = (*string)(unsafe.Pointer(in.FailureReason)) out.FailureMessage = (*string)(unsafe.Pointer(in.FailureMessage)) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/zz_generated.deepcopy.go index da355ddf675e..3919507c2da8 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta1/zz_generated.deepcopy.go @@ -23,7 +23,7 @@ package v1beta1 import ( runtime "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -263,7 +263,7 @@ func (in *AWSMachinePoolStatus) DeepCopyInto(out *AWSMachinePoolStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -490,7 +490,7 @@ func (in *AWSManagedMachinePoolStatus) DeepCopyInto(out *AWSManagedMachinePoolSt } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -632,7 +632,7 @@ func (in *FargateProfileStatus) DeepCopyInto(out *FargateProfileStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsfargateprofile_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsfargateprofile_types.go index 3869fd42fa2d..453fd4b724b4 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsfargateprofile_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsfargateprofile_types.go @@ -23,7 +23,7 @@ import ( infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" iamv1 "sigs.k8s.io/cluster-api-provider-aws/v2/iam/api/v1beta1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) var ( @@ -142,7 +142,7 @@ type FargateProfileStatus struct { // Conditions defines current state of the Fargate profile. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +kubebuilder:object:root=true @@ -163,12 +163,12 @@ type AWSFargateProfile struct { } // GetConditions returns the observations of the operational state of the AWSFargateProfile resource. -func (r *AWSFargateProfile) GetConditions() clusterv1.Conditions { +func (r *AWSFargateProfile) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSFargateProfile to the predescribed clusterv1.Conditions. -func (r *AWSFargateProfile) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSFargateProfile to the predescribed clusterv1beta1.Conditions. +func (r *AWSFargateProfile) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsfargateprofile_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsfargateprofile_webhook.go index ed38ff73ae9e..f0cb893cb846 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsfargateprofile_webhook.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsfargateprofile_webhook.go @@ -30,7 +30,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" "sigs.k8s.io/cluster-api-provider-aws/v2/pkg/eks" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -53,8 +53,10 @@ func (r *AWSFargateProfile) SetupWebhookWithManager(mgr ctrl.Manager) error { type awsFargateProfileWebhook struct{} -var _ webhook.CustomDefaulter = &awsFargateProfileWebhook{} -var _ webhook.CustomValidator = &awsFargateProfileWebhook{} +var ( + _ webhook.CustomDefaulter = &awsFargateProfileWebhook{} + _ webhook.CustomValidator = &awsFargateProfileWebhook{} +) // Default will set default values for the AWSFargateProfile. func (*awsFargateProfileWebhook) Default(_ context.Context, obj runtime.Object) error { @@ -66,7 +68,7 @@ func (*awsFargateProfileWebhook) Default(_ context.Context, obj runtime.Object) if r.Labels == nil { r.Labels = make(map[string]string) } - r.Labels[clusterv1.ClusterNameLabel] = r.Spec.ClusterName + r.Labels[clusterv1beta1.ClusterNameLabel] = r.Spec.ClusterName if r.Spec.ProfileName == "" { name, err := eks.GenerateEKSName(r.Name, r.Namespace, maxProfileNameLength) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmachinepool_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmachinepool_types.go index ef0a219513f4..a5eb28ee20cb 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmachinepool_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmachinepool_types.go @@ -23,7 +23,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // Constants block. @@ -204,7 +204,7 @@ type AWSMachinePoolStatus struct { // Conditions defines current service state of the AWSMachinePool. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // Instances contains the status for each instance in the pool // +optional @@ -306,12 +306,12 @@ func init() { } // GetConditions returns the observations of the operational state of the AWSMachinePool resource. -func (r *AWSMachinePool) GetConditions() clusterv1.Conditions { +func (r *AWSMachinePool) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSMachinePool to the predescribed clusterv1.Conditions. -func (r *AWSMachinePool) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSMachinePool to the predescribed clusterv1beta1.Conditions. +func (r *AWSMachinePool) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmachinepool_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmachinepool_webhook.go index 3b8cf9fdacaa..478ec233749f 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmachinepool_webhook.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmachinepool_webhook.go @@ -231,7 +231,7 @@ func (r *AWSMachinePool) validateCapacityReservation() field.ErrorList { if r.Spec.AWSLaunchTemplate.CapacityReservationID != nil && r.Spec.AWSLaunchTemplate.CapacityReservationPreference != infrav1.CapacityReservationPreferenceOnly && r.Spec.AWSLaunchTemplate.CapacityReservationPreference != "" { - allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "capacityReservationPreference"), "when a reservation ID is specified, capacityReservationPreference may only be `capacity-reservations-only` or empty")) + allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "capacityReservationPreference"), "when capacityReservationId is specified, capacityReservationPreference may only be `CapacityReservationsOnly` or empty")) } return allErrs } @@ -314,12 +314,14 @@ func (*AWSMachinePoolWebhook) Default(ctx context.Context, obj runtime.Object) e r.Spec.DefaultInstanceWarmup.Duration = 300 * time.Second } - if r.ignitionEnabled() && r.Spec.Ignition.Version == "" { - r.Spec.Ignition.Version = infrav1.DefaultIgnitionVersion - } if r.ignitionEnabled() && r.Spec.Ignition.StorageType == "" { r.Spec.Ignition.StorageType = infrav1.DefaultMachinePoolIgnitionStorageType } + // Defaults the version field if StorageType is not set to `UnencryptedUserData`. + // When using `UnencryptedUserData` the version field is ignored because the userdata defines its version itself. + if r.ignitionEnabled() && r.Spec.Ignition.Version == "" && r.Spec.Ignition.StorageType != infrav1.IgnitionStorageTypeOptionUnencryptedUserData { + r.Spec.Ignition.Version = infrav1.DefaultIgnitionVersion + } return nil } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmanagedmachinepool_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmanagedmachinepool_types.go index 0aeb7be0dca8..8e761a506f18 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmanagedmachinepool_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/awsmanagedmachinepool_types.go @@ -23,7 +23,7 @@ import ( infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" iamv1 "sigs.k8s.io/cluster-api-provider-aws/v2/iam/api/v1beta1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // ManagedMachineAMIType specifies which AWS AMI to use for a managed MachinePool. @@ -214,6 +214,10 @@ type AWSManagedMachinePoolSpec struct { // AWSLifecycleHooks specifies lifecycle hooks for the managed node group. // +optional AWSLifecycleHooks []AWSLifecycleHook `json:"lifecycleHooks,omitempty"` + + // NodeRepairConfig specifies the node auto repair configuration for the managed node group. + // +optional + NodeRepairConfig *NodeRepairConfig `json:"nodeRepairConfig,omitempty"` } // ManagedMachinePoolScaling specifies scaling options. @@ -294,7 +298,16 @@ type AWSManagedMachinePoolStatus struct { // Conditions defines current service state of the managed machine pool // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` +} + +// NodeRepairConfig defines the node auto repair configuration for managed node groups. +type NodeRepairConfig struct { + // Enabled specifies whether node auto repair is enabled for the node group. + // When enabled, EKS will automatically repair unhealthy nodes by replacing them. + // +optional + // +kubebuilder:default=false + Enabled *bool `json:"enabled,omitempty"` } // +kubebuilder:object:root=true @@ -314,12 +327,12 @@ type AWSManagedMachinePool struct { } // GetConditions returns the observations of the operational state of the AWSManagedMachinePool resource. -func (r *AWSManagedMachinePool) GetConditions() clusterv1.Conditions { +func (r *AWSManagedMachinePool) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the AWSManagedMachinePool to the predescribed clusterv1.Conditions. -func (r *AWSManagedMachinePool) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the AWSManagedMachinePool to the predescribed clusterv1beta1.Conditions. +func (r *AWSManagedMachinePool) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/conditions_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/conditions_consts.go index 0f3d8675ca80..7e656f93c5e6 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/conditions_consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/conditions_consts.go @@ -16,11 +16,13 @@ limitations under the License. package v1beta2 -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" +import ( + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" +) const ( // ASGReadyCondition reports on current status of the autoscaling group. Ready indicates the group is provisioned. - ASGReadyCondition clusterv1.ConditionType = "ASGReady" + ASGReadyCondition clusterv1beta1.ConditionType = "ASGReady" // ASGNotFoundReason used when the autoscaling group couldn't be retrieved. ASGNotFoundReason = "ASGNotFound" // ASGProvisionFailedReason used for failures during autoscaling group provisioning. @@ -29,7 +31,7 @@ const ( ASGDeletionInProgress = "ASGDeletionInProgress" // LaunchTemplateReadyCondition represents the status of an AWSMachinePool's associated Launch Template. - LaunchTemplateReadyCondition clusterv1.ConditionType = "LaunchTemplateReady" + LaunchTemplateReadyCondition clusterv1beta1.ConditionType = "LaunchTemplateReady" // LaunchTemplateNotFoundReason is used when an associated Launch Template can't be found. LaunchTemplateNotFoundReason = "LaunchTemplateNotFound" // LaunchTemplateCreateFailedReason used for failures during Launch Template creation. @@ -38,9 +40,9 @@ const ( LaunchTemplateReconcileFailedReason = "LaunchTemplateReconcileFailed" // PreLaunchTemplateUpdateCheckCondition reports if all prerequisite are met for launch template update. - PreLaunchTemplateUpdateCheckCondition clusterv1.ConditionType = "PreLaunchTemplateUpdateCheckSuccess" + PreLaunchTemplateUpdateCheckCondition clusterv1beta1.ConditionType = "PreLaunchTemplateUpdateCheckSuccess" // PostLaunchTemplateUpdateOperationCondition reports on successfully completes post launch template update operation. - PostLaunchTemplateUpdateOperationCondition clusterv1.ConditionType = "PostLaunchTemplateUpdateOperationSuccess" + PostLaunchTemplateUpdateOperationCondition clusterv1beta1.ConditionType = "PostLaunchTemplateUpdateOperationSuccess" // PreLaunchTemplateUpdateCheckFailedReason used to report when not all prerequisite are met for launch template update. PreLaunchTemplateUpdateCheckFailedReason = "PreLaunchTemplateUpdateCheckFailed" @@ -48,7 +50,7 @@ const ( PostLaunchTemplateUpdateOperationFailedReason = "PostLaunchTemplateUpdateOperationFailed" // InstanceRefreshStartedCondition reports on successfully starting instance refresh. - InstanceRefreshStartedCondition clusterv1.ConditionType = "InstanceRefreshStarted" + InstanceRefreshStartedCondition clusterv1beta1.ConditionType = "InstanceRefreshStarted" // InstanceRefreshNotReadyReason used to report instance refresh is not initiated. // If there are instance refreshes that are in progress, then a new instance refresh request will fail. InstanceRefreshNotReadyReason = "InstanceRefreshNotReady" @@ -60,7 +62,7 @@ const ( // AWSMachineDeletionFailed reports if deleting AWSMachines failed. AWSMachineDeletionFailed = "AWSMachineDeletionFailed" // LifecycleHookReadyCondition reports on the status of the lifecycle hook. - LifecycleHookReadyCondition clusterv1.ConditionType = "LifecycleHookReady" + LifecycleHookReadyCondition clusterv1beta1.ConditionType = "LifecycleHookReady" // LifecycleHookCreationFailedReason used for failures during lifecycle hook creation. LifecycleHookCreationFailedReason = "LifecycleHookCreationFailed" // LifecycleHookUpdateFailedReason used for failures during lifecycle hook update. @@ -71,7 +73,7 @@ const ( const ( // EKSNodegroupReadyCondition condition reports on the successful reconciliation of eks control plane. - EKSNodegroupReadyCondition clusterv1.ConditionType = "EKSNodegroupReady" + EKSNodegroupReadyCondition clusterv1beta1.ConditionType = "EKSNodegroupReady" // EKSNodegroupReconciliationFailedReason used to report failures while reconciling EKS control plane. EKSNodegroupReconciliationFailedReason = "EKSNodegroupReconciliationFailed" // WaitingForEKSControlPlaneReason used when the machine pool is waiting for @@ -81,10 +83,10 @@ const ( const ( // EKSFargateProfileReadyCondition condition reports on the successful reconciliation of eks control plane. - EKSFargateProfileReadyCondition clusterv1.ConditionType = "EKSFargateProfileReady" + EKSFargateProfileReadyCondition clusterv1beta1.ConditionType = "EKSFargateProfileReady" // EKSFargateCreatingCondition condition reports on whether the fargate // profile is creating. - EKSFargateCreatingCondition clusterv1.ConditionType = "EKSFargateCreating" + EKSFargateCreatingCondition clusterv1beta1.ConditionType = "EKSFargateCreating" // EKSFargateDeletingCondition used to report that the profile is deleting. EKSFargateDeletingCondition = "EKSFargateDeleting" // EKSFargateReconciliationFailedReason used to report failures while reconciling EKS control plane. @@ -104,13 +106,13 @@ const ( const ( // IAMNodegroupRolesReadyCondition condition reports on the successful // reconciliation of EKS nodegroup iam roles. - IAMNodegroupRolesReadyCondition clusterv1.ConditionType = "IAMNodegroupRolesReady" + IAMNodegroupRolesReadyCondition clusterv1beta1.ConditionType = "IAMNodegroupRolesReady" // IAMNodegroupRolesReconciliationFailedReason used to report failures while // reconciling EKS nodegroup iam roles. IAMNodegroupRolesReconciliationFailedReason = "IAMNodegroupRolesReconciliationFailed" // IAMFargateRolesReadyCondition condition reports on the successful // reconciliation of EKS nodegroup iam roles. - IAMFargateRolesReadyCondition clusterv1.ConditionType = "IAMFargateRolesReady" + IAMFargateRolesReadyCondition clusterv1beta1.ConditionType = "IAMFargateRolesReady" // IAMFargateRolesReconciliationFailedReason used to report failures while // reconciling EKS nodegroup iam roles. IAMFargateRolesReconciliationFailedReason = "IAMFargateRolesReconciliationFailed" @@ -118,9 +120,9 @@ const ( const ( // RosaMachinePoolReadyCondition condition reports on the successful reconciliation of rosa machinepool. - RosaMachinePoolReadyCondition clusterv1.ConditionType = "RosaMachinePoolReady" + RosaMachinePoolReadyCondition clusterv1beta1.ConditionType = "RosaMachinePoolReady" // RosaMachinePoolUpgradingCondition condition reports whether ROSAMachinePool is upgrading or not. - RosaMachinePoolUpgradingCondition clusterv1.ConditionType = "RosaMachinePoolUpgrading" + RosaMachinePoolUpgradingCondition clusterv1beta1.ConditionType = "RosaMachinePoolUpgrading" // WaitingForRosaControlPlaneReason used when the machine pool is waiting for // ROSA control plane infrastructure to be ready before proceeding. @@ -129,3 +131,23 @@ const ( // RosaMachinePoolReconciliationFailedReason used to report failures while reconciling ROSAMachinePool. RosaMachinePoolReconciliationFailedReason = "ReconciliationFailed" ) + +const ( + // ROSANetworkReadyCondition condition reports on the successful reconciliation of ROSANetwork. + ROSANetworkReadyCondition clusterv1beta1.ConditionType = "ROSANetworkReady" + + // ROSANetworkCreatingReason used when ROSANetwork is being created. + ROSANetworkCreatingReason = "Creating" + + // ROSANetworkCreatedReason used when ROSANetwork is created. + ROSANetworkCreatedReason = "Created" + + // ROSANetworkFailedReason used when rosaNetwork creation failed. + ROSANetworkFailedReason = "Failed" + + // ROSANetworkDeletingReason used when ROSANetwork is being deleted. + ROSANetworkDeletingReason = "Deleting" + + // ROSANetworkDeletionFailedReason used to report failures while deleting ROSANetwork. + ROSANetworkDeletionFailedReason = "DeletionFailed" +) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/finalizers.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/finalizers.go index 1125449285a5..f0cffa7958f2 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/finalizers.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/finalizers.go @@ -28,4 +28,7 @@ const ( // RosaMachinePoolFinalizer allows the controller to clean up resources on delete. RosaMachinePoolFinalizer = "rosamachinepools.infrastructure.cluster.x-k8s.io" + + // RosaRoleConfigFinalizer allows the controller to clean up resources on delete. + RosaRoleConfigFinalizer = "rosaroleconfigs.infrastructure.cluster.x-k8s.io" ) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosacluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosacluster_types.go index 3303125d1c74..2b24e5f0e2dd 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosacluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosacluster_types.go @@ -19,14 +19,14 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // ROSAClusterSpec defines the desired state of ROSACluster. type ROSAClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` } // ROSAClusterStatus defines the observed state of ROSACluster. @@ -37,11 +37,11 @@ type ROSAClusterStatus struct { // FailureDomains specifies a list fo available availability zones that can be used // +optional - FailureDomains clusterv1.FailureDomains `json:"failureDomains,omitempty"` + FailureDomains clusterv1beta1.FailureDomains `json:"failureDomains,omitempty"` // Conditions defines current service state of the ROSACluster. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +kubebuilder:object:root=true @@ -72,13 +72,13 @@ type ROSAClusterList struct { // GetConditions returns the observations of the operational state of the // ROSACluster resource. -func (r *ROSACluster) GetConditions() clusterv1.Conditions { +func (r *ROSACluster) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } // SetConditions sets the underlying service state of the ROSACluster to the -// predescribed clusterv1.Conditions. -func (r *ROSACluster) SetConditions(conditions clusterv1.Conditions) { +// predescribed clusterv1beta1.Conditions. +func (r *ROSACluster) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosamachinepool_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosamachinepool_types.go index 0dc3af30ed64..9c379586c69f 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosamachinepool_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosamachinepool_types.go @@ -22,7 +22,8 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + rosacontrolplanev1 "sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // RosaMachinePoolSpec defines the desired state of RosaMachinePool. @@ -79,7 +80,7 @@ type RosaMachinePoolSpec struct { // Autoscaling specifies auto scaling behaviour for this MachinePool. // required if Replicas is not configured // +optional - Autoscaling *RosaMachinePoolAutoScaling `json:"autoscaling,omitempty"` + Autoscaling *rosacontrolplanev1.AutoScaling `json:"autoscaling,omitempty"` // TuningConfigs specifies the names of the tuning configs to be applied to this MachinePool. // Tuning configs must already exist. @@ -118,6 +119,12 @@ type RosaMachinePoolSpec struct { // // +optional UpdateConfig *RosaUpdateConfig `json:"updateConfig,omitempty"` + + // CapacityReservationID specifies the ID of an AWS On-Demand Capacity Reservation and Capacity Blocks for ML. + // The CapacityReservationID must be pre-created in advance, before creating a NodePool. + // + // +optional + CapacityReservationID string `json:"capacityReservationID,omitempty"` } // RosaTaint represents a taint to be applied to a node. @@ -139,14 +146,6 @@ type RosaTaint struct { Effect corev1.TaintEffect `json:"effect"` } -// RosaMachinePoolAutoScaling specifies scaling options. -type RosaMachinePoolAutoScaling struct { - // +kubebuilder:validation:Minimum=1 - MinReplicas int `json:"minReplicas,omitempty"` - // +kubebuilder:validation:Minimum=1 - MaxReplicas int `json:"maxReplicas,omitempty"` -} - // RosaUpdateConfig specifies update configuration type RosaUpdateConfig struct { // RollingUpdate specifies MaxUnavailable & MaxSurge number of nodes during update. @@ -207,7 +206,7 @@ type RosaMachinePoolStatus struct { Replicas int32 `json:"replicas"` // Conditions defines current service state of the managed machine pool // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // FailureMessage will be set in the event that there is a terminal problem // reconciling the state and will be set to a descriptive error message. // @@ -253,12 +252,12 @@ type ROSAMachinePoolList struct { } // GetConditions returns the observations of the operational state of the RosaMachinePool resource. -func (r *ROSAMachinePool) GetConditions() clusterv1.Conditions { +func (r *ROSAMachinePool) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the RosaMachinePool to the predescribed clusterv1.Conditions. -func (r *ROSAMachinePool) SetConditions(conditions clusterv1.Conditions) { +// SetConditions sets the underlying service state of the RosaMachinePool to the predescribed clusterv1beta1.Conditions. +func (r *ROSAMachinePool) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosanetwork_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosanetwork_types.go new file mode 100644 index 000000000000..0cb9922530d7 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosanetwork_types.go @@ -0,0 +1,149 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" +) + +// ROSANetworkFinalizer allows the controller to clean up resources on delete. +const ROSANetworkFinalizer = "rosanetwork.infrastructure.cluster.x-k8s.io" + +// ROSANetworkSpec defines the desired state of ROSANetwork +type ROSANetworkSpec struct { + // The name of the cloudformation stack under which the network infrastructure would be created + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="stackName is immutable" + // +kubebuilder:validation:Required + StackName string `json:"stackName"` + + // The AWS region in which the components of ROSA network infrastruture are to be crated + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="region is immutable" + // +kubebuilder:validation:Required + Region string `json:"region"` + + // The number of availability zones to be used for creation of the network infrastructure. + // You can specify anything between one and four, depending on the chosen AWS region. + // Either AvailabilityZoneCount OR AvailabilityZones must be set. + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="availabilityZoneCount is immutable" + // +optional + AvailabilityZoneCount int `json:"availabilityZoneCount,omitempty"` + + // The list of availability zones to be used for creation of the network infrastructure. + // You can specify anything between one and four valid availability zones from a given region. + // Either AvailabilityZones OR AvailabilityZoneCount must be set. + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="availabilityZones is immutable" + // +optional + AvailabilityZones []string `json:"availabilityZones,omitempty"` + + // CIDR block to be used for the VPC + // +kubebuilder:validation:Format=cidr + // +kubebuilder:validation:Required + CIDRBlock string `json:"cidrBlock"` + + // IdentityRef is a reference to an identity to be used when reconciling rosa network. + // If no identity is specified, the default identity for this controller will be used. + // +optional + IdentityRef *infrav1.AWSIdentityReference `json:"identityRef,omitempty"` + + // StackTags is an optional set of tags to add to the created cloudformation stack. + // The stack tags will then be automatically applied to the supported AWS resources (VPC, subnets, ...). + // +optional + StackTags Tags `json:"stackTags,omitempty"` +} + +// ROSANetworkSubnet groups public and private subnet and the availability zone in which the two subnets got created +type ROSANetworkSubnet struct { + // Availability zone of the subnet pair, for example us-west-2a + AvailabilityZone string `json:"availabilityZone"` + + // ID of the public subnet, for example subnet-0f7e49a3ce68ff338 + PublicSubnet string `json:"publicSubnet"` + + // ID of the private subnet, for example subnet-07a20d6c41af2b725 + PrivateSubnet string `json:"privateSubnet"` +} + +// CFResource groups information pertaining to a resource created as a part of a cloudformation stack +type CFResource struct { + // Type of the created resource: AWS::EC2::VPC, AWS::EC2::Subnet, ... + ResourceType string `json:"resource"` + + // LogicalResourceID of the created resource. + LogicalID string `json:"logicalId"` + + // PhysicalResourceID of the created resource. + PhysicalID string `json:"physicalId"` + + // Status of the resource: CREATE_IN_PROGRESS, CREATE_COMPLETE, ... + Status string `json:"status"` + + // Message pertaining to the status of the resource + Reason string `json:"reason"` +} + +// ROSANetworkStatus defines the observed state of ROSANetwork +type ROSANetworkStatus struct { + // Array of created private, public subnets and availability zones, grouped by availability zones + Subnets []ROSANetworkSubnet `json:"subnets,omitempty"` + + // Resources created in the cloudformation stack + Resources []CFResource `json:"resources,omitempty"` + + // Conditions specifies the conditions for ROSANetwork + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=rosanetworks,shortName=rosanet,scope=Namespaced,categories=cluster-api +// +kubebuilder:storageversion +// +kubebuilder:subresource:status + +// ROSANetwork is the schema for the rosanetworks API +type ROSANetwork struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ROSANetworkSpec `json:"spec,omitempty"` + Status ROSANetworkStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// ROSANetworkList contains a list of ROSANetwork +type ROSANetworkList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ROSANetwork `json:"items"` +} + +// GetConditions returns the observations of the operational state of the ROSANetwork resource. +func (r *ROSANetwork) GetConditions() clusterv1beta1.Conditions { + return r.Status.Conditions +} + +// SetConditions sets the underlying service state of the ROSANetwork to the predescribed clusterv1beta1.Conditions. +func (r *ROSANetwork) SetConditions(conditions clusterv1beta1.Conditions) { + r.Status.Conditions = conditions +} + +func init() { + SchemeBuilder.Register(&ROSANetwork{}, &ROSANetworkList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosanetwork_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosanetwork_webhook.go new file mode 100644 index 000000000000..0465d892a2fa --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosanetwork_webhook.go @@ -0,0 +1,73 @@ +package v1beta2 + +import ( + "context" + "fmt" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// SetupWebhookWithManager will setup the webhooks for the ROSANetwork. +func (r *ROSANetwork) SetupWebhookWithManager(mgr ctrl.Manager) error { + w := new(rosaNetworkWebhook) + return ctrl.NewWebhookManagedBy(mgr). + For(r). + WithValidator(w). + WithDefaulter(w). + Complete() +} + +// +kubebuilder:webhook:verbs=create;update,path=/validate-infrastructure-cluster-x-k8s-io-v1beta2-rosanetwork,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=rosanetworks,versions=v1beta2,name=validation.rosanetwork.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 +// +kubebuilder:webhook:verbs=create;update,path=/mutate-infrastructure-cluster-x-k8s-io-v1beta2-rosanetwork,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=rosanetworks,versions=v1beta2,name=default.rosanetwork.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 + +type rosaNetworkWebhook struct{} + +var _ webhook.CustomDefaulter = &rosaNetworkWebhook{} +var _ webhook.CustomValidator = &rosaNetworkWebhook{} + +// ValidateCreate implements admission.Validator. +func (r *rosaNetworkWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) (warnings admission.Warnings, err error) { + rosaNet, ok := obj.(*ROSANetwork) + if !ok { + return nil, fmt.Errorf("expected an ROSANetwork object but got %T", rosaNet) + } + + var allErrs field.ErrorList + if rosaNet.Spec.AvailabilityZoneCount == 0 && len(rosaNet.Spec.AvailabilityZones) == 0 { + err := field.Invalid(field.NewPath("spec.AvailabilityZones"), rosaNet.Spec.AvailabilityZones, "Either AvailabilityZones OR AvailabilityZoneCount must be set.") + allErrs = append(allErrs, err) + } + if rosaNet.Spec.AvailabilityZoneCount != 0 && len(rosaNet.Spec.AvailabilityZones) > 0 { + err := field.Invalid(field.NewPath("spec.AvailabilityZones"), rosaNet.Spec.AvailabilityZones, "Either AvailabilityZones OR AvailabilityZoneCount can be set.") + allErrs = append(allErrs, err) + } + + if len(allErrs) > 0 { + return nil, apierrors.NewInvalid( + rosaNet.GroupVersionKind().GroupKind(), + rosaNet.Name, + allErrs) + } + + return nil, nil +} + +// ValidateUpdate implements admission.Validator. +func (r *rosaNetworkWebhook) ValidateUpdate(ctx context.Context, old runtime.Object, updated runtime.Object) (warnings admission.Warnings, err error) { + return nil, nil +} + +// ValidateDelete implements admission.Validator. +func (r *rosaNetworkWebhook) ValidateDelete(ctx context.Context, obj runtime.Object) (warnings admission.Warnings, err error) { + return nil, nil +} + +// Default implements admission.Defaulter. +func (r *rosaNetworkWebhook) Default(ctx context.Context, obj runtime.Object) error { + return nil +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosaroleconfig_types.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosaroleconfig_types.go new file mode 100644 index 000000000000..41e0c21addb3 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosaroleconfig_types.go @@ -0,0 +1,248 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" + rosacontrolplanev1 "sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" +) + +// OidcProviderType set to Managed or UnManaged +type OidcProviderType string + +const ( + // Managed OIDC Provider type + Managed OidcProviderType = "Managed" + + // Unmanaged OIDC Provider type + Unmanaged OidcProviderType = "Unmanaged" +) + +// Operator Role const +const ( + // IngressOperatorARNSuffix is the suffix for the ingress operator role. + IngressOperatorARNSuffix = "-openshift-ingress-operator-cloud-credentials" + + // ImageRegistryARNSuffix is the suffix for the image registry operator role. + ImageRegistryARNSuffix = "-openshift-image-registry-installer-cloud-credentials" + + // StorageARNSuffix is the suffix for the storage operator role. + StorageARNSuffix = "-openshift-cluster-csi-drivers-ebs-cloud-credentials" + + // NetworkARNSuffix is the suffix for the network operator role. + NetworkARNSuffix = "-openshift-cloud-network-config-controller-cloud-credentials" + + // KubeCloudControllerARNSuffix is the suffix for the kube cloud controller role. + KubeCloudControllerARNSuffix = "-kube-system-kube-controller-manager" + + // NodePoolManagementARNSuffix is the suffix for the node pool management role. + NodePoolManagementARNSuffix = "-kube-system-capa-controller-manager" + + // ControlPlaneOperatorARNSuffix is the suffix for the control plane operator role. + ControlPlaneOperatorARNSuffix = "-kube-system-control-plane-operator" + + // KMSProviderARNSuffix is the suffix for the kms provider role. + KMSProviderARNSuffix = "-kube-system-kms-provider" +) + +// Account Role const +const ( + // HCPROSAInstallerRole is the suffix for installer account role + HCPROSAInstallerRole = "-HCP-ROSA-Installer-Role" + + // HCPROSASupportRole is the suffix for support account role + HCPROSASupportRole = "-HCP-ROSA-Support-Role" + + // HCPROSAWorkerRole is the suffix for worker account role + HCPROSAWorkerRole = "-HCP-ROSA-Worker-Role" +) + +const ( + // RosaRoleConfigReadyCondition condition reports on the successful reconciliation of RosaRoleConfig. + RosaRoleConfigReadyCondition = "RosaRoleConfigReady" + + // RosaRoleConfigDeletionFailedReason used to report failures while deleting RosaRoleConfig. + RosaRoleConfigDeletionFailedReason = "DeletionFailed" + + // RosaRoleConfigReconciliationFailedReason used to report reconciliation failures. + RosaRoleConfigReconciliationFailedReason = "ReconciliationFailed" + + // RosaRoleConfigDeletionStarted used to indicate that the deletion of RosaRoleConfig has started. + RosaRoleConfigDeletionStarted = "DeletionStarted" + + // RosaRoleConfigCreatedReason used to indicate that the RosaRoleConfig has been created. + RosaRoleConfigCreatedReason = "Created" +) + +// ROSARoleConfigSpec defines the desired state of ROSARoleConfig +type ROSARoleConfigSpec struct { + // AccountRoleConfig defines account-wide IAM roles before creating your ROSA cluster. + AccountRoleConfig AccountRoleConfig `json:"accountRoleConfig"` + + // OperatorRoleConfig defines cluster-specific operator IAM roles based on your cluster configuration. + OperatorRoleConfig OperatorRoleConfig `json:"operatorRoleConfig"` + + // IdentityRef is a reference to an identity to be used when reconciling the ROSA Role Config. + // If no identity is specified, the default identity for this controller will be used. + // +optional + IdentityRef *infrav1.AWSIdentityReference `json:"identityRef,omitempty"` + + // CredentialsSecretRef references a secret with necessary credentials to connect to the OCM API. + // +optional + CredentialsSecretRef *corev1.LocalObjectReference `json:"credentialsSecretRef,omitempty"` + + // OIDC provider type values are Managed or UnManaged. When set to Unmanged OperatorRoleConfig OIDCID field must be provided. + // +kubebuilder:validation:Enum=Managed;Unmanaged + // +kubebuilder:default=Managed + OidcProviderType OidcProviderType `json:"oidcProviderType"` +} + +// AccountRoleConfig defines account IAM roles before creating your ROSA cluster. +type AccountRoleConfig struct { + // User-defined prefix for all generated AWS account role + // +kubebuilder:validation:Required + // +kubebuilder:validation:MaxLength:=4 + // +kubebuilder:validation:Pattern:=`^[a-z]([-a-z0-9]*[a-z0-9])?$` + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="prefix is immutable" + Prefix string `json:"prefix"` + + // The ARN of the policy that is used to set the permissions boundary for the account roles. + // +optional + PermissionsBoundaryARN string `json:"permissionsBoundaryARN,omitempty"` + + // The arn path for the account/operator roles as well as their policies. + // +optional + Path string `json:"path,omitempty"` + + // Version of OpenShift that will be used to the roles tag in formate of x.y.z example; "4.19.0" + // Setting the role OpenShift version tag does not affect the associated ROSAControlplane version. + // +kubebuilder:validation:Required + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="version is immutable" + Version string `json:"version"` + + // SharedVPCConfig is used to set up shared VPC. + // +optional + SharedVPCConfig SharedVPCConfig `json:"sharedVPCConfig,omitempty"` +} + +// OperatorRoleConfig defines cluster-specific operator IAM roles based on your cluster configuration. +type OperatorRoleConfig struct { + // User-defined prefix for generated AWS operator roles. + // +kubebuilder:validation:Required + // +kubebuilder:validation:MaxLength:=4 + // +kubebuilder:validation:Pattern:=`^[a-z]([-a-z0-9]*[a-z0-9])?$` + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="prefix is immutable" + Prefix string `json:"prefix"` + + // The ARN of the policy that is used to set the permissions boundary for the operator roles. + // +optional + PermissionsBoundaryARN string `json:"permissionsBoundaryARN,omitempty"` + + // SharedVPCConfig is used to set up shared VPC. + // +optional + SharedVPCConfig SharedVPCConfig `json:"sharedVPCConfig,omitempty"` + + // OIDCID is the ID of the OIDC config that will be used to create the operator roles. + // Cannot be set when OidcProviderType set to Managed + // +optional + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="oidcID is immutable" + OIDCID string `json:"oidcID,omitempty"` +} + +// SharedVPCConfig is used to set up shared VPC. +type SharedVPCConfig struct { + // Role ARN associated with the private hosted zone used for Hosted Control Plane cluster shared VPC, this role contains policies to be used with Route 53 + RouteRoleARN string `json:"routeRoleARN,omitempty"` + + // Role ARN associated with the shared VPC used for Hosted Control Plane clusters, this role contains policies to be used with the VPC endpoint + VPCEndpointRoleARN string `json:"vpcEndpointRoleArn,omitempty"` +} + +// ROSARoleConfigStatus defines the observed state of ROSARoleConfig +type ROSARoleConfigStatus struct { + // ID of created OIDC config + OIDCID string `json:"oidcID,omitempty"` + + // Create OIDC provider for operators to authenticate against in an STS cluster. + OIDCProviderARN string `json:"oidcProviderARN,omitempty"` + + // Created Account roles that can be used to + AccountRolesRef AccountRolesRef `json:"accountRolesRef,omitempty"` + + // AWS IAM roles used to perform credential requests by the openshift operators. + OperatorRolesRef rosacontrolplanev1.AWSRolesRef `json:"operatorRolesRef,omitempty"` + + // Conditions specifies the ROSARoleConfig conditions + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` +} + +// AccountRolesRef defscribes ARNs used as Account roles. +type AccountRolesRef struct { + // InstallerRoleARN is an AWS IAM role that OpenShift Cluster Manager will assume to create the cluster.. + InstallerRoleARN string `json:"installerRoleARN,omitempty"` + + // SupportRoleARN is an AWS IAM role used by Red Hat SREs to enable + // access to the cluster account in order to provide support. + SupportRoleARN string `json:"supportRoleARN,omitempty"` + + // WorkerRoleARN is an AWS IAM role that will be attached to worker instances. + WorkerRoleARN string `json:"workerRoleARN,omitempty"` +} + +// ROSARoleConfig is the Schema for the rosaroleconfigs API +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=rosaroleconfigs,scope=Namespaced,categories=cluster-api,shortName=rosarole +// +kubebuilder:storageversion +// +kubebuilder:subresource:status +type ROSARoleConfig struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ROSARoleConfigSpec `json:"spec,omitempty"` + Status ROSARoleConfigStatus `json:"status,omitempty"` +} + +// ROSARoleConfigList contains a list of ROSARoleConfig +// +kubebuilder:object:root=true +type ROSARoleConfigList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ROSARoleConfig `json:"items"` +} + +// SetConditions sets the conditions of the ROSARoleConfig. +func (r *ROSARoleConfig) SetConditions(conditions clusterv1beta1.Conditions) { + r.Status.Conditions = conditions +} + +// GetConditions returns the observations of the operational state of the RosaNetwork resource. +func (r *ROSARoleConfig) GetConditions() clusterv1beta1.Conditions { + return r.Status.Conditions +} + +// IsSharedVPC checks if the shared VPC config is set. +func (s SharedVPCConfig) IsSharedVPC() bool { + return s.VPCEndpointRoleARN != "" || s.RouteRoleARN != "" +} + +func init() { + SchemeBuilder.Register(&ROSARoleConfig{}, &ROSARoleConfigList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosaroleconfig_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosaroleconfig_webhook.go new file mode 100644 index 000000000000..5e9d36a30b98 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/rosaroleconfig_webhook.go @@ -0,0 +1,79 @@ +package v1beta2 + +import ( + "context" + "fmt" + + "github.com/blang/semver" + apierrors "k8s.io/apimachinery/pkg/api/errors" + runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// SetupWebhookWithManager will setup the webhooks for the ROSARoleConfig. +func (r *ROSARoleConfig) SetupWebhookWithManager(mgr ctrl.Manager) error { + w := new(rosaRoleConfigWebhook) + return ctrl.NewWebhookManagedBy(mgr). + For(r). + WithValidator(w). + WithDefaulter(w). + Complete() +} + +// +kubebuilder:webhook:verbs=create;update,path=/validate-infrastructure-cluster-x-k8s-io-v1beta2-rosaroleconfig,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=rosaroleconfigs,versions=v1beta2,name=validation.rosaroleconfig.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 +// +kubebuilder:webhook:verbs=create;update,path=/mutate-infrastructure-cluster-x-k8s-io-v1beta2-rosaroleconfig,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=rosaroleconfigs,versions=v1beta2,name=default.rosaroleconfig.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 + +type rosaRoleConfigWebhook struct{} + +var _ webhook.CustomDefaulter = &rosaRoleConfigWebhook{} +var _ webhook.CustomValidator = &rosaRoleConfigWebhook{} + +// ValidateCreate implements admission.Validator. +func (r *rosaRoleConfigWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) (warnings admission.Warnings, err error) { + roleConfig, ok := obj.(*ROSARoleConfig) + if !ok { + return nil, fmt.Errorf("expected an ROSARoleConfig object but got %T", roleConfig) + } + + var allErrs field.ErrorList + if roleConfig.Spec.OidcProviderType == Managed && roleConfig.Spec.OperatorRoleConfig.OIDCID != "" { + err := field.Invalid(field.NewPath("spec.operatorRoleConfig.oidcId"), roleConfig.Spec.OperatorRoleConfig.OIDCID, "cannot be set with Managed oidc provider type") + allErrs = append(allErrs, err) + } else if roleConfig.Spec.OidcProviderType == Unmanaged && roleConfig.Spec.OperatorRoleConfig.OIDCID == "" { + err := field.Invalid(field.NewPath("spec.operatorRoleConfig.oidcId"), roleConfig.Spec.OperatorRoleConfig.OIDCID, "must set operatorRoleConfig.oidcId with UnManaged oidc provider type") + allErrs = append(allErrs, err) + } + + _, vErr := semver.Parse(roleConfig.Spec.AccountRoleConfig.Version) + if vErr != nil { + err := field.Invalid(field.NewPath("spec.accountRoleConfig.version"), roleConfig.Spec.AccountRoleConfig.Version, "must be a valid semantic version") + allErrs = append(allErrs, err) + } + + if len(allErrs) > 0 { + return nil, apierrors.NewInvalid( + roleConfig.GroupVersionKind().GroupKind(), + roleConfig.Name, + allErrs) + } + + return nil, nil +} + +// ValidateUpdate implements admission.Validator. +func (r *rosaRoleConfigWebhook) ValidateUpdate(ctx context.Context, old runtime.Object, updated runtime.Object) (warnings admission.Warnings, err error) { + return nil, nil +} + +// ValidateDelete implements admission.Validator. +func (r *rosaRoleConfigWebhook) ValidateDelete(ctx context.Context, obj runtime.Object) (warnings admission.Warnings, err error) { + return nil, nil +} + +// Default implements admission.Defaulter. +func (r *rosaRoleConfigWebhook) Default(ctx context.Context, obj runtime.Object) error { + return nil +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/zz_generated.deepcopy.go index 6885eb4c6479..592ec7d7fa8f 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2/zz_generated.deepcopy.go @@ -21,11 +21,13 @@ limitations under the License. package v1beta2 import ( + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" apiv1beta2 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" - "sigs.k8s.io/cluster-api/api/v1beta1" + rosaapiv1beta2 "sigs.k8s.io/cluster-api-provider-aws/v2/controlplane/rosa/api/v1beta2" + "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -567,6 +569,11 @@ func (in *AWSManagedMachinePoolSpec) DeepCopyInto(out *AWSManagedMachinePoolSpec (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.NodeRepairConfig != nil { + in, out := &in.NodeRepairConfig, &out.NodeRepairConfig + *out = new(NodeRepairConfig) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSManagedMachinePoolSpec. @@ -621,6 +628,37 @@ func (in *AWSManagedMachinePoolStatus) DeepCopy() *AWSManagedMachinePoolStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AccountRoleConfig) DeepCopyInto(out *AccountRoleConfig) { + *out = *in + out.SharedVPCConfig = in.SharedVPCConfig +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccountRoleConfig. +func (in *AccountRoleConfig) DeepCopy() *AccountRoleConfig { + if in == nil { + return nil + } + out := new(AccountRoleConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AccountRolesRef) DeepCopyInto(out *AccountRolesRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccountRolesRef. +func (in *AccountRolesRef) DeepCopy() *AccountRolesRef { + if in == nil { + return nil + } + out := new(AccountRolesRef) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AutoScalingGroup) DeepCopyInto(out *AutoScalingGroup) { *out = *in @@ -688,6 +726,21 @@ func (in *BlockDeviceMapping) DeepCopy() *BlockDeviceMapping { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CFResource) DeepCopyInto(out *CFResource) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CFResource. +func (in *CFResource) DeepCopy() *CFResource { + if in == nil { + return nil + } + out := new(CFResource) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EBS) DeepCopyInto(out *EBS) { *out = *in @@ -891,6 +944,42 @@ func (in *MixedInstancesPolicy) DeepCopy() *MixedInstancesPolicy { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeRepairConfig) DeepCopyInto(out *NodeRepairConfig) { + *out = *in + if in.Enabled != nil { + in, out := &in.Enabled, &out.Enabled + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeRepairConfig. +func (in *NodeRepairConfig) DeepCopy() *NodeRepairConfig { + if in == nil { + return nil + } + out := new(NodeRepairConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *OperatorRoleConfig) DeepCopyInto(out *OperatorRoleConfig) { + *out = *in + out.SharedVPCConfig = in.SharedVPCConfig +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OperatorRoleConfig. +func (in *OperatorRoleConfig) DeepCopy() *OperatorRoleConfig { + if in == nil { + return nil + } + out := new(OperatorRoleConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Overrides) DeepCopyInto(out *Overrides) { *out = *in @@ -1129,6 +1218,254 @@ func (in *ROSAMachinePoolList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSANetwork) DeepCopyInto(out *ROSANetwork) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSANetwork. +func (in *ROSANetwork) DeepCopy() *ROSANetwork { + if in == nil { + return nil + } + out := new(ROSANetwork) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ROSANetwork) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSANetworkList) DeepCopyInto(out *ROSANetworkList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ROSANetwork, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSANetworkList. +func (in *ROSANetworkList) DeepCopy() *ROSANetworkList { + if in == nil { + return nil + } + out := new(ROSANetworkList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ROSANetworkList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSANetworkSpec) DeepCopyInto(out *ROSANetworkSpec) { + *out = *in + if in.AvailabilityZones != nil { + in, out := &in.AvailabilityZones, &out.AvailabilityZones + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.IdentityRef != nil { + in, out := &in.IdentityRef, &out.IdentityRef + *out = new(apiv1beta2.AWSIdentityReference) + **out = **in + } + if in.StackTags != nil { + in, out := &in.StackTags, &out.StackTags + *out = make(Tags, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSANetworkSpec. +func (in *ROSANetworkSpec) DeepCopy() *ROSANetworkSpec { + if in == nil { + return nil + } + out := new(ROSANetworkSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSANetworkStatus) DeepCopyInto(out *ROSANetworkStatus) { + *out = *in + if in.Subnets != nil { + in, out := &in.Subnets, &out.Subnets + *out = make([]ROSANetworkSubnet, len(*in)) + copy(*out, *in) + } + if in.Resources != nil { + in, out := &in.Resources, &out.Resources + *out = make([]CFResource, len(*in)) + copy(*out, *in) + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(v1beta1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSANetworkStatus. +func (in *ROSANetworkStatus) DeepCopy() *ROSANetworkStatus { + if in == nil { + return nil + } + out := new(ROSANetworkStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSANetworkSubnet) DeepCopyInto(out *ROSANetworkSubnet) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSANetworkSubnet. +func (in *ROSANetworkSubnet) DeepCopy() *ROSANetworkSubnet { + if in == nil { + return nil + } + out := new(ROSANetworkSubnet) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSARoleConfig) DeepCopyInto(out *ROSARoleConfig) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSARoleConfig. +func (in *ROSARoleConfig) DeepCopy() *ROSARoleConfig { + if in == nil { + return nil + } + out := new(ROSARoleConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ROSARoleConfig) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSARoleConfigList) DeepCopyInto(out *ROSARoleConfigList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ROSARoleConfig, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSARoleConfigList. +func (in *ROSARoleConfigList) DeepCopy() *ROSARoleConfigList { + if in == nil { + return nil + } + out := new(ROSARoleConfigList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ROSARoleConfigList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSARoleConfigSpec) DeepCopyInto(out *ROSARoleConfigSpec) { + *out = *in + out.AccountRoleConfig = in.AccountRoleConfig + out.OperatorRoleConfig = in.OperatorRoleConfig + if in.IdentityRef != nil { + in, out := &in.IdentityRef, &out.IdentityRef + *out = new(apiv1beta2.AWSIdentityReference) + **out = **in + } + if in.CredentialsSecretRef != nil { + in, out := &in.CredentialsSecretRef, &out.CredentialsSecretRef + *out = new(corev1.LocalObjectReference) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSARoleConfigSpec. +func (in *ROSARoleConfigSpec) DeepCopy() *ROSARoleConfigSpec { + if in == nil { + return nil + } + out := new(ROSARoleConfigSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ROSARoleConfigStatus) DeepCopyInto(out *ROSARoleConfigStatus) { + *out = *in + out.AccountRolesRef = in.AccountRolesRef + out.OperatorRolesRef = in.OperatorRolesRef + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(v1beta1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ROSARoleConfigStatus. +func (in *ROSARoleConfigStatus) DeepCopy() *ROSARoleConfigStatus { + if in == nil { + return nil + } + out := new(ROSARoleConfigStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RefreshPreferences) DeepCopyInto(out *RefreshPreferences) { *out = *in @@ -1189,21 +1526,6 @@ func (in *RollingUpdate) DeepCopy() *RollingUpdate { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *RosaMachinePoolAutoScaling) DeepCopyInto(out *RosaMachinePoolAutoScaling) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RosaMachinePoolAutoScaling. -func (in *RosaMachinePoolAutoScaling) DeepCopy() *RosaMachinePoolAutoScaling { - if in == nil { - return nil - } - out := new(RosaMachinePoolAutoScaling) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RosaMachinePoolSpec) DeepCopyInto(out *RosaMachinePoolSpec) { *out = *in @@ -1228,7 +1550,7 @@ func (in *RosaMachinePoolSpec) DeepCopyInto(out *RosaMachinePoolSpec) { } if in.Autoscaling != nil { in, out := &in.Autoscaling, &out.Autoscaling - *out = new(RosaMachinePoolAutoScaling) + *out = new(rosaapiv1beta2.AutoScaling) **out = **in } if in.TuningConfigs != nil { @@ -1335,6 +1657,21 @@ func (in *RosaUpdateConfig) DeepCopy() *RosaUpdateConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SharedVPCConfig) DeepCopyInto(out *SharedVPCConfig) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SharedVPCConfig. +func (in *SharedVPCConfig) DeepCopy() *SharedVPCConfig { + if in == nil { + return nil + } + out := new(SharedVPCConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SuspendProcessesTypes) DeepCopyInto(out *SuspendProcessesTypes) { *out = *in diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureasomanagedcluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureasomanagedcluster_types.go index 3063586ab57c..b42d22da923b 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureasomanagedcluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureasomanagedcluster_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -38,7 +38,7 @@ type AzureASOManagedClusterSpec struct { // Because this field is programmatically set by CAPZ after resource creation, we define it as +optional // in the API schema to permit resource admission. //+optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` } // AzureASOManagedClusterStatus defines the observed state of AzureASOManagedCluster. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureasomanagedcontrolplane_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureasomanagedcontrolplane_types.go index c32c98f83c0e..4a0cb985b208 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureasomanagedcontrolplane_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureasomanagedcontrolplane_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AzureASOManagedControlPlaneKind is the kind for AzureASOManagedControlPlane. @@ -51,7 +51,7 @@ type AzureASOManagedControlPlaneStatus struct { // ControlPlaneEndpoint represents the endpoint for the cluster's API server. //+optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` } // +kubebuilder:object:root=true diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azurecluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azurecluster_types.go index 8f4397b9ae88..08195026981a 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azurecluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azurecluster_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -53,7 +53,7 @@ type AzureClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. It is not recommended to set // this when creating an AzureCluster as CAPZ will set this for you. However, if it is set, CAPZ will not change it. // +optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint,omitempty"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint,omitempty"` } // AzureClusterStatus defines the observed state of AzureCluster. @@ -65,7 +65,7 @@ type AzureClusterStatus struct { // See: https://learn.microsoft.com/azure/reliability/availability-zones-overview // This list will be used by Cluster API to try and spread the machines across the failure domains. // +optional - FailureDomains clusterv1.FailureDomains `json:"failureDomains,omitempty"` + FailureDomains clusterv1beta1.FailureDomains `json:"failureDomains,omitempty"` // Ready is true when the provider resource is ready. // +optional @@ -73,7 +73,7 @@ type AzureClusterStatus struct { // Conditions defines current service state of the AzureCluster. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // LongRunningOperationStates saves the states for Azure long-running operations so they can be continued on the // next reconciliation loop. @@ -114,12 +114,12 @@ type AzureClusterList struct { } // GetConditions returns the list of conditions for an AzureCluster API object. -func (c *AzureCluster) GetConditions() clusterv1.Conditions { +func (c *AzureCluster) GetConditions() clusterv1beta1.Conditions { return c.Status.Conditions } // SetConditions will set the given conditions on an AzureCluster object. -func (c *AzureCluster) SetConditions(conditions clusterv1.Conditions) { +func (c *AzureCluster) SetConditions(conditions clusterv1beta1.Conditions) { c.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureclusteridentity_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureclusteridentity_types.go index 62ab41f0bd78..83559f407e24 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureclusteridentity_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azureclusteridentity_types.go @@ -19,7 +19,7 @@ package v1beta1 import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AllowedNamespaces defines the namespaces the clusters are allowed to use the identity from @@ -89,7 +89,7 @@ type AzureClusterIdentitySpec struct { type AzureClusterIdentityStatus struct { // Conditions defines current service state of the AzureClusterIdentity. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +kubebuilder:object:root=true @@ -118,12 +118,12 @@ type AzureClusterIdentityList struct { } // GetConditions returns the list of conditions for an AzureClusterIdentity API object. -func (c *AzureClusterIdentity) GetConditions() clusterv1.Conditions { +func (c *AzureClusterIdentity) GetConditions() clusterv1beta1.Conditions { return c.Status.Conditions } // SetConditions will set the given conditions on an AzureClusterIdentity object. -func (c *AzureClusterIdentity) SetConditions(conditions clusterv1.Conditions) { +func (c *AzureClusterIdentity) SetConditions(conditions clusterv1beta1.Conditions) { c.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachine_default.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachine_default.go index 80f5afcc399a..7e216e82e6e7 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachine_default.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachine_default.go @@ -27,7 +27,7 @@ import ( "golang.org/x/crypto/ssh" kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/uuid" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" utilSSH "sigs.k8s.io/cluster-api-provider-azure/util/ssh" @@ -189,7 +189,7 @@ func GetOwnerAzureClusterNameAndNamespace(cli client.Client, clusterName string, break } - return ownerCluster.Spec.InfrastructureRef.Name, ownerCluster.Spec.InfrastructureRef.Namespace, nil + return ownerCluster.Spec.InfrastructureRef.Name, ownerCluster.Namespace, nil } // GetSubscriptionID returns the subscription ID for the AzureCluster given the cluster name and namespace. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachine_types.go index 090f24edace2..402888f180ff 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachine_types.go @@ -20,7 +20,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -246,7 +246,7 @@ type AzureMachineStatus struct { // Conditions defines current service state of the AzureMachine. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // LongRunningOperationStates saves the states for Azure long-running operations so they can be continued on the // next reconciliation loop. @@ -297,12 +297,12 @@ type AzureMachineList struct { } // GetConditions returns the list of conditions for an AzureMachine API object. -func (m *AzureMachine) GetConditions() clusterv1.Conditions { +func (m *AzureMachine) GetConditions() clusterv1beta1.Conditions { return m.Status.Conditions } // SetConditions will set the given conditions on an AzureMachine object. -func (m *AzureMachine) SetConditions(conditions clusterv1.Conditions) { +func (m *AzureMachine) SetConditions(conditions clusterv1beta1.Conditions) { m.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachinetemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachinetemplate_types.go index c4403f19dac4..e9332c91cda8 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachinetemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachinetemplate_types.go @@ -17,10 +17,64 @@ limitations under the License. package v1beta1 import ( + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) +// Architecture represents the CPU architecture of the node. +// Its underlying type is a string and its value can be any of amd64, arm64. +type Architecture string + +// Architecture constants. +const ( + // ArchitectureAmd64 represents the amd64 CPU architecture. + ArchitectureAmd64 Architecture = "amd64" + // ArchitectureArm64 represents the arm64 CPU architecture. + ArchitectureArm64 Architecture = "arm64" +) + +// OperatingSystem represents the operating system of the node. +// Its underlying type is a string and its value can be any of linux, windows. +type OperatingSystem string + +// Operating system constants. +const ( + // OperatingSystemLinux represents the Linux operating system. + OperatingSystemLinux OperatingSystem = "linux" + // OperatingSystemWindows represents the Windows operating system. + OperatingSystemWindows OperatingSystem = "windows" +) + +// NodeInfo contains information about the node's architecture and operating system. +type NodeInfo struct { + // Architecture is the CPU architecture of the node. + // Its underlying type is a string and its value can be any of amd64, arm64. + // +kubebuilder:validation:Enum=amd64;arm64 + // +optional + Architecture Architecture `json:"architecture,omitempty"` + // OperatingSystem is the operating system of the node. + // Its underlying type is a string and its value can be any of linux, windows. + // +kubebuilder:validation:Enum=linux;windows + // +optional + OperatingSystem OperatingSystem `json:"operatingSystem,omitempty"` +} + +// AzureMachineTemplateStatus defines the observed state of AzureMachineTemplate. +type AzureMachineTemplateStatus struct { + // Capacity defines the resource capacity for this machine. + // This value is used for autoscaling from zero operations as defined in: + // https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20210310-opt-in-autoscaling-from-zero.md + // +optional + Capacity corev1.ResourceList `json:"capacity,omitempty"` + + // NodeInfo contains information about the node's architecture and operating system. + // This value is used for autoscaling from zero operations as defined in: + // https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20210310-opt-in-autoscaling-from-zero.md + // +optional + NodeInfo *NodeInfo `json:"nodeInfo,omitempty"` +} + // AzureMachineTemplateSpec defines the desired state of AzureMachineTemplate. type AzureMachineTemplateSpec struct { Template AzureMachineTemplateResource `json:"template"` @@ -29,13 +83,15 @@ type AzureMachineTemplateSpec struct { // +kubebuilder:object:root=true // +kubebuilder:resource:path=azuremachinetemplates,scope=Namespaced,categories=cluster-api // +kubebuilder:storageversion +// +kubebuilder:subresource:status // AzureMachineTemplate is the Schema for the azuremachinetemplates API. type AzureMachineTemplate struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` - Spec AzureMachineTemplateSpec `json:"spec,omitempty"` + Spec AzureMachineTemplateSpec `json:"spec,omitempty"` + Status AzureMachineTemplateStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true @@ -54,7 +110,7 @@ func init() { // AzureMachineTemplateResource describes the data needed to create an AzureMachine from a template. type AzureMachineTemplateResource struct { // +optional - ObjectMeta clusterv1.ObjectMeta `json:"metadata,omitempty"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` // Spec is the specification of the desired behavior of the machine. Spec AzureMachineSpec `json:"spec"` } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachinetemplate_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachinetemplate_webhook.go index 36a82211cf20..e135e209db39 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachinetemplate_webhook.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremachinetemplate_webhook.go @@ -111,7 +111,7 @@ func (r *azureMachineTemplateWebhook) ValidateUpdate(ctx context.Context, oldRaw return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a admission.Request inside context: %v", err)) } - if !topology.ShouldSkipImmutabilityChecks(req, t) && + if !topology.IsDryRunRequest(req, t) && !reflect.DeepEqual(t.Spec.Template.Spec, old.Spec.Template.Spec) { // The equality failure could be because of default mismatch between v1alpha3 and v1beta1. This happens because // the new object `r` will have run through the default webhooks but the old object `old` would not have so. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcluster_types.go index 5a4056338767..f3da4714fea2 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcluster_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AzureManagedClusterSpec defines the desired state of AzureManagedCluster. @@ -28,7 +28,7 @@ type AzureManagedClusterSpec struct { // Because this field is programmatically set by CAPZ after resource creation, we define it as +optional // in the API schema to permit resource admission. // +optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` } // AzureManagedClusterStatus defines the observed state of AzureManagedCluster. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_default.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_default.go index 66b628fed938..65275a89be1e 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_default.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_default.go @@ -23,7 +23,7 @@ import ( "golang.org/x/crypto/ssh" "k8s.io/utils/ptr" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" utilSSH "sigs.k8s.io/cluster-api-provider-azure/util/ssh" diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_types.go index 8938e26508c5..0f4055684fe6 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -156,7 +156,7 @@ type AzureManagedControlPlaneSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // Immutable, populated by the AKS API at create. // +optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint,omitempty"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint,omitempty"` // SSHPublicKey is a string literal containing an ssh public key base64 encoded. // Use empty string to autogenerate new key. Use null value to not set key. @@ -424,7 +424,7 @@ type AzureManagedControlPlaneStatus struct { // Conditions defines current service state of the AzureManagedControlPlane. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // LongRunningOperationStates saves the states for Azure long-running operations so they can be continued on the // next reconciliation loop. @@ -689,12 +689,12 @@ type AzureManagedControlPlaneList struct { } // GetConditions returns the list of conditions for an AzureManagedControlPlane API object. -func (m *AzureManagedControlPlane) GetConditions() clusterv1.Conditions { +func (m *AzureManagedControlPlane) GetConditions() clusterv1beta1.Conditions { return m.Status.Conditions } // SetConditions will set the given conditions on an AzureManagedControlPlane object. -func (m *AzureManagedControlPlane) SetConditions(conditions clusterv1.Conditions) { +func (m *AzureManagedControlPlane) SetConditions(conditions clusterv1beta1.Conditions) { m.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_webhook.go index 3eff0314865c..40a1a0f52437 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_webhook.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedcontrolplane_webhook.go @@ -30,7 +30,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/utils/ptr" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" @@ -116,8 +116,8 @@ func (mw *azureManagedControlPlaneWebhook) ValidateUpdate(_ context.Context, old immutableFields := []struct { path *field.Path - old interface{} - new interface{} + old any + new any }{ {field.NewPath("spec", "subscriptionID"), old.Spec.SubscriptionID, m.Spec.SubscriptionID}, {field.NewPath("spec", "resourceGroupName"), old.Spec.ResourceGroupName, m.Spec.ResourceGroupName}, @@ -539,24 +539,19 @@ func validateManagedClusterNetwork(cli client.Client, labels map[string]string, return allErrs } - if clusterNetwork := ownerCluster.Spec.ClusterNetwork; clusterNetwork != nil { - if clusterNetwork.Services != nil { - // A user may provide zero or one CIDR blocks. If they provide an empty array, - // we ignore it and use the default. AKS doesn't support > 1 Service/Pod CIDR. - if len(clusterNetwork.Services.CIDRBlocks) > 1 { - allErrs = append(allErrs, field.TooMany(field.NewPath("Cluster", "spec", "clusterNetwork", "services", "cidrBlocks"), len(clusterNetwork.Services.CIDRBlocks), 1)) - } - if len(clusterNetwork.Services.CIDRBlocks) == 1 { - serviceCIDR = clusterNetwork.Services.CIDRBlocks[0] - } - } - if clusterNetwork.Pods != nil { - // A user may provide zero or one CIDR blocks. If they provide an empty array, - // we ignore it and use the default. AKS doesn't support > 1 Service/Pod CIDR. - if len(clusterNetwork.Pods.CIDRBlocks) > 1 { - allErrs = append(allErrs, field.TooMany(field.NewPath("Cluster", "spec", "clusterNetwork", "pods", "cidrBlocks"), len(clusterNetwork.Pods.CIDRBlocks), 1)) - } - } + clusterNetwork := ownerCluster.Spec.ClusterNetwork + // A user may provide zero or one CIDR blocks. If they provide an empty array, + // we ignore it and use the default. AKS doesn't support > 1 Service/Pod CIDR. + if len(clusterNetwork.Services.CIDRBlocks) > 1 { + allErrs = append(allErrs, field.TooMany(field.NewPath("Cluster", "spec", "clusterNetwork", "services", "cidrBlocks"), len(clusterNetwork.Services.CIDRBlocks), 1)) + } + if len(clusterNetwork.Services.CIDRBlocks) == 1 { + serviceCIDR = clusterNetwork.Services.CIDRBlocks[0] + } + // A user may provide zero or one CIDR blocks. If they provide an empty array, + // we ignore it and use the default. AKS doesn't support > 1 Service/Pod CIDR. + if len(clusterNetwork.Pods.CIDRBlocks) > 1 { + allErrs = append(allErrs, field.TooMany(field.NewPath("Cluster", "spec", "clusterNetwork", "pods", "cidrBlocks"), len(clusterNetwork.Pods.CIDRBlocks), 1)) } if dnsServiceIP != nil { diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedmachinepool_types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedmachinepool_types.go index 166dbb77953c..de21f87f5d54 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedmachinepool_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedmachinepool_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -473,7 +473,7 @@ type AzureManagedMachinePoolStatus struct { // Conditions defines current service state of the AzureManagedControlPlane. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // LongRunningOperationStates saves the states for Azure long-running operations so they can be continued on the // next reconciliation loop. @@ -513,12 +513,12 @@ type AzureManagedMachinePoolList struct { } // GetConditions returns the list of conditions for an AzureManagedMachinePool API object. -func (m *AzureManagedMachinePool) GetConditions() clusterv1.Conditions { +func (m *AzureManagedMachinePool) GetConditions() clusterv1beta1.Conditions { return m.Status.Conditions } // SetConditions will set the given conditions on an AzureManagedMachinePool object. -func (m *AzureManagedMachinePool) SetConditions(conditions clusterv1.Conditions) { +func (m *AzureManagedMachinePool) SetConditions(conditions clusterv1beta1.Conditions) { m.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedmachinepool_webhook.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedmachinepool_webhook.go index 4437c15307e9..84560b083712 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedmachinepool_webhook.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/azuremanagedmachinepool_webhook.go @@ -30,7 +30,7 @@ import ( kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/utils/ptr" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" clusterctlv1alpha3 "sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/consts.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/consts.go index ab8012c8e311..c6fa7ca8654b 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/consts.go @@ -16,12 +16,12 @@ limitations under the License. package v1beta1 -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" +import clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" // AzureCluster Conditions and Reasons. const ( // NetworkInfrastructureReadyCondition reports of current status of cluster infrastructure. - NetworkInfrastructureReadyCondition clusterv1.ConditionType = "NetworkInfrastructureReady" + NetworkInfrastructureReadyCondition clusterv1beta1.ConditionType = "NetworkInfrastructureReady" // NamespaceNotAllowedByIdentity used to indicate cluster in a namespace not allowed by identity. NamespaceNotAllowedByIdentity = "NamespaceNotAllowedByIdentity" ) @@ -29,9 +29,9 @@ const ( // AzureMachine Conditions and Reasons. const ( // VMRunningCondition reports on current status of the Azure VM. - VMRunningCondition clusterv1.ConditionType = "VMRunning" + VMRunningCondition clusterv1beta1.ConditionType = "VMRunning" // VMIdentitiesReadyCondition reports on the readiness of the Azure VM identities. - VMIdentitiesReadyCondition clusterv1.ConditionType = "VMIdentitiesReady" + VMIdentitiesReadyCondition clusterv1beta1.ConditionType = "VMIdentitiesReady" // VMCreatingReason used when the vm creation is in progress. VMCreatingReason = "VMCreating" // VMUpdatingReason used when the vm updating is in progress. @@ -47,7 +47,7 @@ const ( // WaitingForBootstrapDataReason used when machine is waiting for bootstrap data to be ready before proceeding. WaitingForBootstrapDataReason = "WaitingForBootstrapData" // BootstrapSucceededCondition reports the result of the execution of the bootstrap data on the machine. - BootstrapSucceededCondition clusterv1.ConditionType = "BootstrapSucceeded" + BootstrapSucceededCondition clusterv1beta1.ConditionType = "BootstrapSucceeded" // BootstrapInProgressReason is used to indicate the bootstrap data has not finished executing. BootstrapInProgressReason = "BootstrapInProgress" // BootstrapFailedReason is used to indicate the bootstrap process ran into an error. @@ -57,7 +57,7 @@ const ( // AzureMachinePool Conditions and Reasons. const ( // ScaleSetRunningCondition reports on current status of the Azure Scale Set. - ScaleSetRunningCondition clusterv1.ConditionType = "ScaleSetRunning" + ScaleSetRunningCondition clusterv1beta1.ConditionType = "ScaleSetRunning" // ScaleSetCreatingReason used when the scale set creation is in progress. ScaleSetCreatingReason = "ScaleSetCreating" // ScaleSetUpdatingReason used when the scale set updating is in progress. @@ -68,14 +68,14 @@ const ( ScaleSetProvisionFailedReason = "ScaleSetProvisionFailed" // ScaleSetDesiredReplicasCondition reports on the scaling state of the machine pool. - ScaleSetDesiredReplicasCondition clusterv1.ConditionType = "ScaleSetDesiredReplicas" + ScaleSetDesiredReplicasCondition clusterv1beta1.ConditionType = "ScaleSetDesiredReplicas" // ScaleSetScaleUpReason describes the machine pool scaling up. ScaleSetScaleUpReason = "ScaleSetScalingUp" // ScaleSetScaleDownReason describes the machine pool scaling down. ScaleSetScaleDownReason = "ScaleSetScalingDown" // ScaleSetModelUpdatedCondition reports on the model state of the pool. - ScaleSetModelUpdatedCondition clusterv1.ConditionType = "ScaleSetModelUpdated" + ScaleSetModelUpdatedCondition clusterv1beta1.ConditionType = "ScaleSetModelUpdated" // ScaleSetModelOutOfDateReason describes the machine pool model being out of date. ScaleSetModelOutOfDateReason = "ScaleSetModelOutOfDate" ) @@ -83,57 +83,57 @@ const ( // AzureManagedCluster Conditions and Reasons. const ( // ManagedClusterRunningCondition means the AKS cluster exists and is in a running state. - ManagedClusterRunningCondition clusterv1.ConditionType = "ManagedClusterRunning" + ManagedClusterRunningCondition clusterv1beta1.ConditionType = "ManagedClusterRunning" // AgentPoolsReadyCondition means the AKS agent pools exist and are ready to be used. - AgentPoolsReadyCondition clusterv1.ConditionType = "AgentPoolsReady" + AgentPoolsReadyCondition clusterv1beta1.ConditionType = "AgentPoolsReady" // AzureResourceAvailableCondition means the AKS cluster is healthy according to Azure's Resource Health API. - AzureResourceAvailableCondition clusterv1.ConditionType = "AzureResourceAvailable" + AzureResourceAvailableCondition clusterv1beta1.ConditionType = "AzureResourceAvailable" ) // Azure Services Conditions and Reasons. const ( // ResourceGroupReadyCondition means the resource group exists and is ready to be used. - ResourceGroupReadyCondition clusterv1.ConditionType = "ResourceGroupReady" + ResourceGroupReadyCondition clusterv1beta1.ConditionType = "ResourceGroupReady" // VNetReadyCondition means the virtual network exists and is ready to be used. - VNetReadyCondition clusterv1.ConditionType = "VNetReady" + VNetReadyCondition clusterv1beta1.ConditionType = "VNetReady" // VnetPeeringReadyCondition means the virtual network peerings exist and are ready to be used. - VnetPeeringReadyCondition clusterv1.ConditionType = "VnetPeeringReady" + VnetPeeringReadyCondition clusterv1beta1.ConditionType = "VnetPeeringReady" // SecurityGroupsReadyCondition means the security groups exist and are ready to be used. - SecurityGroupsReadyCondition clusterv1.ConditionType = "SecurityGroupsReady" + SecurityGroupsReadyCondition clusterv1beta1.ConditionType = "SecurityGroupsReady" // RouteTablesReadyCondition means the route tables exist and are ready to be used. - RouteTablesReadyCondition clusterv1.ConditionType = "RouteTablesReady" + RouteTablesReadyCondition clusterv1beta1.ConditionType = "RouteTablesReady" // PublicIPsReadyCondition means the public IPs exist and are ready to be used. - PublicIPsReadyCondition clusterv1.ConditionType = "PublicIPsReady" + PublicIPsReadyCondition clusterv1beta1.ConditionType = "PublicIPsReady" // NATGatewaysReadyCondition means the NAT gateways exist and are ready to be used. - NATGatewaysReadyCondition clusterv1.ConditionType = "NATGatewaysReady" + NATGatewaysReadyCondition clusterv1beta1.ConditionType = "NATGatewaysReady" // SubnetsReadyCondition means the subnets exist and are ready to be used. - SubnetsReadyCondition clusterv1.ConditionType = "SubnetsReady" + SubnetsReadyCondition clusterv1beta1.ConditionType = "SubnetsReady" // LoadBalancersReadyCondition means the load balancers exist and are ready to be used. - LoadBalancersReadyCondition clusterv1.ConditionType = "LoadBalancersReady" + LoadBalancersReadyCondition clusterv1beta1.ConditionType = "LoadBalancersReady" // PrivateDNSZoneReadyCondition means the private DNS zone exists and is ready to be used. - PrivateDNSZoneReadyCondition clusterv1.ConditionType = "PrivateDNSZoneReady" + PrivateDNSZoneReadyCondition clusterv1beta1.ConditionType = "PrivateDNSZoneReady" // PrivateDNSLinkReadyCondition means the private DNS links exist and are ready to be used. - PrivateDNSLinkReadyCondition clusterv1.ConditionType = "PrivateDNSLinkReady" + PrivateDNSLinkReadyCondition clusterv1beta1.ConditionType = "PrivateDNSLinkReady" // PrivateDNSRecordReadyCondition means the private DNS records exist and are ready to be used. - PrivateDNSRecordReadyCondition clusterv1.ConditionType = "PrivateDNSRecordReady" + PrivateDNSRecordReadyCondition clusterv1beta1.ConditionType = "PrivateDNSRecordReady" // BastionHostReadyCondition means the bastion host exists and is ready to be used. - BastionHostReadyCondition clusterv1.ConditionType = "BastionHostReady" + BastionHostReadyCondition clusterv1beta1.ConditionType = "BastionHostReady" // InboundNATRulesReadyCondition means the inbound NAT rules exist and are ready to be used. - InboundNATRulesReadyCondition clusterv1.ConditionType = "InboundNATRulesReady" + InboundNATRulesReadyCondition clusterv1beta1.ConditionType = "InboundNATRulesReady" // AvailabilitySetReadyCondition means the availability set exists and is ready to be used. - AvailabilitySetReadyCondition clusterv1.ConditionType = "AvailabilitySetReady" + AvailabilitySetReadyCondition clusterv1beta1.ConditionType = "AvailabilitySetReady" // RoleAssignmentReadyCondition means the role assignment exists and is ready to be used. - RoleAssignmentReadyCondition clusterv1.ConditionType = "RoleAssignmentReady" + RoleAssignmentReadyCondition clusterv1beta1.ConditionType = "RoleAssignmentReady" // DisksReadyCondition means the disks exist and are ready to be used. - DisksReadyCondition clusterv1.ConditionType = "DisksReady" + DisksReadyCondition clusterv1beta1.ConditionType = "DisksReady" // NetworkInterfaceReadyCondition means the network interfaces exist and are ready to be used. - NetworkInterfaceReadyCondition clusterv1.ConditionType = "NetworkInterfacesReady" + NetworkInterfaceReadyCondition clusterv1beta1.ConditionType = "NetworkInterfacesReady" // PrivateEndpointsReadyCondition means the private endpoints exist and are ready to be used. - PrivateEndpointsReadyCondition clusterv1.ConditionType = "PrivateEndpointsReady" + PrivateEndpointsReadyCondition clusterv1beta1.ConditionType = "PrivateEndpointsReady" // FleetReadyCondition means the Fleet exists and is ready to be used. - FleetReadyCondition clusterv1.ConditionType = "FleetReady" + FleetReadyCondition clusterv1beta1.ConditionType = "FleetReady" // AKSExtensionsReadyCondition means the AKS Extensions exist and are ready to be used. - AKSExtensionsReadyCondition clusterv1.ConditionType = "AKSExtensionsReady" + AKSExtensionsReadyCondition clusterv1beta1.ConditionType = "AKSExtensionsReady" // CreatingReason means the resource is being created. CreatingReason = "Creating" diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/tags.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/tags.go index ccda71281fa7..2b7a41aa9e96 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/tags.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/tags.go @@ -18,6 +18,7 @@ package v1beta1 import ( "fmt" + "maps" "reflect" ) @@ -69,9 +70,7 @@ func (t Tags) Difference(other Tags) Tags { // Merge merges in tags from other. If a tag already exists, it is replaced by the tag in other. func (t Tags) Merge(other Tags) { - for k, v := range other { - t[k] = v - } + maps.Copy(t, other) } // AddSpecVersionHashTag adds a spec version hash to the Azure resource tags to determine quickly if state has changed. @@ -192,9 +191,7 @@ type BuildParams struct { // Build builds tags including the cluster tag and returns them in map form. func Build(params BuildParams) Tags { tags := make(Tags) - for k, v := range params.Additional { - tags[k] = v - } + maps.Copy(tags, params.Additional) tags[ClusterTagKey(params.ClusterName)] = string(params.Lifecycle) if params.Role != nil { diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types.go index ba3a74680b16..9a861d38e2a3 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types.go @@ -17,6 +17,8 @@ limitations under the License. package v1beta1 import ( + "slices" + "github.com/pkg/errors" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/utils/net" @@ -259,6 +261,10 @@ type NatGateway struct { // +optional NatGatewayIP PublicIPSpec `json:"ip,omitempty"` + // Zones mentions the list of zones the NAT gateway should be a part of. + // +optional + Zones []string `json:"zones,omitempty"` + NatGatewayClassSpec `json:",inline"` } @@ -905,12 +911,7 @@ func (s SubnetSpec) IsNatGatewayEnabled() bool { // IsIPv6Enabled returns whether or not IPv6 is enabled on the subnet. func (s SubnetSpec) IsIPv6Enabled() bool { - for _, cidr := range s.CIDRBlocks { - if net.IsIPv6CIDRString(cidr) { - return true - } - } - return false + return slices.ContainsFunc(s.CIDRBlocks, net.IsIPv6CIDRString) } // GetSecurityRuleByDestination returns security group rule, which matches provided destination ports. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types_class.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types_class.go index 452eab517f8f..358cb1e60824 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types_class.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types_class.go @@ -19,7 +19,7 @@ package v1beta1 import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // AzureClusterClassSpec defines the AzureCluster properties that may be shared across several Azure clusters. @@ -76,7 +76,7 @@ type AzureClusterClassSpec struct { // which is a separated group of datacenters within a region. // See: https://learn.microsoft.com/azure/reliability/availability-zones-overview // +optional - FailureDomains clusterv1.FailureDomains `json:"failureDomains,omitempty"` + FailureDomains clusterv1beta1.FailureDomains `json:"failureDomains,omitempty"` } // AzureManagedControlPlaneClassSpec defines the AzureManagedControlPlane properties that may be shared across several azure managed control planes. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types_template.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types_template.go index e0ed7ae0683d..f654ed20be93 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types_template.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/types_template.go @@ -17,6 +17,8 @@ limitations under the License. package v1beta1 import ( + "slices" + "github.com/pkg/errors" "k8s.io/utils/net" ) @@ -133,12 +135,7 @@ func (s SubnetTemplateSpec) IsNatGatewayEnabled() bool { // IsIPv6Enabled returns whether or not IPv6 is enabled on the subnet. func (s SubnetTemplateSpec) IsIPv6Enabled() bool { - for _, cidr := range s.CIDRBlocks { - if net.IsIPv6CIDRString(cidr) { - return true - } - } - return false + return slices.ContainsFunc(s.CIDRBlocks, net.IsIPv6CIDRString) } // SubnetTemplatesSpec specifies a list of subnet templates. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/zz_generated.deepcopy.go index 036180f4bed9..e806a35a1124 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/api/v1beta1/zz_generated.deepcopy.go @@ -24,7 +24,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -1062,7 +1062,7 @@ func (in *AzureClusterClassSpec) DeepCopyInto(out *AzureClusterClassSpec) { } if in.FailureDomains != nil { in, out := &in.FailureDomains, &out.FailureDomains - *out = make(apiv1beta1.FailureDomains, len(*in)) + *out = make(corev1beta1.FailureDomains, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -1164,7 +1164,7 @@ func (in *AzureClusterIdentityStatus) DeepCopyInto(out *AzureClusterIdentityStat *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -1237,14 +1237,14 @@ func (in *AzureClusterStatus) DeepCopyInto(out *AzureClusterStatus) { *out = *in if in.FailureDomains != nil { in, out := &in.FailureDomains, &out.FailureDomains - *out = make(apiv1beta1.FailureDomains, len(*in)) + *out = make(corev1beta1.FailureDomains, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -1642,7 +1642,7 @@ func (in *AzureMachineStatus) DeepCopyInto(out *AzureMachineStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -1670,6 +1670,7 @@ func (in *AzureMachineTemplate) DeepCopyInto(out *AzureMachineTemplate) { out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AzureMachineTemplate. @@ -1755,6 +1756,33 @@ func (in *AzureMachineTemplateSpec) DeepCopy() *AzureMachineTemplateSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AzureMachineTemplateStatus) DeepCopyInto(out *AzureMachineTemplateStatus) { + *out = *in + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(corev1.ResourceList, len(*in)) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } + if in.NodeInfo != nil { + in, out := &in.NodeInfo, &out.NodeInfo + *out = new(NodeInfo) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AzureMachineTemplateStatus. +func (in *AzureMachineTemplateStatus) DeepCopy() *AzureMachineTemplateStatus { + if in == nil { + return nil + } + out := new(AzureMachineTemplateStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AzureManagedCluster) DeepCopyInto(out *AzureManagedCluster) { *out = *in @@ -2198,7 +2226,7 @@ func (in *AzureManagedControlPlaneStatus) DeepCopyInto(out *AzureManagedControlP *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -2575,7 +2603,7 @@ func (in *AzureManagedMachinePoolStatus) DeepCopyInto(out *AzureManagedMachinePo } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -3690,6 +3718,11 @@ func (in *ManagedMachinePoolScaling) DeepCopy() *ManagedMachinePoolScaling { func (in *NatGateway) DeepCopyInto(out *NatGateway) { *out = *in in.NatGatewayIP.DeepCopyInto(&out.NatGatewayIP) + if in.Zones != nil { + in, out := &in.Zones, &out.Zones + *out = make([]string, len(*in)) + copy(*out, *in) + } out.NatGatewayClassSpec = in.NatGatewayClassSpec } @@ -3842,6 +3875,21 @@ func (in *NetworkTemplateSpec) DeepCopy() *NetworkTemplateSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeInfo) DeepCopyInto(out *NodeInfo) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeInfo. +func (in *NodeInfo) DeepCopy() *NodeInfo { + if in == nil { + return nil + } + out := new(NodeInfo) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OIDCIssuerProfile) DeepCopyInto(out *OIDCIssuerProfile) { *out = *in diff --git a/vendor/sigs.k8s.io/cluster-api-provider-azure/util/azure/azure.go b/vendor/sigs.k8s.io/cluster-api-provider-azure/util/azure/azure.go index 403565a621b7..17984b0a0380 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-azure/util/azure/azure.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-azure/util/azure/azure.go @@ -23,7 +23,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" "github.com/pkg/errors" - expv1 "sigs.k8s.io/cluster-api/exp/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -42,9 +42,9 @@ func IsAzureSystemNodeLabelKey(labelKey string) bool { } // FindParentMachinePool finds the parent MachinePool for the AzureMachinePool. -func FindParentMachinePool(ampName string, cli client.Client) (*expv1.MachinePool, error) { +func FindParentMachinePool(ampName string, cli client.Client) (*clusterv1.MachinePool, error) { ctx := context.Background() - machinePoolList := &expv1.MachinePoolList{} + machinePoolList := &clusterv1.MachinePoolList{} if err := cli.List(ctx, machinePoolList); err != nil { return nil, errors.Wrapf(err, "failed to list MachinePools for %s", ampName) } @@ -57,7 +57,7 @@ func FindParentMachinePool(ampName string, cli client.Client) (*expv1.MachinePoo } // FindParentMachinePoolWithRetry finds the parent MachinePool for the AzureMachinePool with retry. -func FindParentMachinePoolWithRetry(ampName string, cli client.Client, maxAttempts int) (*expv1.MachinePool, error) { +func FindParentMachinePoolWithRetry(ampName string, cli client.Client, maxAttempts int) (*clusterv1.MachinePool, error) { for i := 1; ; i++ { p, err := FindParentMachinePool(ampName, cli) if err != nil { @@ -71,6 +71,38 @@ func FindParentMachinePoolWithRetry(ampName string, cli client.Client, maxAttemp } } +// FindParentMachinePoolV1Beta1 finds the parent MachinePool for the AzureMachinePool. +// TODO: delete after reconciliation is using v1beta2. +func FindParentMachinePoolV1Beta1(ampName string, cli client.Client) (*clusterv1.MachinePool, error) { + ctx := context.Background() + machinePoolList := &clusterv1.MachinePoolList{} + if err := cli.List(ctx, machinePoolList); err != nil { + return nil, errors.Wrapf(err, "failed to list MachinePools for %s", ampName) + } + for _, mp := range machinePoolList.Items { + if mp.Spec.Template.Spec.InfrastructureRef.Name == ampName { + return &mp, nil + } + } + return nil, errors.Errorf("failed to get MachinePool for %s", ampName) +} + +// FindParentMachinePoolWithRetryV1Beta1 finds the parent MachinePool for the AzureMachinePool with retry. +// TODO: delete after reconciliation is using v1beta2. +func FindParentMachinePoolWithRetryV1Beta1(ampName string, cli client.Client, maxAttempts int) (*clusterv1.MachinePool, error) { + for i := 1; ; i++ { + p, err := FindParentMachinePoolV1Beta1(ampName, cli) + if err != nil { + if i >= maxAttempts { + return nil, errors.Wrap(err, "failed to find parent MachinePool") + } + time.Sleep(1 * time.Second) + continue + } + return p, nil + } +} + // ParseResourceID parses a string to an *arm.ResourceID, first removing any "azure://" prefix. func ParseResourceID(id string) (*arm.ResourceID, error) { return arm.ParseResourceID(strings.TrimPrefix(id, ProviderIDPrefix)) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpcluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpcluster_types.go index 4095ae541cd3..ca3d2f7c351d 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpcluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpcluster_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) const ( @@ -37,7 +37,7 @@ type GCPClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` // NetworkSpec encapsulates all things related to GCP network. // +optional @@ -62,6 +62,8 @@ type GCPClusterSpec struct { // CredentialsRef is a reference to a Secret that contains the credentials to use for provisioning this cluster. If not // supplied then the credentials of the controller will be used. + // When creating a new GCP client, the controller will try to extract the type + // of credential from the JSON data, and it will request a client for the specific credential type. // +optional CredentialsRef *ObjectReference `json:"credentialsRef,omitempty"` @@ -77,8 +79,8 @@ type GCPClusterSpec struct { // GCPClusterStatus defines the observed state of GCPCluster. type GCPClusterStatus struct { - FailureDomains clusterv1.FailureDomains `json:"failureDomains,omitempty"` - Network Network `json:"network,omitempty"` + FailureDomains clusterv1beta1.FailureDomains `json:"failureDomains,omitempty"` + Network Network `json:"network,omitempty"` // Bastion Instance `json:"bastion,omitempty"` Ready bool `json:"ready"` diff --git a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpclustertemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpclustertemplate_types.go index 977bbcd77cc5..4f8a3dc2bac3 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpclustertemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpclustertemplate_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // GCPClusterTemplateSpec defines the desired state of GCPClusterTemplate. @@ -31,7 +31,7 @@ type GCPClusterTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta clusterv1.ObjectMeta `json:"metadata,omitempty"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` Spec GCPClusterSpec `json:"spec"` } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpmachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpmachine_types.go index acff1ab33a9a..b0659ab767ba 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpmachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/gcpmachine_types.go @@ -236,6 +236,23 @@ const ( ProvisioningModelSpot ProvisioningModel = "Spot" ) +// AliasIPRange is an alias IP range attached to an instance's network interface. +type AliasIPRange struct { + // IPCidrRange is the IP alias ranges to allocate for this interface. This IP + // CIDR range must belong to the specified subnetwork and cannot contain IP + // addresses reserved by system or used by other network interfaces. This range + // may be a single IP address (such as 10.2.3.4), a netmask (such as /24) or a + // CIDR-formatted string (such as 10.1.2.0/24). + // +kubebuilder:validation:Pattern=`^((([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/([0-9]|[12][0-9]|3[0-2])|(([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(/([0-9]|[12][0-9]|3[0-2])))$` + // +required + IPCidrRange string `json:"ipCidrRange"` + // SubnetworkRangeName is the name of a subnetwork secondary IP range from which + // to allocate an IP alias range. If not specified, the primary range of the + // subnetwork is used. + // +optional + SubnetworkRangeName string `json:"subnetworkRangeName,omitempty"` +} + // GCPMachineSpec defines the desired state of GCPMachine. type GCPMachineSpec struct { // InstanceType is the type of instance to create. Example: n1.standard-2 @@ -246,6 +263,10 @@ type GCPMachineSpec struct { // +optional Subnet *string `json:"subnet,omitempty"` + // AliasIPRanges let you assign ranges of internal IP addresses as aliases to a VM's network interfaces. + // +optional + AliasIPRanges []AliasIPRange `json:"aliasIPRanges,omitempty"` + // ProviderID is the unique identifier as specified by the cloud provider. // +optional ProviderID *string `json:"providerID,omitempty"` @@ -360,6 +381,25 @@ type GCPMachineSpec struct { // RootDiskEncryptionKey defines the KMS key to be used to encrypt the root disk. // +optional RootDiskEncryptionKey *CustomerEncryptionKey `json:"rootDiskEncryptionKey,omitempty"` + + // GuestAccelerators is a list of the type and count of accelerator cards + // attached to the instance. + // +optional + GuestAccelerators []Accelerator `json:"guestAccelerators,omitempty"` +} + +// Accelerator is a specification of the type and number of accelerator +// cards attached to the instance. +type Accelerator struct { + // Count is the number of the guest accelerator cards exposed to this + // instance. + Count int64 `json:"count,omitempty"` + // Type is the full or partial URL of the accelerator type resource to + // attach to this instance. For example: + // projects/my-project/zones/us-central1-c/acceleratorTypes/nvidia-tesla-p100 + // If you are creating an instance template, specify only the accelerator name. + // See GPUs on Compute Engine for a full list of accelerator types. + Type string `json:"type,omitempty"` } // MetadataItem defines a single piece of metadata associated with an instance. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/types.go b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/types.go index a346e3f9841e..4d94c8f2ca89 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/types.go @@ -19,7 +19,7 @@ package v1beta1 import ( "fmt" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // GCPMachineTemplateResource describes the data needed to create am GCPMachine from a template. @@ -27,7 +27,7 @@ type GCPMachineTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta clusterv1.ObjectMeta `json:"metadata,omitempty"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` // Spec is the specification of the desired behavior of the machine. Spec GCPMachineSpec `json:"spec"` @@ -107,6 +107,36 @@ type Network struct { APIInternalForwardingRule *string `json:"apiInternalForwardingRule,omitempty"` } +// FirewallSpec contains configuration for the firewall. +type FirewallSpec struct { + // DefaultRulesManagement determines the management policy for the default firewall rules + // created by the controller. DefaultRulesManagement has no effect on user specified firewall + // rules. DefaultRulesManagement has no effect when a HostProject is specified. + // "Managed": The controller will create and manage firewall rules. + // "Unmanaged": The controller will not create or modify any firewall rules. If + // the RulesManagement is changed from Managed to Unmanaged after the firewall rules + // have been created, then the firewall rules will not be deleted. + // + // Defaults to "Managed". + // +optional + // +kubebuilder:default:="Managed" + DefaultRulesManagement RulesManagementPolicy `json:"defaultRulesManagement,omitempty"` +} + +// RulesManagementPolicy is a string enum type for managing firewall rules. +// +kubebuilder:validation:Enum=Managed;Unmanaged +type RulesManagementPolicy string + +const ( + // RulesManagementManaged indicates that the controller should create and manage + // firewall rules. This is the default behavior. + RulesManagementManaged RulesManagementPolicy = "Managed" + + // RulesManagementUnmanaged indicates that the controller should not create or manage + // any firewall rules. If rules already exist, they will be left as-is. + RulesManagementUnmanaged RulesManagementPolicy = "Unmanaged" +) + // NetworkSpec encapsulates all things related to a GCP network. type NetworkSpec struct { // Name is the name of the network to be used. @@ -137,6 +167,10 @@ type NetworkSpec struct { // +optional HostProject *string `json:"hostProject,omitempty"` + // Firewall configuration. + // +optional + Firewall FirewallSpec `json:"firewall,omitempty,omitzero"` + // Mtu: Maximum Transmission Unit in bytes. The minimum value for this field is // 1300 and the maximum value is 8896. The suggested value is 1500, which is // the default MTU used on the Internet, or 8896 if you want to use Jumbo @@ -147,6 +181,16 @@ type NetworkSpec struct { // +kubebuilder:default:=1460 // +optional Mtu int64 `json:"mtu,omitempty"` + + // MinPortsPerVM: Minimum number of ports allocated to a VM from this NAT + // config. If not set, a default number of ports is allocated to a VM. This is + // rounded up to the nearest power of 2. For example, if the value of this + // field is 50, at least 64 ports are allocated to a VM. + // +kubebuilder:validation:Minimum:=2 + // +kubebuilder:validation:Maximum:=65536 + // +kubebuilder:default:=64 + // +optional + MinPortsPerVM int64 `json:"minPortsPerVm,omitempty"` } // LoadBalancerType defines the Load Balancer that should be created. @@ -395,4 +439,10 @@ type LoadBalancer struct { // +kubebuilder:default=Regional // +optional InternalAccess InternalAccess `json:"internalAccess,omitempty"` + + // IPAddress is the static IP address to use for the Load Balancer. + // If not set, a new static IP address will be allocated. + // If set, it must be a valid free IP address from the LoadBalancer Subnet. + // +optional + IPAddress *string `json:"ipAddress,omitempty"` } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/zz_generated.deepcopy.go index cf0ce0bf5138..9f1502661a7d 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1/zz_generated.deepcopy.go @@ -23,9 +23,39 @@ package v1beta1 import ( "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Accelerator) DeepCopyInto(out *Accelerator) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Accelerator. +func (in *Accelerator) DeepCopy() *Accelerator { + if in == nil { + return nil + } + out := new(Accelerator) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AliasIPRange) DeepCopyInto(out *AliasIPRange) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AliasIPRange. +func (in *AliasIPRange) DeepCopy() *AliasIPRange { + if in == nil { + return nil + } + out := new(AliasIPRange) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AttachedDiskSpec) DeepCopyInto(out *AttachedDiskSpec) { *out = *in @@ -133,6 +163,21 @@ func (in *Filter) DeepCopy() *Filter { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *FirewallSpec) DeepCopyInto(out *FirewallSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FirewallSpec. +func (in *FirewallSpec) DeepCopy() *FirewallSpec { + if in == nil { + return nil + } + out := new(FirewallSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GCPCluster) DeepCopyInto(out *GCPCluster) { *out = *in @@ -242,7 +287,7 @@ func (in *GCPClusterStatus) DeepCopyInto(out *GCPClusterStatus) { *out = *in if in.FailureDomains != nil { in, out := &in.FailureDomains, &out.FailureDomains - *out = make(apiv1beta1.FailureDomains, len(*in)) + *out = make(corev1beta1.FailureDomains, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -418,6 +463,11 @@ func (in *GCPMachineSpec) DeepCopyInto(out *GCPMachineSpec) { *out = new(string) **out = **in } + if in.AliasIPRanges != nil { + in, out := &in.AliasIPRanges, &out.AliasIPRanges + *out = make([]AliasIPRange, len(*in)) + copy(*out, *in) + } if in.ProviderID != nil { in, out := &in.ProviderID, &out.ProviderID *out = new(string) @@ -509,6 +559,11 @@ func (in *GCPMachineSpec) DeepCopyInto(out *GCPMachineSpec) { *out = new(CustomerEncryptionKey) (*in).DeepCopyInto(*out) } + if in.GuestAccelerators != nil { + in, out := &in.GuestAccelerators, &out.GuestAccelerators + *out = make([]Accelerator, len(*in)) + copy(*out, *in) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GCPMachineSpec. @@ -696,6 +751,11 @@ func (in *LoadBalancer) DeepCopyInto(out *LoadBalancer) { *out = new(string) **out = **in } + if in.IPAddress != nil { + in, out := &in.IPAddress, &out.IPAddress + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancer. @@ -887,6 +947,7 @@ func (in *NetworkSpec) DeepCopyInto(out *NetworkSpec) { *out = new(string) **out = **in } + out.Firewall = in.Firewall } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkSpec. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/conditions_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/conditions_consts.go index cdc8fc59593e..041b6c059635 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/conditions_consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/conditions_consts.go @@ -17,7 +17,7 @@ limitations under the License. package v1beta1 import ( - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) const ( @@ -42,7 +42,7 @@ const ( const ( // InstanceReadyCondition reports on current status of the instance. Ready indicates the instance is in a Running state. - InstanceReadyCondition capiv1beta1.ConditionType = "InstanceReady" + InstanceReadyCondition clusterv1beta1.ConditionType = "InstanceReady" ) const ( @@ -60,10 +60,10 @@ const ( const ( // ImageReadyCondition reports on current status of the image. Ready indicates the image is in a active state. - ImageReadyCondition capiv1beta1.ConditionType = "ImageReady" + ImageReadyCondition clusterv1beta1.ConditionType = "ImageReady" // ImageImportedCondition reports on current status of the image import job. Ready indicates the import job is finished. - ImageImportedCondition capiv1beta1.ConditionType = "ImageImported" + ImageImportedCondition clusterv1beta1.ConditionType = "ImageImported" ) const ( @@ -73,5 +73,5 @@ const ( const ( // LoadBalancerReadyCondition reports on current status of the load balancer. Ready indicates the load balancer is in a active state. - LoadBalancerReadyCondition capiv1beta1.ConditionType = "LoadBalancerReady" + LoadBalancerReadyCondition clusterv1beta1.ConditionType = "LoadBalancerReady" ) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervs_conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervs_conversion.go index 019ad5796842..5cc85a66fe6e 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervs_conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervs_conversion.go @@ -26,130 +26,130 @@ import ( "sigs.k8s.io/controller-runtime/pkg/conversion" - infrav1beta2 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" + infrav1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" ) func (src *IBMPowerVSCluster) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSCluster) + dst := dstRaw.(*infrav1.IBMPowerVSCluster) return Convert_v1beta1_IBMPowerVSCluster_To_v1beta2_IBMPowerVSCluster(src, dst, nil) } func (dst *IBMPowerVSCluster) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSCluster) + src := srcRaw.(*infrav1.IBMPowerVSCluster) return Convert_v1beta2_IBMPowerVSCluster_To_v1beta1_IBMPowerVSCluster(src, dst, nil) } func (src *IBMPowerVSClusterList) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSClusterList) + dst := dstRaw.(*infrav1.IBMPowerVSClusterList) return Convert_v1beta1_IBMPowerVSClusterList_To_v1beta2_IBMPowerVSClusterList(src, dst, nil) } func (dst *IBMPowerVSClusterList) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSClusterList) + src := srcRaw.(*infrav1.IBMPowerVSClusterList) return Convert_v1beta2_IBMPowerVSClusterList_To_v1beta1_IBMPowerVSClusterList(src, dst, nil) } func (src *IBMPowerVSClusterTemplate) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSClusterTemplate) + dst := dstRaw.(*infrav1.IBMPowerVSClusterTemplate) return Convert_v1beta1_IBMPowerVSClusterTemplate_To_v1beta2_IBMPowerVSClusterTemplate(src, dst, nil) } func (dst *IBMPowerVSClusterTemplate) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSClusterTemplate) + src := srcRaw.(*infrav1.IBMPowerVSClusterTemplate) return Convert_v1beta2_IBMPowerVSClusterTemplate_To_v1beta1_IBMPowerVSClusterTemplate(src, dst, nil) } func (src *IBMPowerVSClusterTemplateList) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSClusterTemplateList) + dst := dstRaw.(*infrav1.IBMPowerVSClusterTemplateList) return Convert_v1beta1_IBMPowerVSClusterTemplateList_To_v1beta2_IBMPowerVSClusterTemplateList(src, dst, nil) } func (dst *IBMPowerVSClusterTemplateList) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSClusterTemplateList) + src := srcRaw.(*infrav1.IBMPowerVSClusterTemplateList) return Convert_v1beta2_IBMPowerVSClusterTemplateList_To_v1beta1_IBMPowerVSClusterTemplateList(src, dst, nil) } func (src *IBMPowerVSMachine) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSMachine) + dst := dstRaw.(*infrav1.IBMPowerVSMachine) return Convert_v1beta1_IBMPowerVSMachine_To_v1beta2_IBMPowerVSMachine(src, dst, nil) } func (dst *IBMPowerVSMachine) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSMachine) + src := srcRaw.(*infrav1.IBMPowerVSMachine) return Convert_v1beta2_IBMPowerVSMachine_To_v1beta1_IBMPowerVSMachine(src, dst, nil) } func (src *IBMPowerVSMachineList) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSMachineList) + dst := dstRaw.(*infrav1.IBMPowerVSMachineList) return Convert_v1beta1_IBMPowerVSMachineList_To_v1beta2_IBMPowerVSMachineList(src, dst, nil) } func (dst *IBMPowerVSMachineList) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSMachineList) + src := srcRaw.(*infrav1.IBMPowerVSMachineList) return Convert_v1beta2_IBMPowerVSMachineList_To_v1beta1_IBMPowerVSMachineList(src, dst, nil) } func (src *IBMPowerVSMachineTemplate) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSMachineTemplate) + dst := dstRaw.(*infrav1.IBMPowerVSMachineTemplate) return Convert_v1beta1_IBMPowerVSMachineTemplate_To_v1beta2_IBMPowerVSMachineTemplate(src, dst, nil) } func (dst *IBMPowerVSMachineTemplate) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSMachineTemplate) + src := srcRaw.(*infrav1.IBMPowerVSMachineTemplate) return Convert_v1beta2_IBMPowerVSMachineTemplate_To_v1beta1_IBMPowerVSMachineTemplate(src, dst, nil) } func (src *IBMPowerVSMachineTemplateList) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSMachineTemplateList) + dst := dstRaw.(*infrav1.IBMPowerVSMachineTemplateList) return Convert_v1beta1_IBMPowerVSMachineTemplateList_To_v1beta2_IBMPowerVSMachineTemplateList(src, dst, nil) } func (dst *IBMPowerVSMachineTemplateList) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSMachineTemplateList) + src := srcRaw.(*infrav1.IBMPowerVSMachineTemplateList) return Convert_v1beta2_IBMPowerVSMachineTemplateList_To_v1beta1_IBMPowerVSMachineTemplateList(src, dst, nil) } func (src *IBMPowerVSImage) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSImage) + dst := dstRaw.(*infrav1.IBMPowerVSImage) return Convert_v1beta1_IBMPowerVSImage_To_v1beta2_IBMPowerVSImage(src, dst, nil) } func (dst *IBMPowerVSImage) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSImage) + src := srcRaw.(*infrav1.IBMPowerVSImage) return Convert_v1beta2_IBMPowerVSImage_To_v1beta1_IBMPowerVSImage(src, dst, nil) } func (src *IBMPowerVSImageList) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMPowerVSImageList) + dst := dstRaw.(*infrav1.IBMPowerVSImageList) return Convert_v1beta1_IBMPowerVSImageList_To_v1beta2_IBMPowerVSImageList(src, dst, nil) } func (dst *IBMPowerVSImageList) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMPowerVSImageList) + src := srcRaw.(*infrav1.IBMPowerVSImageList) return Convert_v1beta2_IBMPowerVSImageList_To_v1beta1_IBMPowerVSImageList(src, dst, nil) } -func Convert_v1beta1_IBMPowerVSMachineSpec_To_v1beta2_IBMPowerVSMachineSpec(in *IBMPowerVSMachineSpec, out *infrav1beta2.IBMPowerVSMachineSpec, s apiconversion.Scope) error { +func Convert_v1beta1_IBMPowerVSMachineSpec_To_v1beta2_IBMPowerVSMachineSpec(in *IBMPowerVSMachineSpec, out *infrav1.IBMPowerVSMachineSpec, s apiconversion.Scope) error { out.SystemType = in.SysType out.Processors = intstr.FromString(in.Processors) @@ -160,18 +160,18 @@ func Convert_v1beta1_IBMPowerVSMachineSpec_To_v1beta2_IBMPowerVSMachineSpec(in * out.MemoryGiB = int32(memory) switch in.ProcType { - case strings.ToLower(string(infrav1beta2.PowerVSProcessorTypeDedicated)): - out.ProcessorType = infrav1beta2.PowerVSProcessorTypeDedicated - case strings.ToLower(string(infrav1beta2.PowerVSProcessorTypeShared)): - out.ProcessorType = infrav1beta2.PowerVSProcessorTypeShared - case strings.ToLower(string(infrav1beta2.PowerVSProcessorTypeCapped)): - out.ProcessorType = infrav1beta2.PowerVSProcessorTypeCapped + case strings.ToLower(string(infrav1.PowerVSProcessorTypeDedicated)): + out.ProcessorType = infrav1.PowerVSProcessorTypeDedicated + case strings.ToLower(string(infrav1.PowerVSProcessorTypeShared)): + out.ProcessorType = infrav1.PowerVSProcessorTypeShared + case strings.ToLower(string(infrav1.PowerVSProcessorTypeCapped)): + out.ProcessorType = infrav1.PowerVSProcessorTypeCapped } return autoConvert_v1beta1_IBMPowerVSMachineSpec_To_v1beta2_IBMPowerVSMachineSpec(in, out, s) } -func Convert_v1beta2_IBMPowerVSMachineSpec_To_v1beta1_IBMPowerVSMachineSpec(in *infrav1beta2.IBMPowerVSMachineSpec, out *IBMPowerVSMachineSpec, s apiconversion.Scope) error { +func Convert_v1beta2_IBMPowerVSMachineSpec_To_v1beta1_IBMPowerVSMachineSpec(in *infrav1.IBMPowerVSMachineSpec, out *IBMPowerVSMachineSpec, s apiconversion.Scope) error { out.SysType = in.SystemType out.Memory = strconv.FormatInt(int64(in.MemoryGiB), 10) @@ -183,33 +183,37 @@ func Convert_v1beta2_IBMPowerVSMachineSpec_To_v1beta1_IBMPowerVSMachineSpec(in * } switch in.ProcessorType { - case infrav1beta2.PowerVSProcessorTypeDedicated: - out.ProcType = strings.ToLower(string(infrav1beta2.PowerVSProcessorTypeDedicated)) - case infrav1beta2.PowerVSProcessorTypeShared: - out.ProcType = strings.ToLower(string(infrav1beta2.PowerVSProcessorTypeShared)) - case infrav1beta2.PowerVSProcessorTypeCapped: - out.ProcType = strings.ToLower(string(infrav1beta2.PowerVSProcessorTypeCapped)) + case infrav1.PowerVSProcessorTypeDedicated: + out.ProcType = strings.ToLower(string(infrav1.PowerVSProcessorTypeDedicated)) + case infrav1.PowerVSProcessorTypeShared: + out.ProcType = strings.ToLower(string(infrav1.PowerVSProcessorTypeShared)) + case infrav1.PowerVSProcessorTypeCapped: + out.ProcType = strings.ToLower(string(infrav1.PowerVSProcessorTypeCapped)) } return autoConvert_v1beta2_IBMPowerVSMachineSpec_To_v1beta1_IBMPowerVSMachineSpec(in, out, s) } -func Convert_v1beta2_IBMPowerVSClusterSpec_To_v1beta1_IBMPowerVSClusterSpec(in *infrav1beta2.IBMPowerVSClusterSpec, out *IBMPowerVSClusterSpec, s apiconversion.Scope) error { +func Convert_v1beta2_IBMPowerVSClusterSpec_To_v1beta1_IBMPowerVSClusterSpec(in *infrav1.IBMPowerVSClusterSpec, out *IBMPowerVSClusterSpec, s apiconversion.Scope) error { if in.ServiceInstance != nil && in.ServiceInstance.ID != nil { out.ServiceInstanceID = *in.ServiceInstance.ID } return autoConvert_v1beta2_IBMPowerVSClusterSpec_To_v1beta1_IBMPowerVSClusterSpec(in, out, s) } -func Convert_v1beta2_IBMPowerVSClusterStatus_To_v1beta1_IBMPowerVSClusterStatus(in *infrav1beta2.IBMPowerVSClusterStatus, out *IBMPowerVSClusterStatus, s apiconversion.Scope) error { +func Convert_v1beta2_IBMPowerVSClusterStatus_To_v1beta1_IBMPowerVSClusterStatus(in *infrav1.IBMPowerVSClusterStatus, out *IBMPowerVSClusterStatus, s apiconversion.Scope) error { return autoConvert_v1beta2_IBMPowerVSClusterStatus_To_v1beta1_IBMPowerVSClusterStatus(in, out, s) } -func Convert_v1beta2_IBMPowerVSImageSpec_To_v1beta1_IBMPowerVSImageSpec(in *infrav1beta2.IBMPowerVSImageSpec, out *IBMPowerVSImageSpec, s apiconversion.Scope) error { +func Convert_v1beta2_IBMPowerVSImageSpec_To_v1beta1_IBMPowerVSImageSpec(in *infrav1.IBMPowerVSImageSpec, out *IBMPowerVSImageSpec, s apiconversion.Scope) error { return autoConvert_v1beta2_IBMPowerVSImageSpec_To_v1beta1_IBMPowerVSImageSpec(in, out, s) } -func Convert_v1beta2_IBMPowerVSMachineStatus_To_v1beta1_IBMPowerVSMachineStatus(in *infrav1beta2.IBMPowerVSMachineStatus, out *IBMPowerVSMachineStatus, s apiconversion.Scope) error { +func Convert_v1beta2_IBMPowerVSMachineStatus_To_v1beta1_IBMPowerVSMachineStatus(in *infrav1.IBMPowerVSMachineStatus, out *IBMPowerVSMachineStatus, s apiconversion.Scope) error { // CAPI V1Beta2 was added in CAPIBM v1beta2 return autoConvert_v1beta2_IBMPowerVSMachineStatus_To_v1beta1_IBMPowerVSMachineStatus(in, out, s) } + +func Convert_v1beta2_IBMPowerVSImageStatus_To_v1beta1_IBMPowerVSImageStatus(in *infrav1.IBMPowerVSImageStatus, out *IBMPowerVSImageStatus, s apiconversion.Scope) error { + return autoConvert_v1beta2_IBMPowerVSImageStatus_To_v1beta1_IBMPowerVSImageStatus(in, out, s) +} diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervscluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervscluster_types.go index 8b0bdbcf8d37..f616d8a3141a 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervscluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervscluster_types.go @@ -19,7 +19,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -44,7 +44,7 @@ type IBMPowerVSClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint capiv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` } // IBMPowerVSClusterStatus defines the observed state of IBMPowerVSCluster. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsclustertemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsclustertemplate_types.go index f83136e2c699..0f99113c9e34 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsclustertemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsclustertemplate_types.go @@ -19,7 +19,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // IBMPowerVSClusterTemplateSpec defines the desired state of IBMPowerVSClusterTemplate. @@ -53,8 +53,8 @@ type IBMPowerVSClusterTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta capiv1beta1.ObjectMeta `json:"metadata,omitempty"` - Spec IBMPowerVSClusterSpec `json:"spec"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` + Spec IBMPowerVSClusterSpec `json:"spec"` } func init() { diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsimage_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsimage_types.go index 1c8386adabb6..535c0d7cb37b 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsimage_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsimage_types.go @@ -19,7 +19,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -51,7 +51,7 @@ type IBMPowerVSImageSpec struct { // Type of storage, storage pool with the most available space will be selected. // +kubebuilder:default=tier1 - // +kubebuilder:validation:Enum=tier1;tier3 + // +kubebuilder:validation:Enum=tier0;tier1;tier3 // +optional StorageType string `json:"storageType,omitempty"` @@ -82,7 +82,7 @@ type IBMPowerVSImageStatus struct { // Conditions defines current service state of the IBMPowerVSImage. // +optional - Conditions capiv1beta1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } //+kubebuilder:object:root=true @@ -100,12 +100,12 @@ type IBMPowerVSImage struct { } // GetConditions returns the observations of the operational state of the IBMPowerVSImage resource. -func (r *IBMPowerVSImage) GetConditions() capiv1beta1.Conditions { +func (r *IBMPowerVSImage) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the IBMPowerVSImage to the predescribed clusterv1.Conditions. -func (r *IBMPowerVSImage) SetConditions(conditions capiv1beta1.Conditions) { +// SetConditions sets the underlying service state of the IBMPowerVSImage to the predescribed clusterv1beta1.Conditions. +func (r *IBMPowerVSImage) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsmachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsmachine_types.go index 09c5eaa2e175..1f09acb805db 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsmachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmpowervsmachine_types.go @@ -20,7 +20,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -164,7 +164,7 @@ type IBMPowerVSMachineStatus struct { // Conditions defines current service state of the IBMPowerVSMachine. // +optional - Conditions capiv1beta1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // Region specifies the Power VS Service instance region. Region *string `json:"region,omitempty"` @@ -194,12 +194,12 @@ type IBMPowerVSMachine struct { } // GetConditions returns the observations of the operational state of the IBMPowerVSMachine resource. -func (r *IBMPowerVSMachine) GetConditions() capiv1beta1.Conditions { +func (r *IBMPowerVSMachine) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the IBMPowerVSMachine to the predescribed clusterv1.Conditions. -func (r *IBMPowerVSMachine) SetConditions(conditions capiv1beta1.Conditions) { +// SetConditions sets the underlying service state of the IBMPowerVSMachine to the predescribed clusterv1beta1.Conditions. +func (r *IBMPowerVSMachine) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmvpc_conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmvpc_conversion.go index a839f00ac1ea..dda591423abe 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmvpc_conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmvpc_conversion.go @@ -23,54 +23,54 @@ import ( utilconversion "sigs.k8s.io/cluster-api/util/conversion" - infrav1beta2 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" + infrav1 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" ) func (src *IBMVPCCluster) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMVPCCluster) + dst := dstRaw.(*infrav1.IBMVPCCluster) return Convert_v1beta1_IBMVPCCluster_To_v1beta2_IBMVPCCluster(src, dst, nil) } func (dst *IBMVPCCluster) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMVPCCluster) + src := srcRaw.(*infrav1.IBMVPCCluster) return Convert_v1beta2_IBMVPCCluster_To_v1beta1_IBMVPCCluster(src, dst, nil) } func (src *IBMVPCClusterList) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMVPCClusterList) + dst := dstRaw.(*infrav1.IBMVPCClusterList) return Convert_v1beta1_IBMVPCClusterList_To_v1beta2_IBMVPCClusterList(src, dst, nil) } func (dst *IBMVPCClusterList) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMVPCClusterList) + src := srcRaw.(*infrav1.IBMVPCClusterList) return Convert_v1beta2_IBMVPCClusterList_To_v1beta1_IBMVPCClusterList(src, dst, nil) } func (src *IBMVPCMachine) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMVPCMachine) + dst := dstRaw.(*infrav1.IBMVPCMachine) if err := Convert_v1beta1_IBMVPCMachine_To_v1beta2_IBMVPCMachine(src, dst, nil); err != nil { return err } if src.Spec.Image != "" { - dst.Spec.Image = &infrav1beta2.IBMVPCResourceReference{ + dst.Spec.Image = &infrav1.IBMVPCResourceReference{ ID: &src.Spec.Image, } } if src.Spec.ImageName != "" { - dst.Spec.Image = &infrav1beta2.IBMVPCResourceReference{ + dst.Spec.Image = &infrav1.IBMVPCResourceReference{ Name: &src.Spec.ImageName, } } for _, sshKey := range src.Spec.SSHKeyNames { - dst.Spec.SSHKeys = append(dst.Spec.SSHKeys, &infrav1beta2.IBMVPCResourceReference{ + dst.Spec.SSHKeys = append(dst.Spec.SSHKeys, &infrav1.IBMVPCResourceReference{ Name: sshKey, }) } @@ -79,7 +79,7 @@ func (src *IBMVPCMachine) ConvertTo(dstRaw conversion.Hub) error { } func (dst *IBMVPCMachine) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMVPCMachine) + src := srcRaw.(*infrav1.IBMVPCMachine) if err := Convert_v1beta2_IBMVPCMachine_To_v1beta1_IBMVPCMachine(src, dst, nil); err != nil { return err @@ -108,38 +108,38 @@ func (dst *IBMVPCMachine) ConvertFrom(srcRaw conversion.Hub) error { } func (src *IBMVPCMachineList) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMVPCMachineList) + dst := dstRaw.(*infrav1.IBMVPCMachineList) return Convert_v1beta1_IBMVPCMachineList_To_v1beta2_IBMVPCMachineList(src, dst, nil) } func (dst *IBMVPCMachineList) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMVPCMachineList) + src := srcRaw.(*infrav1.IBMVPCMachineList) return Convert_v1beta2_IBMVPCMachineList_To_v1beta1_IBMVPCMachineList(src, dst, nil) } func (src *IBMVPCMachineTemplate) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMVPCMachineTemplate) + dst := dstRaw.(*infrav1.IBMVPCMachineTemplate) if err := Convert_v1beta1_IBMVPCMachineTemplate_To_v1beta2_IBMVPCMachineTemplate(src, dst, nil); err != nil { return err } if src.Spec.Template.Spec.Image != "" { - dst.Spec.Template.Spec.Image = &infrav1beta2.IBMVPCResourceReference{ + dst.Spec.Template.Spec.Image = &infrav1.IBMVPCResourceReference{ ID: &src.Spec.Template.Spec.Image, } } if src.Spec.Template.Spec.ImageName != "" { - dst.Spec.Template.Spec.Image = &infrav1beta2.IBMVPCResourceReference{ + dst.Spec.Template.Spec.Image = &infrav1.IBMVPCResourceReference{ Name: &src.Spec.Template.Spec.ImageName, } } for _, sshKey := range src.Spec.Template.Spec.SSHKeyNames { - dst.Spec.Template.Spec.SSHKeys = append(dst.Spec.Template.Spec.SSHKeys, &infrav1beta2.IBMVPCResourceReference{ + dst.Spec.Template.Spec.SSHKeys = append(dst.Spec.Template.Spec.SSHKeys, &infrav1.IBMVPCResourceReference{ Name: sshKey, }) } @@ -148,7 +148,7 @@ func (src *IBMVPCMachineTemplate) ConvertTo(dstRaw conversion.Hub) error { } func (dst *IBMVPCMachineTemplate) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMVPCMachineTemplate) + src := srcRaw.(*infrav1.IBMVPCMachineTemplate) if err := Convert_v1beta2_IBMVPCMachineTemplate_To_v1beta1_IBMVPCMachineTemplate(src, dst, nil); err != nil { return err @@ -177,39 +177,39 @@ func (dst *IBMVPCMachineTemplate) ConvertFrom(srcRaw conversion.Hub) error { } func (src *IBMVPCMachineTemplateList) ConvertTo(dstRaw conversion.Hub) error { - dst := dstRaw.(*infrav1beta2.IBMVPCMachineTemplateList) + dst := dstRaw.(*infrav1.IBMVPCMachineTemplateList) return Convert_v1beta1_IBMVPCMachineTemplateList_To_v1beta2_IBMVPCMachineTemplateList(src, dst, nil) } func (dst *IBMVPCMachineTemplateList) ConvertFrom(srcRaw conversion.Hub) error { - src := srcRaw.(*infrav1beta2.IBMVPCMachineTemplateList) + src := srcRaw.(*infrav1.IBMVPCMachineTemplateList) return Convert_v1beta2_IBMVPCMachineTemplateList_To_v1beta1_IBMVPCMachineTemplateList(src, dst, nil) } -func Convert_v1beta1_IBMVPCMachineSpec_To_v1beta2_IBMVPCMachineSpec(in *IBMVPCMachineSpec, out *infrav1beta2.IBMVPCMachineSpec, s apiconversion.Scope) error { +func Convert_v1beta1_IBMVPCMachineSpec_To_v1beta2_IBMVPCMachineSpec(in *IBMVPCMachineSpec, out *infrav1.IBMVPCMachineSpec, s apiconversion.Scope) error { return autoConvert_v1beta1_IBMVPCMachineSpec_To_v1beta2_IBMVPCMachineSpec(in, out, s) } -func Convert_v1beta2_IBMVPCMachineSpec_To_v1beta1_IBMVPCMachineSpec(in *infrav1beta2.IBMVPCMachineSpec, out *IBMVPCMachineSpec, s apiconversion.Scope) error { +func Convert_v1beta2_IBMVPCMachineSpec_To_v1beta1_IBMVPCMachineSpec(in *infrav1.IBMVPCMachineSpec, out *IBMVPCMachineSpec, s apiconversion.Scope) error { return autoConvert_v1beta2_IBMVPCMachineSpec_To_v1beta1_IBMVPCMachineSpec(in, out, s) } -func Convert_v1beta2_IBMVPCMachineTemplateStatus_To_v1beta1_IBMVPCMachineTemplateStatus(in *infrav1beta2.IBMVPCMachineTemplateStatus, out *IBMVPCMachineTemplateStatus, s apiconversion.Scope) error { +func Convert_v1beta2_IBMVPCMachineTemplateStatus_To_v1beta1_IBMVPCMachineTemplateStatus(in *infrav1.IBMVPCMachineTemplateStatus, out *IBMVPCMachineTemplateStatus, s apiconversion.Scope) error { return autoConvert_v1beta2_IBMVPCMachineTemplateStatus_To_v1beta1_IBMVPCMachineTemplateStatus(in, out, s) } -func Convert_Slice_Pointer_string_To_Slice_Pointer_v1beta2_IBMVPCResourceReference(in *[]*string, out *[]*infrav1beta2.IBMVPCResourceReference, _ apiconversion.Scope) error { +func Convert_Slice_Pointer_string_To_Slice_Pointer_v1beta2_IBMVPCResourceReference(in *[]*string, out *[]*infrav1.IBMVPCResourceReference, _ apiconversion.Scope) error { for _, sshKey := range *in { - *out = append(*out, &infrav1beta2.IBMVPCResourceReference{ + *out = append(*out, &infrav1.IBMVPCResourceReference{ ID: sshKey, }) } return nil } -func Convert_Slice_Pointer_v1beta2_IBMVPCResourceReference_To_Slice_Pointer_string(in *[]*infrav1beta2.IBMVPCResourceReference, out *[]*string, _ apiconversion.Scope) error { +func Convert_Slice_Pointer_v1beta2_IBMVPCResourceReference_To_Slice_Pointer_string(in *[]*infrav1.IBMVPCResourceReference, out *[]*string, _ apiconversion.Scope) error { if in != nil { for _, sshKey := range *in { if sshKey.ID != nil { @@ -220,22 +220,22 @@ func Convert_Slice_Pointer_v1beta2_IBMVPCResourceReference_To_Slice_Pointer_stri return nil } -func Convert_v1beta2_VPCLoadBalancerSpec_To_v1beta1_VPCLoadBalancerSpec(in *infrav1beta2.VPCLoadBalancerSpec, out *VPCLoadBalancerSpec, s apiconversion.Scope) error { +func Convert_v1beta2_VPCLoadBalancerSpec_To_v1beta1_VPCLoadBalancerSpec(in *infrav1.VPCLoadBalancerSpec, out *VPCLoadBalancerSpec, s apiconversion.Scope) error { return autoConvert_v1beta2_VPCLoadBalancerSpec_To_v1beta1_VPCLoadBalancerSpec(in, out, s) } -func Convert_v1beta2_IBMVPCClusterSpec_To_v1beta1_IBMVPCClusterSpec(in *infrav1beta2.IBMVPCClusterSpec, out *IBMVPCClusterSpec, s apiconversion.Scope) error { +func Convert_v1beta2_IBMVPCClusterSpec_To_v1beta1_IBMVPCClusterSpec(in *infrav1.IBMVPCClusterSpec, out *IBMVPCClusterSpec, s apiconversion.Scope) error { return autoConvert_v1beta2_IBMVPCClusterSpec_To_v1beta1_IBMVPCClusterSpec(in, out, s) } -func Convert_v1beta2_IBMVPCClusterStatus_To_v1beta1_IBMVPCClusterStatus(in *infrav1beta2.IBMVPCClusterStatus, out *IBMVPCClusterStatus, s apiconversion.Scope) error { +func Convert_v1beta2_IBMVPCClusterStatus_To_v1beta1_IBMVPCClusterStatus(in *infrav1.IBMVPCClusterStatus, out *IBMVPCClusterStatus, s apiconversion.Scope) error { return autoConvert_v1beta2_IBMVPCClusterStatus_To_v1beta1_IBMVPCClusterStatus(in, out, s) } -func Convert_v1beta2_IBMVPCMachineStatus_To_v1beta1_IBMVPCMachineStatus(in *infrav1beta2.IBMVPCMachineStatus, out *IBMVPCMachineStatus, s apiconversion.Scope) error { +func Convert_v1beta2_IBMVPCMachineStatus_To_v1beta1_IBMVPCMachineStatus(in *infrav1.IBMVPCMachineStatus, out *IBMVPCMachineStatus, s apiconversion.Scope) error { return autoConvert_v1beta2_IBMVPCMachineStatus_To_v1beta1_IBMVPCMachineStatus(in, out, s) } -func Convert_v1beta2_NetworkInterface_To_v1beta1_NetworkInterface(in *infrav1beta2.NetworkInterface, out *NetworkInterface, s apiconversion.Scope) error { +func Convert_v1beta2_NetworkInterface_To_v1beta1_NetworkInterface(in *infrav1.NetworkInterface, out *NetworkInterface, s apiconversion.Scope) error { return autoConvert_v1beta2_NetworkInterface_To_v1beta1_NetworkInterface(in, out, s) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmvpccluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmvpccluster_types.go index 813b3df7b061..a0a3017f9ab4 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmvpccluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/ibmvpccluster_types.go @@ -19,7 +19,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -49,7 +49,7 @@ type IBMVPCClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint capiv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` // ControlPlaneLoadBalancer is optional configuration for customizing control plane behavior. // +optional @@ -83,7 +83,7 @@ type IBMVPCClusterStatus struct { // Conditions defines current service state of the load balancer. // +optional - Conditions capiv1beta1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // VPC holds the VPC information. @@ -121,11 +121,11 @@ func init() { } // GetConditions returns the observations of the operational state of the IBMVPCCluster resource. -func (r *IBMVPCCluster) GetConditions() capiv1beta1.Conditions { +func (r *IBMVPCCluster) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the IBMVPCCluster to the predescribed clusterv1.Conditions. -func (r *IBMVPCCluster) SetConditions(conditions capiv1beta1.Conditions) { +// SetConditions sets the underlying service state of the IBMVPCCluster to the predescribed clusterv1beta1.Conditions. +func (r *IBMVPCCluster) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/zz_generated.conversion.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/zz_generated.conversion.go index ffeb92e4137c..1752c066edd3 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/zz_generated.conversion.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/zz_generated.conversion.go @@ -28,7 +28,7 @@ import ( conversion "k8s.io/apimachinery/pkg/conversion" runtime "k8s.io/apimachinery/pkg/runtime" v1beta2 "sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) func init() { @@ -138,11 +138,6 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1beta2.IBMPowerVSImageStatus)(nil), (*IBMPowerVSImageStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1beta2_IBMPowerVSImageStatus_To_v1beta1_IBMPowerVSImageStatus(a.(*v1beta2.IBMPowerVSImageStatus), b.(*IBMPowerVSImageStatus), scope) - }); err != nil { - return err - } if err := s.AddGeneratedConversionFunc((*IBMPowerVSMachine)(nil), (*v1beta2.IBMPowerVSMachine)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta1_IBMPowerVSMachine_To_v1beta2_IBMPowerVSMachine(a.(*IBMPowerVSMachine), b.(*v1beta2.IBMPowerVSMachine), scope) }); err != nil { @@ -413,6 +408,11 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } + if err := s.AddConversionFunc((*v1beta2.IBMPowerVSImageStatus)(nil), (*IBMPowerVSImageStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_IBMPowerVSImageStatus_To_v1beta1_IBMPowerVSImageStatus(a.(*v1beta2.IBMPowerVSImageStatus), b.(*IBMPowerVSImageStatus), scope) + }); err != nil { + return err + } if err := s.AddConversionFunc((*v1beta2.IBMPowerVSMachineSpec)(nil), (*IBMPowerVSMachineSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1beta2_IBMPowerVSMachineSpec_To_v1beta1_IBMPowerVSMachineSpec(a.(*v1beta2.IBMPowerVSMachineSpec), b.(*IBMPowerVSMachineSpec), scope) }); err != nil { @@ -821,7 +821,7 @@ func autoConvert_v1beta1_IBMPowerVSImageStatus_To_v1beta2_IBMPowerVSImageStatus( out.ImageID = in.ImageID out.ImageState = v1beta2.PowerVSImageState(in.ImageState) out.JobID = in.JobID - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } @@ -835,15 +835,11 @@ func autoConvert_v1beta2_IBMPowerVSImageStatus_To_v1beta1_IBMPowerVSImageStatus( out.ImageID = in.ImageID out.ImageState = PowerVSImageState(in.ImageState) out.JobID = in.JobID - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type return nil } -// Convert_v1beta2_IBMPowerVSImageStatus_To_v1beta1_IBMPowerVSImageStatus is an autogenerated conversion function. -func Convert_v1beta2_IBMPowerVSImageStatus_To_v1beta1_IBMPowerVSImageStatus(in *v1beta2.IBMPowerVSImageStatus, out *IBMPowerVSImageStatus, s conversion.Scope) error { - return autoConvert_v1beta2_IBMPowerVSImageStatus_To_v1beta1_IBMPowerVSImageStatus(in, out, s) -} - func autoConvert_v1beta1_IBMPowerVSMachine_To_v1beta2_IBMPowerVSMachine(in *IBMPowerVSMachine, out *v1beta2.IBMPowerVSMachine, s conversion.Scope) error { out.ObjectMeta = in.ObjectMeta if err := Convert_v1beta1_IBMPowerVSMachineSpec_To_v1beta2_IBMPowerVSMachineSpec(&in.Spec, &out.Spec, s); err != nil { @@ -960,7 +956,7 @@ func autoConvert_v1beta1_IBMPowerVSMachineStatus_To_v1beta2_IBMPowerVSMachineSta out.Fault = in.Fault out.FailureReason = (*string)(unsafe.Pointer(in.FailureReason)) out.FailureMessage = (*string)(unsafe.Pointer(in.FailureMessage)) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) out.Region = (*string)(unsafe.Pointer(in.Region)) out.Zone = (*string)(unsafe.Pointer(in.Zone)) return nil @@ -980,7 +976,7 @@ func autoConvert_v1beta2_IBMPowerVSMachineStatus_To_v1beta1_IBMPowerVSMachineSta out.Fault = in.Fault out.FailureReason = (*string)(unsafe.Pointer(in.FailureReason)) out.FailureMessage = (*string)(unsafe.Pointer(in.FailureMessage)) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) out.Region = (*string)(unsafe.Pointer(in.Region)) out.Zone = (*string)(unsafe.Pointer(in.Zone)) // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type @@ -1282,7 +1278,7 @@ func autoConvert_v1beta1_IBMVPCClusterStatus_To_v1beta2_IBMVPCClusterStatus(in * return err } out.ControlPlaneLoadBalancerState = v1beta2.VPCLoadBalancerState(in.ControlPlaneLoadBalancerState) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) return nil } @@ -1306,7 +1302,8 @@ func autoConvert_v1beta2_IBMVPCClusterStatus_To_v1beta1_IBMVPCClusterStatus(in * return err } out.ControlPlaneLoadBalancerState = VPCLoadBalancerState(in.ControlPlaneLoadBalancerState) - out.Conditions = *(*apiv1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + out.Conditions = *(*corev1beta1.Conditions)(unsafe.Pointer(&in.Conditions)) + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type return nil } @@ -1443,6 +1440,7 @@ func autoConvert_v1beta2_IBMVPCMachineStatus_To_v1beta1_IBMVPCMachineStatus(in * // WARNING: in.FailureMessage requires manual conversion: does not exist in peer-type out.InstanceStatus = in.InstanceStatus // WARNING: in.LoadBalancerPoolMembers requires manual conversion: does not exist in peer-type + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type return nil } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/zz_generated.deepcopy.go index 95204009b5ef..134be0c1d667 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta1/zz_generated.deepcopy.go @@ -23,7 +23,7 @@ package v1beta1 import ( "k8s.io/api/core/v1" runtime "k8s.io/apimachinery/pkg/runtime" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -302,7 +302,7 @@ func (in *IBMPowerVSImageStatus) DeepCopyInto(out *IBMPowerVSImageStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -429,7 +429,7 @@ func (in *IBMPowerVSMachineStatus) DeepCopyInto(out *IBMPowerVSMachineStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -687,7 +687,7 @@ func (in *IBMVPCClusterStatus) DeepCopyInto(out *IBMVPCClusterStatus) { in.VPCEndpoint.DeepCopyInto(&out.VPCEndpoint) if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/conditions_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/conditions_consts.go index 1b8390e3c007..7777739d0e93 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/conditions_consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/conditions_consts.go @@ -17,26 +17,55 @@ limitations under the License. package v1beta2 import ( - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // IBMPowerVSMachine's InstanceReady condition and corresponding reasons that will be used in v1Beta2 API version. const ( // IBMPowerVSMachineReadyV1Beta2Condition is true if the IBMPowerVSMachine's deletionTimestamp is not set, IBMPowerVSMachine's // IBMPowerVSMachineInstanceReadyV1Beta2Condition is true. - IBMPowerVSMachineReadyV1Beta2Condition = capiv1beta1.ReadyV1Beta2Condition + IBMPowerVSMachineReadyV1Beta2Condition = clusterv1beta1.ReadyV1Beta2Condition // IBMPowerVSMachineReadyV1Beta2Reason surfaces when the IBMPowerVSMachine readiness criteria is met. - IBMPowerVSMachineReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + IBMPowerVSMachineReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // IBMPowerVSMachineNotReadyV1Beta2Reason surfaces when the IBMPowerVSMachine readiness criteria is not met. - IBMPowerVSMachineNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + IBMPowerVSMachineNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // IBMPowerVSMachineReadyUnknownV1Beta2Reason surfaces when at least one IBMPowerVSMachine readiness criteria is unknown // and no IBMPowerVSMachine readiness criteria is not met. - IBMPowerVSMachineReadyUnknownV1Beta2Reason = capiv1beta1.ReadyUnknownV1Beta2Reason + IBMPowerVSMachineReadyUnknownV1Beta2Reason = clusterv1beta1.ReadyUnknownV1Beta2Reason ) +const ( + // IBMVPCMachineReadyV1Beta2Condition is true if the IBMVPCMachine's deletionTimestamp is not set, IBMVPCMachine's + // IBMVPCMachineInstanceReadyV1Beta2Condition is true. + IBMVPCMachineReadyV1Beta2Condition = clusterv1beta1.ReadyV1Beta2Condition + + // IBMVPCMachineReadyV1Beta2Reason surfaces when the IBMVPCMachine readiness criteria is met. + IBMVPCMachineReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason + + // IBMVPCMachineNotReadyV1Beta2Reason surfaces when the IBMVPCMachine readiness criteria is not met. + IBMVPCMachineNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason + + // IBMVPCMachineReadyUnknownV1Beta2Reason surfaces when at least one IBMVPCMachine readiness criteria is unknown. + IBMVPCMachineReadyUnknownV1Beta2Reason = clusterv1beta1.ReadyUnknownV1Beta2Reason +) + +// IBMVPCMachine's InstanceReady condition and corresponding reasons that will be used in v1Beta2 API version. +const ( + // IBMVPCMachineInstanceReadyV1Beta2Condition documents the status of the instance that is controlled + // by the IBMVPCMachine. + IBMVPCMachineInstanceReadyV1Beta2Condition = "InstanceReady" + + // IBMVPCMachineInstanceReadyV1Beta2Reason surfaces when the instance that is controlled + // by the IBMVPCMachine is ready. + IBMVPCMachineInstanceReadyV1Beta2Reason = "InstanceReady" + + // IBMVPCMachineInstanceNotReadyV1Beta2Reason surfaces when the instance that is controlled + // by the IBMVPCMachine is not ready. + IBMVPCMachineInstanceNotReadyV1Beta2Reason = "InstanceNotReady" +) const ( // IBMPowerVSMachineInstanceReadyV1Beta2Condition documents the status of the instance that is controlled // by the IBMPowerVSMachine. @@ -52,21 +81,21 @@ const ( // IBMPowerVSMachineInstanceWaitingForClusterInfrastructureReadyV1Beta2Reason documents the virtual machine that is controller by // IBMPowerVSMachine waiting for the cluster infrastructure to be ready. - // TODO: Use when CAPI version is updated: IBMPowerVSMachineInstanceWaitingForClusterInfrastructureReadyV1Beta2Reason = capiv1beta1.WaitingForClusterInfrastructureReadyV1Beta2Reason. + // TODO: Use when CAPI version is updated: IBMPowerVSMachineInstanceWaitingForClusterInfrastructureReadyV1Beta2Reason = clusterv1beta1.WaitingForClusterInfrastructureReadyV1Beta2Reason. IBMPowerVSMachineInstanceWaitingForClusterInfrastructureReadyV1Beta2Reason = "WaitingForClusterInfrastructureReady" // IBMPowerVSMachineInstanceWaitingForControlPlaneInitializedV1Beta2Reason documents the virtual machine that is controller by IBMPowerVSMachine waiting // for the control plane to be initialized. - // TODO: Use when CAPI version is updated: IBMPowerVSMachineInstanceWaitingForControlPlaneInitializedV1Beta2Reason = capiv1beta1.WaitingForControlPlaneInitializedV1Beta2Reason. + // TODO: Use when CAPI version is updated: IBMPowerVSMachineInstanceWaitingForControlPlaneInitializedV1Beta2Reason = clusterv1beta1.WaitingForControlPlaneInitializedV1Beta2Reason. IBMPowerVSMachineInstanceWaitingForControlPlaneInitializedV1Beta2Reason = "WaitingForControlPlaneInitialized" // IBMPowerVSMachineInstanceWaitingForBootstrapDataV1Beta2Reason documents the virtual machine that is controller by IBMPowerVSMachine waiting for the bootstrap // data to be ready. - // TODO: Use when CAPI version is updated: IBMPowerVSMachineInstanceWaitingForBootstrapDataV1Beta2Reason = capiv1beta1.WaitingForBootstrapDataV1Beta2Reason. + // TODO: Use when CAPI version is updated: IBMPowerVSMachineInstanceWaitingForBootstrapDataV1Beta2Reason = clusterv1beta1.WaitingForBootstrapDataV1Beta2Reason. IBMPowerVSMachineInstanceWaitingForBootstrapDataV1Beta2Reason = "WaitingForBootstrapData" // IBMPowerVSMachineInstanceDeletingV1Beta2Reason surfaces when the virtual machine controller by IBMPowerVSMachine is deleting. - IBMPowerVSMachineInstanceDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + IBMPowerVSMachineInstanceDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason // IBMPowerVSMachineInstanceLoadBalancerConfigurationFailedV1Beta2Reason surfaces when configuring the virtual machine IP to load balancer fails. IBMPowerVSMachineInstanceLoadBalancerConfigurationFailedV1Beta2Reason = "LoadBalancerConfigurationFailed" @@ -95,13 +124,16 @@ const ( // InstanceNotReadyReason used when the instance is in a not ready state. InstanceNotReadyReason = "InstanceNotReady" + // InstanceDeletingReason is used when the instance is in deleting state. + InstanceDeletingReason = "InstanceDeleting" + // InstanceStateUnknownReason used when the instance is in a unknown state. InstanceStateUnknownReason = "InstanceStateUnknown" ) const ( // InstanceReadyCondition reports on current status of the instance. Ready indicates the instance is in a Running state. - InstanceReadyCondition capiv1beta1.ConditionType = "InstanceReady" + InstanceReadyCondition clusterv1beta1.ConditionType = "InstanceReady" ) const ( @@ -110,7 +142,7 @@ const ( ) const ( - // ImageNotReadyReason used when the image is in a queued state. + // ImageNotReadyReason used when the image is not ready. ImageNotReadyReason = "ImageNotReady" // ImageImportFailedReason used when the image import is failed. @@ -118,14 +150,20 @@ const ( // ImageReconciliationFailedReason used when an error occurs during VPC Custom Image reconciliation. ImageReconciliationFailedReason = "ImageReconciliationFailed" + + // ImageQueuedReason used when the image is in queued state. + ImageQueuedReason = "ImageQueued" ) const ( // ImageReadyCondition reports on current status of the image. Ready indicates the image is in a active state. - ImageReadyCondition capiv1beta1.ConditionType = "ImageReady" + ImageReadyCondition clusterv1beta1.ConditionType = "ImageReady" // ImageImportedCondition reports on current status of the image import job. Ready indicates the import job is finished. - ImageImportedCondition capiv1beta1.ConditionType = "ImageImported" + ImageImportedCondition clusterv1beta1.ConditionType = "ImageImported" + + // IBMPowerVSImageDeletingV1Beta2Reason surfaces when the image is in deleting state. + IBMPowerVSImageDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason ) const ( @@ -135,42 +173,42 @@ const ( const ( // ServiceInstanceReadyCondition reports on the successful reconciliation of a Power VS workspace. - ServiceInstanceReadyCondition capiv1beta1.ConditionType = "ServiceInstanceReady" + ServiceInstanceReadyCondition clusterv1beta1.ConditionType = "ServiceInstanceReady" // ServiceInstanceReconciliationFailedReason used when an error occurs during workspace reconciliation. ServiceInstanceReconciliationFailedReason = "ServiceInstanceReconciliationFailed" // NetworkReadyCondition reports on the successful reconciliation of a Power VS network. - NetworkReadyCondition capiv1beta1.ConditionType = "NetworkReady" + NetworkReadyCondition clusterv1beta1.ConditionType = "NetworkReady" // NetworkReconciliationFailedReason used when an error occurs during network reconciliation. NetworkReconciliationFailedReason = "NetworkReconciliationFailed" // VPCSecurityGroupReadyCondition reports on the successful reconciliation of a VPC. - VPCSecurityGroupReadyCondition capiv1beta1.ConditionType = "VPCSecurityGroupReady" + VPCSecurityGroupReadyCondition clusterv1beta1.ConditionType = "VPCSecurityGroupReady" // VPCSecurityGroupReconciliationFailedReason used when an error occurs during VPC reconciliation. VPCSecurityGroupReconciliationFailedReason = "VPCSecurityGroupReconciliationFailed" // VPCReadyCondition reports on the successful reconciliation of a VPC. - VPCReadyCondition capiv1beta1.ConditionType = "VPCReady" + VPCReadyCondition clusterv1beta1.ConditionType = "VPCReady" // VPCReconciliationFailedReason used when an error occurs during VPC reconciliation. VPCReconciliationFailedReason = "VPCReconciliationFailed" // VPCSubnetReadyCondition reports on the successful reconciliation of a VPC subnet. - VPCSubnetReadyCondition capiv1beta1.ConditionType = "VPCSubnetReady" + VPCSubnetReadyCondition clusterv1beta1.ConditionType = "VPCSubnetReady" // VPCSubnetReconciliationFailedReason used when an error occurs during VPC subnet reconciliation. VPCSubnetReconciliationFailedReason = "VPCSubnetReconciliationFailed" // TransitGatewayReadyCondition reports on the successful reconciliation of a Power VS transit gateway. - TransitGatewayReadyCondition capiv1beta1.ConditionType = "TransitGatewayReady" + TransitGatewayReadyCondition clusterv1beta1.ConditionType = "TransitGatewayReady" // TransitGatewayReconciliationFailedReason used when an error occurs during transit gateway reconciliation. TransitGatewayReconciliationFailedReason = "TransitGatewayReconciliationFailed" // LoadBalancerReadyCondition reports on the successful reconciliation of a Power VS network. - LoadBalancerReadyCondition capiv1beta1.ConditionType = "LoadBalancerReady" + LoadBalancerReadyCondition clusterv1beta1.ConditionType = "LoadBalancerReady" // LoadBalancerReconciliationFailedReason used when an error occurs during loadbalancer reconciliation. LoadBalancerReconciliationFailedReason = "LoadBalancerReconciliationFailed" // COSInstanceReadyCondition reports on the successful reconciliation of a COS instance. - COSInstanceReadyCondition capiv1beta1.ConditionType = "COSInstanceCreated" + COSInstanceReadyCondition clusterv1beta1.ConditionType = "COSInstanceCreated" // COSInstanceReconciliationFailedReason used when an error occurs during COS instance reconciliation. COSInstanceReconciliationFailedReason = "COSInstanceCreationFailed" ) @@ -185,17 +223,34 @@ const ( const ( // IBMPowerVSClusterReadyV1Beta2Condition is true if the IBMPowerVSCluster's deletionTimestamp is not set, IBMPowerVSCluster's // FailureDomainsReady, VCenterAvailable and ClusterModulesReady conditions are true. - IBMPowerVSClusterReadyV1Beta2Condition = capiv1beta1.ReadyV1Beta2Condition + IBMPowerVSClusterReadyV1Beta2Condition = clusterv1beta1.ReadyV1Beta2Condition // IBMPowerVSClusterReadyV1Beta2Reason surfaces when the IBMPowerVSCluster readiness criteria is met. - IBMPowerVSClusterReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + IBMPowerVSClusterReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // IBMPowerVSClusterNotReadyV1Beta2Reason surfaces when the IBMPowerVSCluster readiness criteria is not met. - IBMPowerVSClusterNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + IBMPowerVSClusterNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // IBMPowerVSClusterReadyUnknownV1Beta2Reason surfaces when at least one of the IBMPowerVSCluster readiness criteria is unknown // and none of the IBMPowerVSCluster readiness criteria is met. - IBMPowerVSClusterReadyUnknownV1Beta2Reason = capiv1beta1.ReadyUnknownV1Beta2Reason + IBMPowerVSClusterReadyUnknownV1Beta2Reason = clusterv1beta1.ReadyUnknownV1Beta2Reason +) + +// IBMVPCCluster's Ready condition and corresponding reasons that will be used in v1Beta2 API version. +const ( + // IBMVPCClusterReadyV1Beta2Condition is true if the IBMVPCCluster's deletionTimestamp is not set and IBMVPCCluster's + // conditions are true. + IBMVPCClusterReadyV1Beta2Condition = clusterv1beta1.ReadyV1Beta2Condition + + // IBMVPCClusterReadyV1Beta2Reason surfaces when the IBMVPCCluster readiness criteria is met. + IBMVPCClusterReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason + + // IBMVPCClusterNotReadyV1Beta2Reason surfaces when the IBMVPCCluster readiness criteria is not met. + IBMVPCClusterNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason + + // IBMVPCClusterReadyUnknownV1Beta2Reason surfaces when at least one of the IBMVPCCluster readiness criteria is unknown + // and none of the IBMVPCCluster readiness criteria is met. + IBMVPCClusterReadyUnknownV1Beta2Reason = clusterv1beta1.ReadyUnknownV1Beta2Reason ) const ( @@ -203,95 +258,123 @@ const ( WorkspaceReadyV1Beta2Condition = "WorkspaceReady" // WorkspaceReadyV1Beta2Reason surfaces when the PowerVS workspace is ready. - WorkspaceReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + WorkspaceReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // WorkspaceNotReadyV1Beta2Reason surfaces when PowerVS workspace is not ready. - WorkspaceNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + WorkspaceNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // WorkspaceDeletingV1Beta2Reason surfaces when the PowerVS workspace is being deleted. - WorkspaceDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + WorkspaceDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason // NetworkReadyV1Beta2Condition reports on the successful reconciliation of a PowerVS network. NetworkReadyV1Beta2Condition = "NetworkReady" // NetworkReadyV1Beta2Reason surfaces when PowerVS workspace is ready. - NetworkReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + NetworkReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // NetworkNotReadyV1Beta2Reason surfaces when the PowerVS network is not ready. - NetworkNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + NetworkNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // NetworkDeletingV1Beta2Reason surfaces when the PowerVS network is being deleted. - NetworkDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + NetworkDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason // VPCReadyV1Beta2Condition reports on the successful reconciliation of a VPC. VPCReadyV1Beta2Condition = "VPCReady" // VPCReadyV1Beta2Reason surfaces when the VPC is ready. - VPCReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + VPCReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // VPCNotReadyV1Beta2Reason surfaces when VPC is not ready. - VPCNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + VPCNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // VPCDeletingV1Beta2Reason surfaces when the VPC is being deleted. - VPCDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + VPCDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason // VPCSubnetReadyV1Beta2Condition reports on the successful reconciliation of a VPC subnet. VPCSubnetReadyV1Beta2Condition = "VPCSubnetReady" // VPCSubnetReadyV1Beta2Reason surfaces when the VPC subnet is ready. - VPCSubnetReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + VPCSubnetReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // VPCSubnetNotReadyV1Beta2Reason surfaces when VPC subnet is not ready. - VPCSubnetNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + VPCSubnetNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // VPCSubnetDeletingV1Beta2Reason surfaces when the VPC subnet is being deleted. - VPCSubnetDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + VPCSubnetDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason // VPCSecurityGroupReadyV1Beta2Condition reports on the successful reconciliation of a VPC Security Group. VPCSecurityGroupReadyV1Beta2Condition = "VPCSecurityGroupReady" // VPCSecurityGroupReadyV1Beta2Reason surfaces when the VPC security group is ready. - VPCSecurityGroupReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + VPCSecurityGroupReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // VPCSecurityGroupNotReadyV1Beta2Reason surfaces when VPC security group is not ready. - VPCSecurityGroupNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + VPCSecurityGroupNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // VPCSecurityGroupDeletingV1Beta2Reason surfaces when the VPC security group is being deleted. - VPCSecurityGroupDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + VPCSecurityGroupDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason // TransitGatewayReadyV1Beta2Condition reports on the successful reconciliation of a transit gateway. TransitGatewayReadyV1Beta2Condition = "TransitGatewayReady" // TransitGatewayReadyV1Beta2Reason surfaces when the transit gateway is ready. - TransitGatewayReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + TransitGatewayReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // TransitGatewayNotReadyV1Beta2Reason surfaces when the transit gateway is not ready. - TransitGatewayNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + TransitGatewayNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // TransitGatewayDeletingV1Beta2Reason surfaces when the transit gateway is being deleted. - TransitGatewayDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + TransitGatewayDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason // VPCLoadBalancerReadyV1Beta2Condition reports on the successful reconciliation of a VPC LoadBalancer. VPCLoadBalancerReadyV1Beta2Condition = "LoadBalancerReady" // VPCLoadBalancerReadyV1Beta2Reason surfaces when the VPC LoadBalancer is ready. - VPCLoadBalancerReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + VPCLoadBalancerReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // VPCLoadBalancerNotReadyV1Beta2Reason surfaces when VPC LoadBalancer is not ready. - VPCLoadBalancerNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + VPCLoadBalancerNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // VPCLoadBalancerDeletingV1Beta2Reason surfaces when the VPC LoadBalancer is being deleted. - VPCLoadBalancerDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + VPCLoadBalancerDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason + + // VPCImageReadyV1Beta2Condition reports on the successful reconciliation of a VPC custom image. + VPCImageReadyV1Beta2Condition = "VPCImageReady" + + // VPCImageReadyV1Beta2Reason surfaces when the VPC custom image is ready. + VPCImageReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason + + // VPCImageNotReadyV1Beta2Reason surfaces when the VPC custom image is not ready. + VPCImageNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // COSInstanceReadyV1Beta2Condition reports on the successful reconciliation of a COS instance. COSInstanceReadyV1Beta2Condition = "COSInstanceReady" // COSInstanceReadyV1Beta2Reason surfaces when the COS instance is ready. - COSInstanceReadyV1Beta2Reason = capiv1beta1.ReadyV1Beta2Reason + COSInstanceReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason // COSInstanceNotReadyV1Beta2Reason surfaces when the COS instance is not ready. - COSInstanceNotReadyV1Beta2Reason = capiv1beta1.NotReadyV1Beta2Reason + COSInstanceNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason // COSInstanceDeletingV1Beta2Reason surfaces when the COS instance is being deleted. - COSInstanceDeletingV1Beta2Reason = capiv1beta1.DeletingV1Beta2Reason + COSInstanceDeletingV1Beta2Reason = clusterv1beta1.DeletingV1Beta2Reason +) + +// IBMPowerVSImage's Ready condition and corresponding reasons that will be used in v1Beta2 API version. +const ( + // IBMPowerVSImageReadyCondition is true if the IBMPowerVSImage's deletionTimestamp is not set, IBMPowerVSImage's IBMPowerVSImageReadyV1Beta2Condition is true. + IBMPowerVSImageReadyCondition = clusterv1beta1.ReadyV1Beta2Condition + + // IBMPowerVSImageReadyV1Beta2Condition documents the Ready status of the image. + IBMPowerVSImageReadyV1Beta2Condition = "ImageReady" + + // IBMPowerVSImageReadyV1Beta2Reason surfaces when the IBMPowerVSImage readiness criteria is met. + IBMPowerVSImageReadyV1Beta2Reason = clusterv1beta1.ReadyV1Beta2Reason + + // IBMPowerVSImageNotReadyV1Beta2Reason surfaces when the IBMPowerVSImage readiness criteria is not met. + IBMPowerVSImageNotReadyV1Beta2Reason = clusterv1beta1.NotReadyV1Beta2Reason + + // IBMPowerVSImageReadyUnknownV1Beta2Reason surfaces when at least one of the IBMPowerVSImage readiness criteria is unknown + // and none of the IBMPowerVSImage readiness criteria is met. + IBMPowerVSImageReadyUnknownV1Beta2Reason = clusterv1beta1.ReadyUnknownV1Beta2Reason ) diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervscluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervscluster_types.go index 6d6b69acf681..bebd4d516bca 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervscluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervscluster_types.go @@ -19,7 +19,7 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -54,7 +54,7 @@ type IBMPowerVSClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint capiv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` // serviceInstance is the reference to the Power VS server workspace on which the server instance(VM) will be created. // Power VS server workspace is a container for all Power VS instances at a specific geographic region. @@ -231,7 +231,7 @@ type IBMPowerVSClusterStatus struct { LoadBalancers map[string]VPCLoadBalancerStatus `json:"loadBalancers,omitempty"` // Conditions defines current service state of the IBMPowerVSCluster. - Conditions capiv1beta1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // v1beta2 groups all the fields that will be added or modified in IBMPowerVSCluster's status with the V1Beta2 version. // +optional @@ -335,12 +335,12 @@ type CosInstance struct { } // GetConditions returns the observations of the operational state of the IBMPowerVSCluster resource. -func (r *IBMPowerVSCluster) GetConditions() capiv1beta1.Conditions { +func (r *IBMPowerVSCluster) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the IBMPowerVSCluster to the predescribed clusterv1.Conditions. -func (r *IBMPowerVSCluster) SetConditions(conditions capiv1beta1.Conditions) { +// SetConditions sets the underlying service state of the IBMPowerVSCluster to the predescribed clusterv1beta1.Conditions. +func (r *IBMPowerVSCluster) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsclustertemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsclustertemplate_types.go index 202a6b188eb6..b1b375a1f2f5 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsclustertemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsclustertemplate_types.go @@ -19,7 +19,7 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // IBMPowerVSClusterTemplateSpec defines the desired state of IBMPowerVSClusterTemplate. @@ -54,8 +54,8 @@ type IBMPowerVSClusterTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta capiv1beta1.ObjectMeta `json:"metadata,omitempty"` - Spec IBMPowerVSClusterSpec `json:"spec"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` + Spec IBMPowerVSClusterSpec `json:"spec"` } func init() { diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsimage_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsimage_types.go index 4431e5fa0baa..2cd33c8e3567 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsimage_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsimage_types.go @@ -19,7 +19,7 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -62,7 +62,7 @@ type IBMPowerVSImageSpec struct { // Type of storage, storage pool with the most available space will be selected. // +kubebuilder:default=tier1 - // +kubebuilder:validation:Enum=tier1;tier3 + // +kubebuilder:validation:Enum=tier0;tier1;tier3 // +optional StorageType string `json:"storageType,omitempty"` @@ -93,7 +93,22 @@ type IBMPowerVSImageStatus struct { // Conditions defines current service state of the IBMPowerVSImage. // +optional - Conditions capiv1beta1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` + + // v1beta2 groups all the fields that will be added or modified in IBMPowerVSCluster's status with the V1Beta2 version. + // +optional + V1Beta2 *IBMPowerVSImageV1Beta2Status `json:"v1beta2,omitempty"` +} + +// IBMPowerVSImageV1Beta2Status groups all the fields that will be added or modified in IBMPowerVSCluster with the V1Beta2 version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type IBMPowerVSImageV1Beta2Status struct { + // conditions represents the observations of a DevCluster's current state. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` } //+kubebuilder:object:root=true @@ -112,15 +127,31 @@ type IBMPowerVSImage struct { } // GetConditions returns the observations of the operational state of the IBMPowerVSImage resource. -func (r *IBMPowerVSImage) GetConditions() capiv1beta1.Conditions { +func (r *IBMPowerVSImage) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the IBMPowerVSImage to the predescribed clusterv1.Conditions. -func (r *IBMPowerVSImage) SetConditions(conditions capiv1beta1.Conditions) { +// SetConditions sets the underlying service state of the IBMPowerVSImage to the predescribed clusterv1beta1.Conditions. +func (r *IBMPowerVSImage) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } +// GetV1Beta2Conditions returns the set of conditions for this object. +func (r *IBMPowerVSImage) GetV1Beta2Conditions() []metav1.Condition { + if r.Status.V1Beta2 == nil { + return nil + } + return r.Status.V1Beta2.Conditions +} + +// SetV1Beta2Conditions sets conditions for an API object. +func (r *IBMPowerVSImage) SetV1Beta2Conditions(conditions []metav1.Condition) { + if r.Status.V1Beta2 == nil { + r.Status.V1Beta2 = &IBMPowerVSImageV1Beta2Status{} + } + r.Status.V1Beta2.Conditions = conditions +} + //+kubebuilder:object:root=true // IBMPowerVSImageList contains a list of IBMPowerVSImage. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsmachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsmachine_types.go index 523e2b8056be..2e12ff2089a4 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsmachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmpowervsmachine_types.go @@ -21,7 +21,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -220,7 +220,7 @@ type IBMPowerVSMachineStatus struct { // Conditions defines current service state of the IBMPowerVSMachine. // +optional - Conditions capiv1beta1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // Region specifies the Power VS Service instance region. Region *string `json:"region,omitempty"` @@ -267,12 +267,12 @@ type IBMPowerVSMachine struct { } // GetConditions returns the observations of the operational state of the IBMPowerVSMachine resource. -func (r *IBMPowerVSMachine) GetConditions() capiv1beta1.Conditions { +func (r *IBMPowerVSMachine) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the IBMPowerVSMachine to the predescribed clusterv1.Conditions. -func (r *IBMPowerVSMachine) SetConditions(conditions capiv1beta1.Conditions) { +// SetConditions sets the underlying service state of the IBMPowerVSMachine to the predescribed clusterv1beta1.Conditions. +func (r *IBMPowerVSMachine) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpccluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpccluster_types.go index 60caf354d291..848f7f570486 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpccluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpccluster_types.go @@ -19,7 +19,7 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -49,7 +49,7 @@ type IBMVPCClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional - ControlPlaneEndpoint capiv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` + ControlPlaneEndpoint clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint"` // ControlPlaneLoadBalancer is optional configuration for customizing control plane behavior. // Use this for legacy support, use Network.LoadBalancers for the extended VPC support. @@ -127,6 +127,11 @@ type AdditionalListenerSpec struct { // Will default to TCP protocol if not specified. // +optional Protocol *VPCLoadBalancerListenerProtocol `json:"protocol,omitempty"` + + // The selector is used to find IBMPowerVSMachines with matching labels. + // If the label matches, the machine is then added to the load balancer listener configuration. + // +kubebuilder:validation:Optional + Selector metav1.LabelSelector `json:"selector,omitempty"` } // VPCLoadBalancerBackendPoolSpec defines the desired configuration of a VPC Load Balancer Backend Pool. @@ -314,7 +319,22 @@ type IBMVPCClusterStatus struct { // Conditions defines current service state of the load balancer. // +optional - Conditions capiv1beta1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` + + // V1beta2 groups all the fields that will be added or modified in IBMVPCCluster's status with the V1Beta2 version. + // +optional + V1Beta2 *IBMVPCClusterV1Beta2Status `json:"v1beta2,omitempty"` +} + +// IBMVPCClusterV1Beta2Status groups all the fields that will be added or modified in IBMVPCClusterStatus with the V1Beta2 version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type IBMVPCClusterV1Beta2Status struct { + // Conditions represents the observations of a IBMVPCCluster's current state. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` } // VPCNetworkStatus provides details on the status of VPC network resources for extended VPC Infrastructure support. @@ -386,15 +406,31 @@ type IBMVPCClusterList struct { } // GetConditions returns the observations of the operational state of the IBMVPCCluster resource. -func (r *IBMVPCCluster) GetConditions() capiv1beta1.Conditions { +func (r *IBMVPCCluster) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the IBMVPCCluster to the predescribed clusterv1.Conditions. -func (r *IBMVPCCluster) SetConditions(conditions capiv1beta1.Conditions) { +// SetConditions sets the underlying service state of the IBMVPCCluster to the predescribed clusterv1beta1.Conditions. +func (r *IBMVPCCluster) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } +// GetV1Beta2Conditions returns the set of conditions for IBMVPCCluster object. +func (r *IBMVPCCluster) GetV1Beta2Conditions() []metav1.Condition { + if r.Status.V1Beta2 == nil { + return nil + } + return r.Status.V1Beta2.Conditions +} + +// SetV1Beta2Conditions sets conditions for IBMVPCCluster object. +func (r *IBMVPCCluster) SetV1Beta2Conditions(conditions []metav1.Condition) { + if r.Status.V1Beta2 == nil { + r.Status.V1Beta2 = &IBMVPCClusterV1Beta2Status{} + } + r.Status.V1Beta2.Conditions = conditions +} + func init() { objectTypes = append(objectTypes, &IBMVPCCluster{}, &IBMVPCClusterList{}) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpcclustertemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpcclustertemplate_types.go index 855920c0c090..e018d719f4ef 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpcclustertemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpcclustertemplate_types.go @@ -19,7 +19,7 @@ package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // IBMVPCClusterTemplateSpec defines the desired state of IBMVPCClusterTemplate. @@ -53,8 +53,8 @@ type IBMVPCClusterTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - ObjectMeta capiv1beta1.ObjectMeta `json:"metadata,omitempty"` - Spec IBMVPCClusterSpec `json:"spec"` + ObjectMeta clusterv1beta1.ObjectMeta `json:"metadata,omitempty"` + Spec IBMVPCClusterSpec `json:"spec"` } func init() { diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpcmachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpcmachine_types.go index df3aae0db924..065ed282d797 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpcmachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/ibmvpcmachine_types.go @@ -20,7 +20,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint:staticcheck ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. @@ -154,7 +154,7 @@ type IBMVPCMachineStatus struct { // Conditions deefines current service state of the IBMVPCMachine. // +optional - Conditions capiv1beta1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` // FailureReason will be set in the event that there is a terminal problem // reconciling the Machine and will contain a succinct value suitable @@ -175,6 +175,21 @@ type IBMVPCMachineStatus struct { // LoadBalancerPoolMembers is the status of IBM Cloud VPC Load Balancer Backend Pools the machine is a member. // +optional LoadBalancerPoolMembers []VPCLoadBalancerBackendPoolMember `json:"loadBalancerPoolMembers,omitempty"` + + // V1beta2 groups all the fields that will be added or modified in IBMVPCMachine's status with the V1Beta2 version. + // +optional + V1Beta2 *IBMVPCMachineV1Beta2Status `json:"v1beta2,omitempty"` +} + +// IBMVPCMachineV1Beta2Status groups all the fields that will be added or modified in IBMVPCMachineStatus with the V1Beta2 version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type IBMVPCMachineV1Beta2Status struct { + // Conditions represents the observations of a IBMVPCMachine's current state. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` } // +kubebuilder:object:root=true @@ -193,12 +208,12 @@ type IBMVPCMachine struct { } // GetConditions returns the observations of the operational state of the IBMVPCMachine resource. -func (r *IBMVPCMachine) GetConditions() capiv1beta1.Conditions { +func (r *IBMVPCMachine) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } -// SetConditions sets the underlying service state of the IBMVPCMachine to the predescribed clusterv1.Conditions. -func (r *IBMVPCMachine) SetConditions(conditions capiv1beta1.Conditions) { +// SetConditions sets the underlying service state of the IBMVPCMachine to the predescribed clusterv1beta1.Conditions. +func (r *IBMVPCMachine) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } @@ -211,6 +226,22 @@ type IBMVPCMachineList struct { Items []IBMVPCMachine `json:"items"` } +// GetV1Beta2Conditions returns the set of conditions for IBMVPCMachine object. +func (r *IBMVPCMachine) GetV1Beta2Conditions() []metav1.Condition { + if r.Status.V1Beta2 == nil { + return nil + } + return r.Status.V1Beta2.Conditions +} + +// SetV1Beta2Conditions sets conditions for IBMVPCMachine object. +func (r *IBMVPCMachine) SetV1Beta2Conditions(conditions []metav1.Condition) { + if r.Status.V1Beta2 == nil { + r.Status.V1Beta2 = &IBMVPCMachineV1Beta2Status{} + } + r.Status.V1Beta2.Conditions = conditions +} + func init() { objectTypes = append(objectTypes, &IBMVPCMachine{}, &IBMVPCMachineList{}) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/types.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/types.go index 4ebd4da6a435..237a7cf37a52 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/types.go @@ -56,14 +56,17 @@ var ( // PowerVSImageStateACTIVE is the string representing an image in a active state. PowerVSImageStateACTIVE = PowerVSImageState("active") - // PowerVSImageStateQue is the string representing an image in a queued state. - PowerVSImageStateQue = PowerVSImageState("queued") + // PowerVSImageStateQueued is the string representing an image in a queued state. + PowerVSImageStateQueued = PowerVSImageState("queued") // PowerVSImageStateFailed is the string representing an image in a failed state. PowerVSImageStateFailed = PowerVSImageState("failed") // PowerVSImageStateImporting is the string representing an image in a failed state. PowerVSImageStateImporting = PowerVSImageState("importing") + + // PowerVSImageStateCompleted is the string representing an image in a completed state. + PowerVSImageStateCompleted = PowerVSImageState("completed") ) // ServiceInstanceState describes the state of a service instance. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/zz_generated.deepcopy.go index b0ba240ba49c..faad44717820 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-ibmcloud/api/v1beta2/zz_generated.deepcopy.go @@ -24,7 +24,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/cluster-api/api/v1beta1" + "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -40,6 +40,7 @@ func (in *AdditionalListenerSpec) DeepCopyInto(out *AdditionalListenerSpec) { *out = new(VPCLoadBalancerListenerProtocol) **out = **in } + in.Selector.DeepCopyInto(&out.Selector) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdditionalListenerSpec. @@ -594,6 +595,11 @@ func (in *IBMPowerVSImageStatus) DeepCopyInto(out *IBMPowerVSImageStatus) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.V1Beta2 != nil { + in, out := &in.V1Beta2, &out.V1Beta2 + *out = new(IBMPowerVSImageV1Beta2Status) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IBMPowerVSImageStatus. @@ -606,6 +612,28 @@ func (in *IBMPowerVSImageStatus) DeepCopy() *IBMPowerVSImageStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IBMPowerVSImageV1Beta2Status) DeepCopyInto(out *IBMPowerVSImageV1Beta2Status) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IBMPowerVSImageV1Beta2Status. +func (in *IBMPowerVSImageV1Beta2Status) DeepCopy() *IBMPowerVSImageV1Beta2Status { + if in == nil { + return nil + } + out := new(IBMPowerVSImageV1Beta2Status) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IBMPowerVSMachine) DeepCopyInto(out *IBMPowerVSMachine) { *out = *in @@ -1037,6 +1065,11 @@ func (in *IBMVPCClusterStatus) DeepCopyInto(out *IBMVPCClusterStatus) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.V1Beta2 != nil { + in, out := &in.V1Beta2, &out.V1Beta2 + *out = new(IBMVPCClusterV1Beta2Status) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IBMVPCClusterStatus. @@ -1140,6 +1173,28 @@ func (in *IBMVPCClusterTemplateSpec) DeepCopy() *IBMVPCClusterTemplateSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IBMVPCClusterV1Beta2Status) DeepCopyInto(out *IBMVPCClusterV1Beta2Status) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IBMVPCClusterV1Beta2Status. +func (in *IBMVPCClusterV1Beta2Status) DeepCopy() *IBMVPCClusterV1Beta2Status { + if in == nil { + return nil + } + out := new(IBMVPCClusterV1Beta2Status) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IBMVPCMachine) DeepCopyInto(out *IBMVPCMachine) { *out = *in @@ -1290,6 +1345,11 @@ func (in *IBMVPCMachineStatus) DeepCopyInto(out *IBMVPCMachineStatus) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.V1Beta2 != nil { + in, out := &in.V1Beta2, &out.V1Beta2 + *out = new(IBMVPCMachineV1Beta2Status) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IBMVPCMachineStatus. @@ -1415,6 +1475,28 @@ func (in *IBMVPCMachineTemplateStatus) DeepCopy() *IBMVPCMachineTemplateStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IBMVPCMachineV1Beta2Status) DeepCopyInto(out *IBMVPCMachineV1Beta2Status) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IBMVPCMachineV1Beta2Status. +func (in *IBMVPCMachineV1Beta2Status) DeepCopy() *IBMVPCMachineV1Beta2Status { + if in == nil { + return nil + } + out := new(IBMVPCMachineV1Beta2Status) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IBMVPCResourceReference) DeepCopyInto(out *IBMVPCResourceReference) { *out = *in diff --git a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/condition_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/condition_consts.go index 7f671d8efcae..7848d632821c 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/condition_consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/condition_consts.go @@ -16,7 +16,7 @@ limitations under the License. package v1alpha1 -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" +import clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint SA1019 // Conditions and condition Reasons for the KubevirtMachine object diff --git a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtcluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtcluster_types.go index c13a714dde2d..618b7b103df5 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtcluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtcluster_types.go @@ -19,7 +19,7 @@ package v1alpha1 import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint SA1019 ) const ( @@ -28,7 +28,7 @@ const ( ClusterFinalizer = "kubevirtcluster.infrastructure.cluster.x-k8s.io" ) -const ( //labels +const ( // labels KubevirtMachineNameLabel = "capk.cluster.x-k8s.io/kubevirt-machine-name" KubevirtMachineNamespaceLabel = "capk.cluster.x-k8s.io/kubevirt-machine-namespace" @@ -78,7 +78,7 @@ type KubevirtClusterStatus struct { // Conditions defines current service state of the KubevirtCluster. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions []clusterv1.Condition `json:"conditions,omitempty"` } // APIEndpoint represents a reachable Kubernetes API endpoint. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtclustertemplate_types.go b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtclustertemplate_types.go index bf0b9c70adbb..d66883d42417 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtclustertemplate_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtclustertemplate_types.go @@ -18,7 +18,7 @@ package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint SA1019 ) // KubevirtClusterTemplateResource describes the data needed to create a KubevirtCluster from a template. @@ -34,13 +34,13 @@ type KubevirtClusterTemplateSpec struct { // +kubebuilder:object:root=true // +kubebuilder:resource:path=kubevirtclustertemplates,scope=Namespaced,categories=cluster-api,shortName=kct -// +kubebuilder:validation:XValidation:rule="self == oldSelf", message="KubevirtClusterTemplate is immutable" // KubevirtClusterTemplate is the Schema for the kubevirtclustertemplates API. type KubevirtClusterTemplate struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` - Spec KubevirtClusterTemplateSpec `json:"spec,omitempty"` + // +kubebuilder:validation:XValidation:rule="self == oldSelf", message="KubevirtClusterTemplate Spec is immutable" + Spec KubevirtClusterTemplateSpec `json:"spec,omitempty"` } // +kubebuilder:object:root=true diff --git a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtmachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtmachine_types.go index 94e2bcf9257f..e419b429ab6d 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtmachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/kubevirtmachine_types.go @@ -20,8 +20,8 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kubevirtv1 "kubevirt.io/api/core/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" - "sigs.k8s.io/cluster-api/errors" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta1" //nolint SA1019 + "sigs.k8s.io/cluster-api/errors" //nolint SA1019 ) const ( diff --git a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/zz_generated.deepcopy.go index 930b4d4f1a99..8b8008ec2241 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-kubevirt/api/v1alpha1/zz_generated.deepcopy.go @@ -23,7 +23,7 @@ package v1alpha1 import ( "k8s.io/api/core/v1" runtime "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/cluster-api/api/v1beta1" + "sigs.k8s.io/cluster-api/api/core/v1beta1" "sigs.k8s.io/cluster-api/errors" ) @@ -153,7 +153,7 @@ func (in *KubevirtClusterStatus) DeepCopyInto(out *KubevirtClusterStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(v1beta1.Conditions, len(*in)) + *out = make([]v1beta1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/openstackfloatingippool_types.go b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/openstackfloatingippool_types.go index 30ee3bc20e59..4b7588fbd1b0 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/openstackfloatingippool_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/openstackfloatingippool_types.go @@ -20,7 +20,7 @@ import ( "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" infrav1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" ) @@ -88,7 +88,7 @@ type OpenStackFloatingIPPoolStatus struct { // +optional FloatingIPNetwork *infrav1.NetworkStatus `json:"floatingIPNetwork,omitempty"` - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } //+kubebuilder:object:root=true @@ -114,12 +114,12 @@ type OpenStackFloatingIPPoolList struct { } // GetConditions returns the observations of the operational state of the OpenStackFloatingIPPool resource. -func (r *OpenStackFloatingIPPool) GetConditions() clusterv1.Conditions { +func (r *OpenStackFloatingIPPool) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } // SetConditions sets the underlying service state of the OpenStackFloatingIPPool to the predescribed clusterv1.Conditions. -func (r *OpenStackFloatingIPPool) SetConditions(conditions clusterv1.Conditions) { +func (r *OpenStackFloatingIPPool) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/openstackserver_types.go b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/openstackserver_types.go index 1279e0751f3b..8172658dac74 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/openstackserver_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/openstackserver_types.go @@ -19,7 +19,9 @@ package v1alpha1 import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + runtime "k8s.io/apimachinery/pkg/runtime" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" infrav1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" "sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/optional" @@ -151,7 +153,7 @@ type OpenStackServerStatus struct { // Conditions defines current service state of the OpenStackServer. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +genclient @@ -183,12 +185,12 @@ type OpenStackServerList struct { } // GetConditions returns the observations of the operational state of the OpenStackServer resource. -func (r *OpenStackServer) GetConditions() clusterv1.Conditions { +func (r *OpenStackServer) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } // SetConditions sets the underlying service state of the OpenStackServer to the predescribed clusterv1.Conditions. -func (r *OpenStackServer) SetConditions(conditions clusterv1.Conditions) { +func (r *OpenStackServer) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } @@ -199,6 +201,16 @@ func (r *OpenStackServer) GetIdentityRef() (*string, *infrav1.OpenStackIdentityR return &r.Namespace, &r.Spec.IdentityRef } +func (r *OpenStackServer) ToUnstructured() (*unstructured.Unstructured, error) { + rawMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(r) + if err != nil { + return nil, err + } + u := &unstructured.Unstructured{Object: rawMap} + u.SetGroupVersionKind(infrav1.SchemeGroupVersion.WithKind("OpenStackServer")) + return u, nil +} + func init() { SchemeBuilder.Register(&OpenStackServer{}, &OpenStackServerList{}) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/zz_generated.deepcopy.go index edf6b1d97638..6a2484af9ece 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha1/zz_generated.deepcopy.go @@ -22,9 +22,9 @@ package v1alpha1 import ( "k8s.io/api/core/v1" - runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -142,7 +142,7 @@ func (in *OpenStackFloatingIPPoolStatus) DeepCopyInto(out *OpenStackFloatingIPPo } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -348,7 +348,7 @@ func (in *OpenStackServerStatus) DeepCopyInto(out *OpenStackServerStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/conditions_consts.go b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/conditions_consts.go index ec439ca5aef1..d84500772f12 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/conditions_consts.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/conditions_consts.go @@ -16,11 +16,11 @@ limitations under the License. package v1beta1 -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" +import clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" const ( // InstanceReadyCondition reports on current status of the OpenStack instance. Ready indicates the instance is in a Running state. - InstanceReadyCondition clusterv1.ConditionType = "InstanceReady" + InstanceReadyCondition clusterv1beta1.ConditionType = "InstanceReady" // WaitingForClusterInfrastructureReason used when machine is waiting for cluster infrastructure to be ready before proceeding. WaitingForClusterInfrastructureReason = "WaitingForClusterInfrastructure" @@ -44,11 +44,14 @@ const ( OpenStackErrorReason = "OpenStackError" // DependencyFailedReason indicates that a dependent object failed. DependencyFailedReason = "DependencyFailed" + + // ServerUnexpectedDeletedMessage is the message used when the server is unexpectedly deleted via an external agent. + ServerUnexpectedDeletedMessage = "The server was unexpectedly deleted" ) const ( // APIServerIngressReadyCondition reports on the current status of the network ingress (Loadbalancer, Floating IP) for Control Plane machines. Ready indicates that the instance can receive requests. - APIServerIngressReadyCondition clusterv1.ConditionType = "APIServerIngressReadyCondition" + APIServerIngressReadyCondition clusterv1beta1.ConditionType = "APIServerIngressReadyCondition" // LoadBalancerMemberErrorReason used when the instance could not be added as a loadbalancer member. LoadBalancerMemberErrorReason = "LoadBalancerMemberError" @@ -58,7 +61,7 @@ const ( const ( // FloatingAddressFromPoolReadyCondition reports on the current status of the Floating IPs from ipam pool. - FloatingAddressFromPoolReadyCondition clusterv1.ConditionType = "FloatingAddressFromPoolReady" + FloatingAddressFromPoolReadyCondition clusterv1beta1.ConditionType = "FloatingAddressFromPoolReady" // WaitingForIpamProviderReason used when machine is waiting for ipam provider to be ready before proceeding. FloatingAddressFromPoolWaitingForIpamProviderReason = "WaitingForIPAMProvider" // FloatingAddressFromPoolErrorReason is used when there is an error attaching an IP from the pool to an machine. diff --git a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/openstackcluster_types.go b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/openstackcluster_types.go index 840c816181b7..02833b1ea22d 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/openstackcluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/openstackcluster_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" capoerrors "sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/errors" "sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/optional" @@ -166,7 +166,7 @@ type OpenStackClusterSpec struct { // values set elsewhere. // ControlPlaneEndpoint cannot be modified after ControlPlaneEndpoint.Host has been set. // +optional - ControlPlaneEndpoint *clusterv1.APIEndpoint `json:"controlPlaneEndpoint,omitempty"` + ControlPlaneEndpoint *clusterv1beta1.APIEndpoint `json:"controlPlaneEndpoint,omitempty"` // ControlPlaneAvailabilityZones is the set of availability zones which // control plane machines may be deployed to. @@ -219,7 +219,7 @@ type OpenStackClusterStatus struct { APIServerLoadBalancer *LoadBalancer `json:"apiServerLoadBalancer,omitempty"` // FailureDomains represent OpenStack availability zones - FailureDomains clusterv1.FailureDomains `json:"failureDomains,omitempty"` + FailureDomains clusterv1beta1.FailureDomains `json:"failureDomains,omitempty"` // ControlPlaneSecurityGroup contains the information about the // OpenStack Security Group that needs to be applied to control plane diff --git a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/openstackmachine_types.go b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/openstackmachine_types.go index 7d271e78b596..8b52e62a49b3 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/openstackmachine_types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/openstackmachine_types.go @@ -20,7 +20,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" capoerrors "sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/errors" "sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/optional" @@ -234,7 +234,7 @@ type OpenStackMachineStatus struct { // +optional FailureMessage *string `json:"failureMessage,omitempty"` - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions clusterv1beta1.Conditions `json:"conditions,omitempty"` } // +genclient @@ -267,12 +267,12 @@ type OpenStackMachineList struct { } // GetConditions returns the observations of the operational state of the OpenStackMachine resource. -func (r *OpenStackMachine) GetConditions() clusterv1.Conditions { +func (r *OpenStackMachine) GetConditions() clusterv1beta1.Conditions { return r.Status.Conditions } // SetConditions sets the underlying service state of the OpenStackMachine to the predescribed clusterv1.Conditions. -func (r *OpenStackMachine) SetConditions(conditions clusterv1.Conditions) { +func (r *OpenStackMachine) SetConditions(conditions clusterv1beta1.Conditions) { r.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/types.go b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/types.go index 99bc29d906cd..5cb066219e7a 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/types.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/types.go @@ -723,12 +723,12 @@ type SecurityGroupRuleSpec struct { // security group rule is applied to incoming (ingress) traffic for that // instance. An egress rule is applied to traffic leaving the instance. // +kubebuilder:validation:Required - // +kubebuilder:validation:enum=ingress;egress + // +kubebuilder:validation:Enum=ingress;egress Direction string `json:"direction"` // etherType must be IPv4 or IPv6, and addresses represented in CIDR must match the // ingress or egress rules. - // +kubebuilder:validation:enum=IPv4;IPv6 + // +kubebuilder:validation:Enum=IPv4;IPv6 // +optional EtherType *string `json:"etherType,omitempty"` @@ -879,6 +879,39 @@ type APIServerLoadBalancer struct { // Flavor is the flavor name that will be used to create the APIServerLoadBalancer Spec. //+optional Flavor optional.String `json:"flavor,omitempty"` + + // Monitor contains configuration for the load balancer health monitor. + //+optional + Monitor *APIServerLoadBalancerMonitor `json:"monitor,omitempty"` +} + +// APIServerLoadBalancerMonitor contains configuration for the load balancer health monitor. +type APIServerLoadBalancerMonitor struct { + // Delay is the time in seconds between sending probes to members. + //+optional + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:default:10 + Delay int `json:"delay,omitempty"` + + // Timeout is the maximum time in seconds for a monitor to wait for a connection to be established before it times out. + //+optional + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:default:5 + Timeout int `json:"timeout,omitempty"` + + // MaxRetries is the number of successful checks before changing the operating status of the member to ONLINE. + //+optional + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Maximum=10 + //+kubebuilder:default:5 + MaxRetries int `json:"maxRetries,omitempty"` + + // MaxRetriesDown is the number of allowed check failures before changing the operating status of the member to ERROR. + //+optional + //+kubebuilder:validation:Minimum=1 + //+kubebuilder:validation:Maximum=10 + //+kubebuilder:default:3 + MaxRetriesDown int `json:"maxRetriesDown,omitempty"` } func (s *APIServerLoadBalancer) IsZero() bool { diff --git a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/zz_generated.deepcopy.go index d10b48a05af8..b93422b7a336 100644 --- a/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api-provider-openstack/api/v1beta1/zz_generated.deepcopy.go @@ -24,7 +24,7 @@ import ( "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/errors" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta1 "sigs.k8s.io/cluster-api/api/core/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -72,6 +72,11 @@ func (in *APIServerLoadBalancer) DeepCopyInto(out *APIServerLoadBalancer) { *out = new(string) **out = **in } + if in.Monitor != nil { + in, out := &in.Monitor, &out.Monitor + *out = new(APIServerLoadBalancerMonitor) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServerLoadBalancer. @@ -84,6 +89,21 @@ func (in *APIServerLoadBalancer) DeepCopy() *APIServerLoadBalancer { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIServerLoadBalancerMonitor) DeepCopyInto(out *APIServerLoadBalancerMonitor) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServerLoadBalancerMonitor. +func (in *APIServerLoadBalancerMonitor) DeepCopy() *APIServerLoadBalancerMonitor { + if in == nil { + return nil + } + out := new(APIServerLoadBalancerMonitor) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AdditionalBlockDevice) DeepCopyInto(out *AdditionalBlockDevice) { *out = *in @@ -711,7 +731,7 @@ func (in *OpenStackClusterSpec) DeepCopyInto(out *OpenStackClusterSpec) { } if in.ControlPlaneEndpoint != nil { in, out := &in.ControlPlaneEndpoint, &out.ControlPlaneEndpoint - *out = new(apiv1beta1.APIEndpoint) + *out = new(corev1beta1.APIEndpoint) **out = **in } if in.ControlPlaneAvailabilityZones != nil { @@ -767,7 +787,7 @@ func (in *OpenStackClusterStatus) DeepCopyInto(out *OpenStackClusterStatus) { } if in.FailureDomains != nil { in, out := &in.FailureDomains, &out.FailureDomains - *out = make(apiv1beta1.FailureDomains, len(*in)) + *out = make(corev1beta1.FailureDomains, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -1112,7 +1132,7 @@ func (in *OpenStackMachineStatus) DeepCopyInto(out *OpenStackMachineStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make(corev1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/.import-restrictions b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/.import-restrictions deleted file mode 100644 index a2e1dfd08133..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/.import-restrictions +++ /dev/null @@ -1,5 +0,0 @@ -rules: - - selectorRegexp: sigs[.]k8s[.]io/controller-runtime - allowedPrefixes: [] - forbiddenPrefixes: - - "sigs.k8s.io/controller-runtime" diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/condition_consts.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/condition_consts.go deleted file mode 100644 index 4d207306503a..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/condition_consts.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" - -// Conditions and condition Reasons for the ClusterResourceSet object. -const ( - // ResourcesAppliedCondition documents that all resources in the ClusterResourceSet object are applied to - // all matching clusters. This indicates all resources exist, and no errors during applying them to all clusters. - ResourcesAppliedCondition clusterv1.ConditionType = "ResourcesApplied" - - // RemoteClusterClientFailedReason (Severity=Error) documents failure during getting the remote cluster client. - RemoteClusterClientFailedReason = "RemoteClusterClientFailed" - - // ClusterMatchFailedReason (Severity=Warning) documents failure getting clusters that match the clusterSelector. - ClusterMatchFailedReason = "ClusterMatchFailed" - - // ApplyFailedReason (Severity=Warning) documents applying at least one of the resources to one of the matching clusters is failed. - ApplyFailedReason = "ApplyFailed" - - // RetrievingResourceFailedReason (Severity=Warning) documents at least one of the resources are not successfully retrieved. - RetrievingResourceFailedReason = "RetrievingResourceFailed" - - // WrongSecretTypeReason (Severity=Warning) documents at least one of the Secret's type in the resource list is not supported. - WrongSecretTypeReason = "WrongSecretType" -) diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/v1beta2_condition_consts.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/v1beta2_condition_consts.go deleted file mode 100644 index 7a0fddfece05..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/v1beta2_condition_consts.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" - -// Conditions that will be used for the ClusterResourceSet object in v1Beta2 API version. -const ( - // ClusterResourceSetResourceSetAppliedV1Beta2Condition documents that all resources in the ClusterResourceSet object - // are applied to all matching clusters. This indicates all resources exist, and no errors during applying them to all clusters. - ClusterResourceSetResourceSetAppliedV1Beta2Condition = "ResourceSetApplied" - - // ClusterResourceSetDeletingV1Beta2Condition surfaces details about ongoing deletion of the ClusterResourceSet. - ClusterResourceSetDeletingV1Beta2Condition = clusterv1.DeletingV1Beta2Condition -) diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/clusterresourceset_types.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/clusterresourceset_types.go similarity index 60% rename from vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/clusterresourceset_types.go rename to vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/clusterresourceset_types.go index d6b6d29f7d2b..e57c404acfe4 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/clusterresourceset_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/clusterresourceset_types.go @@ -1,5 +1,5 @@ /* -Copyright 2021 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,33 +14,33 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta1 +package v1beta2 import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) -// ClusterResourceSet's ResourcesApplied condition and corresponding reasons that will be used in v1Beta2 API version. +// ClusterResourceSet's ResourcesApplied condition and corresponding reasons. const ( - // ResourcesAppliedV1Beta2Condition surfaces wether the resources in the ClusterResourceSet are applied to all matching clusters. + // ClusterResourceSetResourcesAppliedCondition surfaces wether the resources in the ClusterResourceSet are applied to all matching clusters. // This indicates all resources exist, and no errors during applying them to all clusters. - ResourcesAppliedV1Beta2Condition = "ResourcesApplied" + ClusterResourceSetResourcesAppliedCondition = "ResourcesApplied" - // ResourcesAppliedV1beta2Reason is the reason used when all resources in the ClusterResourceSet object got applied + // ClusterResourceSetResourcesAppliedReason is the reason used when all resources in the ClusterResourceSet object got applied // to all matching clusters. - ResourcesAppliedV1beta2Reason = "Applied" + ClusterResourceSetResourcesAppliedReason = "Applied" - // ResourcesNotAppliedV1Beta2Reason is the reason used when applying at least one of the resources to one of the matching clusters failed. - ResourcesNotAppliedV1Beta2Reason = "NotApplied" + // ClusterResourceSetResourcesNotAppliedReason is the reason used when applying at least one of the resources to one of the matching clusters failed. + ClusterResourceSetResourcesNotAppliedReason = "NotApplied" - // ResourcesAppliedWrongSecretTypeV1Beta2Reason is the reason used when the Secret's type in the resource list is not supported. - ResourcesAppliedWrongSecretTypeV1Beta2Reason = "WrongSecretType" + // ClusterResourceSetResourcesAppliedWrongSecretTypeReason is the reason used when the Secret's type in the resource list is not supported. + ClusterResourceSetResourcesAppliedWrongSecretTypeReason = "WrongSecretType" - // ResourcesAppliedInternalErrorV1Beta2Reason surfaces unexpected failures when reconciling a ClusterResourceSet. - ResourcesAppliedInternalErrorV1Beta2Reason = clusterv1.InternalErrorV1Beta2Reason + // ClusterResourceSetResourcesAppliedInternalErrorReason surfaces unexpected failures when reconciling a ClusterResourceSet. + ClusterResourceSetResourcesAppliedInternalErrorReason = clusterv1.InternalErrorReason ) const ( @@ -51,8 +51,6 @@ const ( ClusterResourceSetFinalizer = "addons.cluster.x-k8s.io" ) -// ANCHOR: ClusterResourceSetSpec - // ClusterResourceSetSpec defines the desired state of ClusterResourceSet. type ClusterResourceSetSpec struct { // clusterSelector is the label selector for Clusters. The Clusters that are @@ -60,10 +58,12 @@ type ClusterResourceSetSpec struct { // It must match the Cluster labels. This field is immutable. // Label selector cannot be empty. // +required - ClusterSelector metav1.LabelSelector `json:"clusterSelector"` + ClusterSelector metav1.LabelSelector `json:"clusterSelector,omitempty,omitzero"` // resources is a list of Secrets/ConfigMaps where each contains 1 or more resources to be applied to remote clusters. - // +optional + // +required + // +listType=atomic + // +kubebuilder:validation:MinItems=1 // +kubebuilder:validation:MaxItems=100 Resources []ResourceRef `json:"resources,omitempty"` @@ -73,8 +73,6 @@ type ClusterResourceSetSpec struct { Strategy string `json:"strategy,omitempty"` } -// ANCHOR_END: ClusterResourceSetSpec - // ClusterResourceSetResourceKind is a string representation of a ClusterResourceSet resource kind. type ClusterResourceSetResourceKind string @@ -90,12 +88,12 @@ type ResourceRef struct { // +required // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=253 - Name string `json:"name"` + Name string `json:"name,omitempty"` // kind of the resource. Supported kinds are: Secrets and ConfigMaps. // +kubebuilder:validation:Enum=Secret;ConfigMap // +required - Kind string `json:"kind"` + Kind string `json:"kind,omitempty"` } // ClusterResourceSetStrategy is a string representation of a ClusterResourceSet Strategy. @@ -115,67 +113,81 @@ func (c *ClusterResourceSetSpec) SetTypedStrategy(p ClusterResourceSetStrategy) c.Strategy = string(p) } -// ANCHOR: ClusterResourceSetStatus - // ClusterResourceSetStatus defines the observed state of ClusterResourceSet. +// +kubebuilder:validation:MinProperties=1 type ClusterResourceSetStatus struct { + // conditions represents the observations of a ClusterResourceSet's current state. + // Known condition types are ResourcesApplied. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + // observedGeneration reflects the generation of the most recently observed ClusterResourceSet. // +optional + // +kubebuilder:validation:Minimum=1 ObservedGeneration int64 `json:"observedGeneration,omitempty"` - // conditions defines current state of the ClusterResourceSet. + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Deprecated *ClusterResourceSetDeprecatedStatus `json:"deprecated,omitempty"` +} - // v1beta2 groups all the fields that will be added or modified in ClusterResourceSet's status with the V1Beta2 version. +// ClusterResourceSetDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type ClusterResourceSetDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. // +optional - V1Beta2 *ClusterResourceSetV1Beta2Status `json:"v1beta2,omitempty"` + V1Beta1 *ClusterResourceSetV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` } -// ClusterResourceSetV1Beta2Status groups all the fields that will be added or modified in ClusterResourceSet with the V1Beta2 version. +// ClusterResourceSetV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. // See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. -type ClusterResourceSetV1Beta2Status struct { - // conditions represents the observations of a ClusterResourceSet's current state. - // Known condition types are ResourceSetApplied, Deleting. +type ClusterResourceSetV1Beta1DeprecatedStatus struct { + // conditions defines current state of the ClusterResourceSet. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // // +optional - // +listType=map - // +listMapKey=type - // +kubebuilder:validation:MaxItems=32 - Conditions []metav1.Condition `json:"conditions,omitempty"` + Conditions clusterv1.Conditions `json:"conditions,omitempty"` } -// ANCHOR_END: ClusterResourceSetStatus - -// GetConditions returns the set of conditions for this object. -func (m *ClusterResourceSet) GetConditions() clusterv1.Conditions { - return m.Status.Conditions +// GetV1Beta1Conditions returns the set of conditions for this object. +func (m *ClusterResourceSet) GetV1Beta1Conditions() clusterv1.Conditions { + if m.Status.Deprecated == nil || m.Status.Deprecated.V1Beta1 == nil { + return nil + } + return m.Status.Deprecated.V1Beta1.Conditions } -// SetConditions sets the conditions on this object. -func (m *ClusterResourceSet) SetConditions(conditions clusterv1.Conditions) { - m.Status.Conditions = conditions +// SetV1Beta1Conditions sets the conditions on this object. +func (m *ClusterResourceSet) SetV1Beta1Conditions(conditions clusterv1.Conditions) { + if m.Status.Deprecated == nil { + m.Status.Deprecated = &ClusterResourceSetDeprecatedStatus{} + } + if m.Status.Deprecated.V1Beta1 == nil { + m.Status.Deprecated.V1Beta1 = &ClusterResourceSetV1Beta1DeprecatedStatus{} + } + m.Status.Deprecated.V1Beta1.Conditions = conditions } -// GetV1Beta2Conditions returns the set of conditions for this object. -func (m *ClusterResourceSet) GetV1Beta2Conditions() []metav1.Condition { - if m.Status.V1Beta2 == nil { - return nil - } - return m.Status.V1Beta2.Conditions +// GetConditions returns the set of conditions for this object. +func (m *ClusterResourceSet) GetConditions() []metav1.Condition { + return m.Status.Conditions } -// SetV1Beta2Conditions sets conditions for an API object. -func (m *ClusterResourceSet) SetV1Beta2Conditions(conditions []metav1.Condition) { - if m.Status.V1Beta2 == nil { - m.Status.V1Beta2 = &ClusterResourceSetV1Beta2Status{} - } - m.Status.V1Beta2.Conditions = conditions +// SetConditions sets conditions for an API object. +func (m *ClusterResourceSet) SetConditions(conditions []metav1.Condition) { + m.Status.Conditions = conditions } // +kubebuilder:object:root=true // +kubebuilder:resource:path=clusterresourcesets,scope=Namespaced,categories=cluster-api // +kubebuilder:subresource:status // +kubebuilder:storageversion +// +kubebuilder:printcolumn:name="Applied",type="string",JSONPath=`.status.conditions[?(@.type=="ResourcesApplied")].status`,description="Resource applied" +// +kubebuilder:printcolumn:name="Paused",type="string",JSONPath=`.status.conditions[?(@.type=="Paused")].status`,description="Reconciliation paused",priority=10 // +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of ClusterResourceSet" // ClusterResourceSet is the Schema for the clusterresourcesets API. @@ -188,11 +200,11 @@ type ClusterResourceSet struct { metav1.ObjectMeta `json:"metadata,omitempty"` // spec is the desired state of ClusterResourceSet. - // +optional - Spec ClusterResourceSetSpec `json:"spec,omitempty"` + // +required + Spec ClusterResourceSetSpec `json:"spec,omitempty,omitzero"` // status is the observed state of ClusterResourceSet. // +optional - Status ClusterResourceSetStatus `json:"status,omitempty"` + Status ClusterResourceSetStatus `json:"status,omitempty,omitzero"` } // +kubebuilder:object:root=true diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/clusterresourcesetbinding_types.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/clusterresourcesetbinding_types.go similarity index 63% rename from vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/clusterresourcesetbinding_types.go rename to vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/clusterresourcesetbinding_types.go index 783b12da002c..ad2e50f7b6cb 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/clusterresourcesetbinding_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/clusterresourcesetbinding_types.go @@ -1,5 +1,5 @@ /* -Copyright 2021 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,17 +14,15 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta1 +package v1beta2 import ( "reflect" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/utils/ptr" ) -// ANCHOR: ResourceBinding - // ResourceBinding shows the status of a resource that belongs to a ClusterResourceSet matched by the owner cluster of the ClusterResourceSetBinding object. type ResourceBinding struct { // ResourceRef specifies a resource. @@ -39,25 +37,24 @@ type ResourceBinding struct { // lastAppliedTime identifies when this resource was last applied to the cluster. // +optional - LastAppliedTime *metav1.Time `json:"lastAppliedTime,omitempty"` + LastAppliedTime metav1.Time `json:"lastAppliedTime,omitempty,omitzero"` // applied is to track if a resource is applied to the cluster or not. // +required - Applied bool `json:"applied"` + Applied *bool `json:"applied,omitempty"` } -// ANCHOR_END: ResourceBinding - // ResourceSetBinding keeps info on all of the resources in a ClusterResourceSet. type ResourceSetBinding struct { // clusterResourceSetName is the name of the ClusterResourceSet that is applied to the owner cluster of the binding. // +required // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=253 - ClusterResourceSetName string `json:"clusterResourceSetName"` + ClusterResourceSetName string `json:"clusterResourceSetName,omitempty"` // resources is a list of resources that the ClusterResourceSet has. // +optional + // +listType=atomic // +kubebuilder:validation:MaxItems=100 Resources []ResourceBinding `json:"resources,omitempty"` } @@ -65,7 +62,7 @@ type ResourceSetBinding struct { // IsApplied returns true if the resource is applied to the cluster by checking the cluster's binding. func (r *ResourceSetBinding) IsApplied(resourceRef ResourceRef) bool { resourceBinding := r.GetResource(resourceRef) - return resourceBinding != nil && resourceBinding.Applied + return resourceBinding != nil && ptr.Deref(resourceBinding.Applied, false) } // GetResource returns a ResourceBinding for a resource ref if present. @@ -93,14 +90,14 @@ func (r *ResourceSetBinding) SetBinding(resourceBinding ResourceBinding) { // GetOrCreateBinding returns the ResourceSetBinding for a given ClusterResourceSet if exists, // otherwise creates one and updates ClusterResourceSet with it. func (c *ClusterResourceSetBinding) GetOrCreateBinding(clusterResourceSet *ClusterResourceSet) *ResourceSetBinding { - for _, binding := range c.Spec.Bindings { - if binding.ClusterResourceSetName == clusterResourceSet.Name { - return binding + for i := range c.Spec.Bindings { + if c.Spec.Bindings[i].ClusterResourceSetName == clusterResourceSet.Name { + return &c.Spec.Bindings[i] } } - binding := &ResourceSetBinding{ClusterResourceSetName: clusterResourceSet.Name, Resources: []ResourceBinding{}} + binding := ResourceSetBinding{ClusterResourceSetName: clusterResourceSet.Name, Resources: []ResourceBinding{}} c.Spec.Bindings = append(c.Spec.Bindings, binding) - return binding + return &c.Spec.Bindings[len(c.Spec.Bindings)-1] } // RemoveBinding removes the ClusterResourceSet from the ClusterResourceSetBinding Bindings list. @@ -114,68 +111,10 @@ func (c *ClusterResourceSetBinding) RemoveBinding(clusterResourceSet *ClusterRes } } -// DeleteBinding removes the ClusterResourceSet from the ClusterResourceSetBinding Bindings list. -// -// Deprecated: This function is deprecated and will be removed in an upcoming release of Cluster API. -func (c *ClusterResourceSetBinding) DeleteBinding(clusterResourceSet *ClusterResourceSet) { - for i, binding := range c.Spec.Bindings { - if binding.ClusterResourceSetName == clusterResourceSet.Name { - copy(c.Spec.Bindings[i:], c.Spec.Bindings[i+1:]) - c.Spec.Bindings = c.Spec.Bindings[:len(c.Spec.Bindings)-1] - break - } - } - c.OwnerReferences = removeOwnerRef(c.GetOwnerReferences(), metav1.OwnerReference{ - APIVersion: GroupVersion.String(), - Kind: "ClusterResourceSet", - Name: clusterResourceSet.Name, - }) -} - -// removeOwnerRef returns the slice of owner references after removing the supplied owner ref. -// Note: removeOwnerRef ignores apiVersion and UID. It will remove the passed ownerReference where it matches Name, Group and Kind. -// -// Deprecated: This function is deprecated and will be removed in an upcoming release of Cluster API. -func removeOwnerRef(ownerReferences []metav1.OwnerReference, inputRef metav1.OwnerReference) []metav1.OwnerReference { - if index := indexOwnerRef(ownerReferences, inputRef); index != -1 { - return append(ownerReferences[:index], ownerReferences[index+1:]...) - } - return ownerReferences -} - -// indexOwnerRef returns the index of the owner reference in the slice if found, or -1. -// -// Deprecated: This function is deprecated and will be removed in an upcoming release of Cluster API. -func indexOwnerRef(ownerReferences []metav1.OwnerReference, ref metav1.OwnerReference) int { - for index, r := range ownerReferences { - if referSameObject(r, ref) { - return index - } - } - return -1 -} - -// Returns true if a and b point to the same object based on Group, Kind and Name. -// -// Deprecated: This function is deprecated and will be removed in an upcoming release of Cluster API. -func referSameObject(a, b metav1.OwnerReference) bool { - aGV, err := schema.ParseGroupVersion(a.APIVersion) - if err != nil { - return false - } - - bGV, err := schema.ParseGroupVersion(b.APIVersion) - if err != nil { - return false - } - - return aGV.Group == bGV.Group && a.Kind == b.Kind && a.Name == b.Name -} - // +kubebuilder:object:root=true // +kubebuilder:resource:path=clusterresourcesetbindings,scope=Namespaced,categories=cluster-api -// +kubebuilder:subresource:status // +kubebuilder:storageversion +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" // +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of ClusterResourceSetBinding" // ClusterResourceSetBinding lists all matching ClusterResourceSets with the cluster it belongs to. @@ -186,29 +125,25 @@ type ClusterResourceSetBinding struct { // +optional metav1.ObjectMeta `json:"metadata,omitempty"` // spec is the desired state of ClusterResourceSetBinding. - // +optional - Spec ClusterResourceSetBindingSpec `json:"spec,omitempty"` + // +required + Spec ClusterResourceSetBindingSpec `json:"spec,omitempty,omitzero"` } -// ANCHOR: ClusterResourceSetBindingSpec - // ClusterResourceSetBindingSpec defines the desired state of ClusterResourceSetBinding. type ClusterResourceSetBindingSpec struct { // bindings is a list of ClusterResourceSets and their resources. // +optional + // +listType=atomic // +kubebuilder:validation:MaxItems=100 - Bindings []*ResourceSetBinding `json:"bindings,omitempty"` + Bindings []ResourceSetBinding `json:"bindings,omitempty"` // clusterName is the name of the Cluster this binding applies to. - // Note: this field mandatory in v1beta2. - // +optional + // +required // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=63 ClusterName string `json:"clusterName,omitempty"` } -// ANCHOR_END: ClusterResourceSetBindingSpec - // +kubebuilder:object:root=true // ClusterResourceSetBindingList contains a list of ClusterResourceSetBinding. diff --git a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/doc.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/conversion.go similarity index 78% rename from vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/doc.go rename to vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/conversion.go index b5028b59fed0..02f3b10a17b8 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/doc.go +++ b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2021 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1beta1 contains experimental v1beta1 API implementation. -package v1beta1 +package v1beta2 + +func (*ClusterResourceSet) Hub() {} +func (*ClusterResourceSetBinding) Hub() {} diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/doc.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/doc.go new file mode 100644 index 000000000000..9e6bb5e376fe --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package v1beta2 contains API Schema definitions for the addons v1beta2 API group. +// +kubebuilder:object:generate=true +// +groupName=addons.cluster.x-k8s.io +package v1beta2 diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/groupversion_info.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/groupversion_info.go similarity index 83% rename from vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/groupversion_info.go rename to vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/groupversion_info.go index f02006147e95..015aaebe0167 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/groupversion_info.go +++ b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/groupversion_info.go @@ -1,5 +1,5 @@ /* -Copyright 2021 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,10 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1beta1 contains API Schema definitions for the addons v1beta1 API group -// +kubebuilder:object:generate=true -// +groupName=addons.cluster.x-k8s.io -package v1beta1 +package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -27,7 +24,7 @@ import ( var ( // GroupVersion is group version used to register these objects. - GroupVersion = schema.GroupVersion{Group: "addons.cluster.x-k8s.io", Version: "v1beta1"} + GroupVersion = schema.GroupVersion{Group: "addons.cluster.x-k8s.io", Version: "v1beta2"} // schemeBuilder is used to add go types to the GroupVersionKind scheme. schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/v1beta1_condition_consts.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/v1beta1_condition_consts.go new file mode 100644 index 000000000000..efba2a7fdd41 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/v1beta1_condition_consts.go @@ -0,0 +1,41 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" + +// Conditions and condition Reasons for the ClusterResourceSet object. +const ( + // ResourcesAppliedV1Beta1Condition documents that all resources in the ClusterResourceSet object are applied to + // all matching clusters. This indicates all resources exist, and no errors during applying them to all clusters. + ResourcesAppliedV1Beta1Condition clusterv1.ConditionType = "ResourcesApplied" + + // RemoteClusterClientFailedV1Beta1Reason (Severity=Error) documents failure during getting the remote cluster client. + RemoteClusterClientFailedV1Beta1Reason = "RemoteClusterClientFailed" + + // ClusterMatchFailedV1Beta1Reason (Severity=Warning) documents failure getting clusters that match the clusterSelector. + ClusterMatchFailedV1Beta1Reason = "ClusterMatchFailed" + + // ApplyFailedV1Beta1Reason (Severity=Warning) documents applying at least one of the resources to one of the matching clusters is failed. + ApplyFailedV1Beta1Reason = "ApplyFailed" + + // RetrievingResourceFailedV1Beta1Reason (Severity=Warning) documents at least one of the resources are not successfully retrieved. + RetrievingResourceFailedV1Beta1Reason = "RetrievingResourceFailed" + + // WrongSecretTypeV1Beta1Reason (Severity=Warning) documents at least one of the Secret's type in the resource list is not supported. + WrongSecretTypeV1Beta1Reason = "WrongSecretType" +) diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/zz_generated.deepcopy.go similarity index 84% rename from vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/zz_generated.deepcopy.go rename to vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/zz_generated.deepcopy.go index f7afd3968ebc..734fe939ba78 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta2/zz_generated.deepcopy.go @@ -18,12 +18,12 @@ limitations under the License. // Code generated by controller-gen. DO NOT EDIT. -package v1beta1 +package v1beta2 import ( "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta2 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -116,13 +116,9 @@ func (in *ClusterResourceSetBindingSpec) DeepCopyInto(out *ClusterResourceSetBin *out = *in if in.Bindings != nil { in, out := &in.Bindings, &out.Bindings - *out = make([]*ResourceSetBinding, len(*in)) + *out = make([]ResourceSetBinding, len(*in)) for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(ResourceSetBinding) - (*in).DeepCopyInto(*out) - } + (*in)[i].DeepCopyInto(&(*out)[i]) } } } @@ -137,6 +133,26 @@ func (in *ClusterResourceSetBindingSpec) DeepCopy() *ClusterResourceSetBindingSp return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterResourceSetDeprecatedStatus) DeepCopyInto(out *ClusterResourceSetDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(ClusterResourceSetV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterResourceSetDeprecatedStatus. +func (in *ClusterResourceSetDeprecatedStatus) DeepCopy() *ClusterResourceSetDeprecatedStatus { + if in == nil { + return nil + } + out := new(ClusterResourceSetDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClusterResourceSetList) DeepCopyInto(out *ClusterResourceSetList) { *out = *in @@ -195,14 +211,14 @@ func (in *ClusterResourceSetStatus) DeepCopyInto(out *ClusterResourceSetStatus) *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make([]v1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } - if in.V1Beta2 != nil { - in, out := &in.V1Beta2, &out.V1Beta2 - *out = new(ClusterResourceSetV1Beta2Status) + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(ClusterResourceSetDeprecatedStatus) (*in).DeepCopyInto(*out) } } @@ -218,23 +234,23 @@ func (in *ClusterResourceSetStatus) DeepCopy() *ClusterResourceSetStatus { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterResourceSetV1Beta2Status) DeepCopyInto(out *ClusterResourceSetV1Beta2Status) { +func (in *ClusterResourceSetV1Beta1DeprecatedStatus) DeepCopyInto(out *ClusterResourceSetV1Beta1DeprecatedStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]v1.Condition, len(*in)) + *out = make(corev1beta2.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterResourceSetV1Beta2Status. -func (in *ClusterResourceSetV1Beta2Status) DeepCopy() *ClusterResourceSetV1Beta2Status { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterResourceSetV1Beta1DeprecatedStatus. +func (in *ClusterResourceSetV1Beta1DeprecatedStatus) DeepCopy() *ClusterResourceSetV1Beta1DeprecatedStatus { if in == nil { return nil } - out := new(ClusterResourceSetV1Beta2Status) + out := new(ClusterResourceSetV1Beta1DeprecatedStatus) in.DeepCopyInto(out) return out } @@ -243,9 +259,11 @@ func (in *ClusterResourceSetV1Beta2Status) DeepCopy() *ClusterResourceSetV1Beta2 func (in *ResourceBinding) DeepCopyInto(out *ResourceBinding) { *out = *in out.ResourceRef = in.ResourceRef - if in.LastAppliedTime != nil { - in, out := &in.LastAppliedTime, &out.LastAppliedTime - *out = (*in).DeepCopy() + in.LastAppliedTime.DeepCopyInto(&out.LastAppliedTime) + if in.Applied != nil { + in, out := &in.Applied, &out.Applied + *out = new(bool) + **out = **in } } diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/.import-restrictions b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/.import-restrictions new file mode 100644 index 000000000000..f6f10b3ff544 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/.import-restrictions @@ -0,0 +1,5 @@ +rules: + - selectorRegexp: sigs[.]k8s[.]io/controller-runtime + allowedPrefixes: + - "sigs.k8s.io/controller-runtime/pkg/conversion" + forbiddenPrefixes: [] diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/cluster_phase_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/cluster_phase_types.go similarity index 100% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/cluster_phase_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/cluster_phase_types.go diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/cluster_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/cluster_types.go similarity index 98% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/cluster_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/cluster_types.go index be27ac6d1300..c6ff0853b180 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/cluster_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/cluster_types.go @@ -458,8 +458,6 @@ const ( ClusterDeletingInternalErrorV1Beta2Reason = InternalErrorV1Beta2Reason ) -// ANCHOR: ClusterSpec - // ClusterSpec defines the desired state of Cluster. type ClusterSpec struct { // paused can be used to prevent controllers from processing the Cluster and all its associated objects. @@ -904,10 +902,6 @@ type MachinePoolVariables struct { Overrides []ClusterVariable `json:"overrides,omitempty"` } -// ANCHOR_END: ClusterSpec - -// ANCHOR: ClusterNetwork - // ClusterNetwork specifies the different networking // parameters for a cluster. type ClusterNetwork struct { @@ -931,10 +925,6 @@ type ClusterNetwork struct { ServiceDomain string `json:"serviceDomain,omitempty"` } -// ANCHOR_END: ClusterNetwork - -// ANCHOR: NetworkRanges - // NetworkRanges represents ranges of network addresses. type NetworkRanges struct { // cidrBlocks is a list of CIDR blocks. @@ -952,10 +942,6 @@ func (n NetworkRanges) String() string { return strings.Join(n.CIDRBlocks, ",") } -// ANCHOR_END: NetworkRanges - -// ANCHOR: ClusterStatus - // ClusterStatus defines the observed state of Cluster. type ClusterStatus struct { // failureDomains is a slice of failure domain objects synced from the infrastructure provider. @@ -966,7 +952,7 @@ type ClusterStatus struct { // state, and will be set to a token value suitable for // programmatic interpretation. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional FailureReason *capierrors.ClusterStatusError `json:"failureReason,omitempty"` @@ -974,7 +960,7 @@ type ClusterStatus struct { // failureMessage indicates that there is a fatal problem reconciling the // state, and will be set to a descriptive error message. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional // +kubebuilder:validation:MinLength=1 @@ -1081,8 +1067,6 @@ type WorkersStatus struct { AvailableReplicas *int32 `json:"availableReplicas,omitempty"` } -// ANCHOR_END: ClusterStatus - // SetTypedPhase sets the Phase field to the string representation of ClusterPhase. func (c *ClusterStatus) SetTypedPhase(p ClusterPhase) { c.Phase = string(p) @@ -1104,8 +1088,6 @@ func (c *ClusterStatus) GetTypedPhase() ClusterPhase { } } -// ANCHOR: APIEndpoint - // APIEndpoint represents a reachable Kubernetes API endpoint. type APIEndpoint struct { // host is the hostname on which the API server is serving. @@ -1134,11 +1116,9 @@ func (v APIEndpoint) String() string { return net.JoinHostPort(v.Host, fmt.Sprintf("%d", v.Port)) } -// ANCHOR_END: APIEndpoint - // +kubebuilder:object:root=true // +kubebuilder:resource:path=clusters,shortName=cl,scope=Namespaced,categories=cluster-api -// +kubebuilder:storageversion +// +kubebuilder:deprecatedversion // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="ClusterClass",type="string",JSONPath=".spec.topology.class",description="ClusterClass of this Cluster, empty if the Cluster is not using a ClusterClass" // +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase",description="Cluster status such as Pending/Provisioning/Provisioned/Deleting/Failed" diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/clusterclass_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/clusterclass_types.go similarity index 99% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/clusterclass_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/clusterclass_types.go index 4d62dbf7246b..058507504fe0 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/clusterclass_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/clusterclass_types.go @@ -66,7 +66,7 @@ const ( // +kubebuilder:object:root=true // +kubebuilder:resource:path=clusterclasses,shortName=cc,scope=Namespaced,categories=cluster-api -// +kubebuilder:storageversion +// +kubebuilder:deprecatedversion // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of ClusterClass" @@ -889,7 +889,7 @@ type ValidationRule struct { // +optional // +kubebuilder:validation:Enum=FieldValueInvalid;FieldValueForbidden;FieldValueRequired;FieldValueDuplicate // +kubebuilder:default=FieldValueInvalid - // +default=ref(sigs.k8s.io/cluster-api/api/v1beta1.FieldValueInvalid) + // +default=ref(sigs.k8s.io/cluster-api/api/core/v1beta1.FieldValueInvalid) Reason FieldValueErrorReason `json:"reason,omitempty"` // fieldPath represents the field path returned when the validation fails. // It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. @@ -1136,8 +1136,6 @@ type LocalObjectTemplate struct { Ref *corev1.ObjectReference `json:"ref"` } -// ANCHOR: ClusterClassStatus - // ClusterClassStatus defines the observed state of the ClusterClass. type ClusterClassStatus struct { // variables is a list of ClusterClassStatusVariable that are defined for the ClusterClass. @@ -1245,8 +1243,6 @@ func (c *ClusterClass) SetV1Beta2Conditions(conditions []metav1.Condition) { c.Status.V1Beta2.Conditions = conditions } -// ANCHOR_END: ClusterClassStatus - // +kubebuilder:object:root=true // ClusterClassList contains a list of Cluster. diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/common_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/common_types.go similarity index 100% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/common_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/common_types.go diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/condition_consts.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/condition_consts.go similarity index 97% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/condition_consts.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/condition_consts.go index b2797402e8e6..8e36313c79bb 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/condition_consts.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/condition_consts.go @@ -16,8 +16,6 @@ limitations under the License. package v1beta1 -// ANCHOR: CommonConditions - // Common ConditionTypes used by Cluster API objects. const ( // ReadyCondition defines the Ready condition type that summarizes the operational state of a Cluster API object. @@ -53,8 +51,6 @@ const ( WaitingForInfrastructureFallbackReason = "WaitingForInfrastructure" ) -// ANCHOR_END: CommonConditions - // Conditions and condition Reasons for the ClusterClass object. const ( // ClusterClassVariablesReconciledCondition reports if the ClusterClass variables, including both inline and external @@ -358,3 +354,14 @@ const ( // if the references are up-to-date. ClusterClassRefVersionsUpToDateInternalErrorReason = "InternalError" ) + +// Conditions and condition Reasons for the MachinePool object. + +const ( + // ReplicasReadyCondition reports an aggregate of current status of the replicas controlled by the MachinePool. + ReplicasReadyCondition ConditionType = "ReplicasReady" + + // WaitingForReplicasReadyReason (Severity=Info) documents a machinepool waiting for the required replicas + // to be ready. + WaitingForReplicasReadyReason = "WaitingForReplicasReady" +) diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/condition_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/condition_types.go similarity index 93% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/condition_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/condition_types.go index d9e0f44f2528..687a487fe7f5 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/condition_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/condition_types.go @@ -21,8 +21,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// ANCHOR: ConditionSeverity - // ConditionSeverity expresses the severity of a Condition Type failing. // +kubebuilder:validation:MaxLength=32 type ConditionSeverity string @@ -41,19 +39,11 @@ const ( ConditionSeverityNone ConditionSeverity = "" ) -// ANCHOR_END: ConditionSeverity - -// ANCHOR: ConditionType - // ConditionType is a valid value for Condition.Type. // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=256 type ConditionType string -// ANCHOR_END: ConditionType - -// ANCHOR: Condition - // Condition defines an observation of a Cluster API resource operational state. type Condition struct { // type of condition in CamelCase or in foo.example.com/CamelCase. @@ -94,11 +84,5 @@ type Condition struct { Message string `json:"message,omitempty"` } -// ANCHOR_END: Condition - -// ANCHOR: Conditions - // Conditions provide observations of the operational state of a Cluster API resource. type Conditions []Condition - -// ANCHOR_END: Conditions diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/conversion.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/conversion.go new file mode 100644 index 000000000000..03d7a7a9ad8e --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/conversion.go @@ -0,0 +1,2403 @@ +/* +Copyright 2021 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "errors" + "fmt" + "maps" + "reflect" + "slices" + "sort" + "unsafe" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + apimachineryconversion "k8s.io/apimachinery/pkg/conversion" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/conversion" + + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" + utilconversion "sigs.k8s.io/cluster-api/util/conversion" +) + +var apiVersionGetter = func(_ schema.GroupKind) (string, error) { + return "", errors.New("apiVersionGetter not set") +} + +func SetAPIVersionGetter(f func(gk schema.GroupKind) (string, error)) { + apiVersionGetter = f +} + +func (src *Cluster) ConvertTo(dstRaw conversion.Hub) error { + dst := dstRaw.(*clusterv1.Cluster) + + if err := Convert_v1beta1_Cluster_To_v1beta2_Cluster(src, dst, nil); err != nil { + return err + } + + if src.Spec.InfrastructureRef != nil { + infraRef, err := convertToContractVersionedObjectReference(src.Spec.InfrastructureRef) + if err != nil { + return err + } + dst.Spec.InfrastructureRef = infraRef + } + + if src.Spec.ControlPlaneRef != nil { + controlPlaneRef, err := convertToContractVersionedObjectReference(src.Spec.ControlPlaneRef) + if err != nil { + return err + } + dst.Spec.ControlPlaneRef = controlPlaneRef + } + + restored := &clusterv1.Cluster{} + ok, err := utilconversion.UnmarshalData(src, restored) + if err != nil { + return err + } + + // Recover intent for bool values converted to *bool. + clusterv1.Convert_bool_To_Pointer_bool(src.Spec.Paused, ok, restored.Spec.Paused, &dst.Spec.Paused) + + initialization := clusterv1.ClusterInitializationStatus{} + restoredControlPlaneInitialized := restored.Status.Initialization.ControlPlaneInitialized + restoredInfrastructureProvisioned := restored.Status.Initialization.InfrastructureProvisioned + clusterv1.Convert_bool_To_Pointer_bool(src.Status.ControlPlaneReady, ok, restoredControlPlaneInitialized, &initialization.ControlPlaneInitialized) + clusterv1.Convert_bool_To_Pointer_bool(src.Status.InfrastructureReady, ok, restoredInfrastructureProvisioned, &initialization.InfrastructureProvisioned) + if !reflect.DeepEqual(initialization, clusterv1.ClusterInitializationStatus{}) { + dst.Status.Initialization = initialization + } + return nil +} + +func (dst *Cluster) ConvertFrom(srcRaw conversion.Hub) error { + src := srcRaw.(*clusterv1.Cluster) + if err := Convert_v1beta2_Cluster_To_v1beta1_Cluster(src, dst, nil); err != nil { + return err + } + + if src.Spec.InfrastructureRef.IsDefined() { + infraRef, err := convertToObjectReference(src.Spec.InfrastructureRef, src.Namespace) + if err != nil { + return err + } + dst.Spec.InfrastructureRef = infraRef + } + + if src.Spec.ControlPlaneRef.IsDefined() { + controlPlaneRef, err := convertToObjectReference(src.Spec.ControlPlaneRef, src.Namespace) + if err != nil { + return err + } + dst.Spec.ControlPlaneRef = controlPlaneRef + } + + if dst.Spec.ClusterNetwork != nil && dst.Spec.ClusterNetwork.APIServerPort != nil && + *dst.Spec.ClusterNetwork.APIServerPort == 0 { + dst.Spec.ClusterNetwork.APIServerPort = nil + } + + if dst.Spec.Topology != nil { + if dst.Spec.Topology.ControlPlane.MachineHealthCheck != nil && dst.Spec.Topology.ControlPlane.MachineHealthCheck.RemediationTemplate != nil { + dst.Spec.Topology.ControlPlane.MachineHealthCheck.RemediationTemplate.Namespace = dst.Namespace + } + if dst.Spec.Topology.Workers != nil { + for _, md := range dst.Spec.Topology.Workers.MachineDeployments { + if md.MachineHealthCheck != nil && md.MachineHealthCheck.RemediationTemplate != nil { + md.MachineHealthCheck.RemediationTemplate.Namespace = dst.Namespace + } + } + } + } + + dropEmptyStringsCluster(dst) + + return utilconversion.MarshalData(src, dst) +} + +func (src *ClusterClass) ConvertTo(dstRaw conversion.Hub) error { + dst := dstRaw.(*clusterv1.ClusterClass) + + if err := Convert_v1beta1_ClusterClass_To_v1beta2_ClusterClass(src, dst, nil); err != nil { + return err + } + + restored := &clusterv1.ClusterClass{} + ok, err := utilconversion.UnmarshalData(src, restored) + if err != nil { + return err + } + + // Recover intent for bool values converted to *bool. + for i, patch := range dst.Spec.Patches { + for j, definition := range patch.Definitions { + var srcDefinition = &PatchDefinition{} + for _, p := range src.Spec.Patches { + if p.Name == patch.Name { + if len(p.Definitions) == len(patch.Definitions) { + srcDefinition = &p.Definitions[j] + } + break + } + } + if srcDefinition == nil { + return fmt.Errorf("definition %d for patch %s not found in source data", j, patch.Name) + } + var restoredPatchMatchControlPlane, restoredPatchMatchInfrastructureCluster *bool + for _, p := range restored.Spec.Patches { + if p.Name == patch.Name { + if len(p.Definitions) == len(patch.Definitions) { + restoredPatchMatchInfrastructureCluster = p.Definitions[j].Selector.MatchResources.InfrastructureCluster + restoredPatchMatchControlPlane = p.Definitions[j].Selector.MatchResources.ControlPlane + } + break + } + } + clusterv1.Convert_bool_To_Pointer_bool(srcDefinition.Selector.MatchResources.InfrastructureCluster, ok, restoredPatchMatchInfrastructureCluster, &definition.Selector.MatchResources.InfrastructureCluster) + clusterv1.Convert_bool_To_Pointer_bool(srcDefinition.Selector.MatchResources.ControlPlane, ok, restoredPatchMatchControlPlane, &definition.Selector.MatchResources.ControlPlane) + dst.Spec.Patches[i].Definitions[j] = definition + } + } + + for i, variable := range dst.Spec.Variables { + var srcVariable *ClusterClassVariable + for _, v := range src.Spec.Variables { + if v.Name == variable.Name { + srcVariable = &v + break + } + } + if srcVariable == nil { + return fmt.Errorf("variable %q not found in source data", variable.Name) + } + var restoredVariableOpenAPIV3Schema *clusterv1.JSONSchemaProps + for _, v := range restored.Spec.Variables { + if v.Name == variable.Name { + restoredVariableOpenAPIV3Schema = &v.Schema.OpenAPIV3Schema + break + } + } + if err := restoreBoolIntentJSONSchemaProps(&srcVariable.Schema.OpenAPIV3Schema, &variable.Schema.OpenAPIV3Schema, ok, restoredVariableOpenAPIV3Schema); err != nil { + return err + } + dst.Spec.Variables[i] = variable + } + + for i, variable := range dst.Status.Variables { + var srcVariable *ClusterClassStatusVariable + for _, v := range src.Status.Variables { + if v.Name == variable.Name { + srcVariable = &v + break + } + } + if srcVariable == nil { + return fmt.Errorf("variable %q not found in source data", variable.Name) + } + var restoredVariable *clusterv1.ClusterClassStatusVariable + var restoredVariableDefinitionsConflict *bool + for _, v := range restored.Status.Variables { + if v.Name == variable.Name { + restoredVariable = &v + restoredVariableDefinitionsConflict = v.DefinitionsConflict + break + } + } + clusterv1.Convert_bool_To_Pointer_bool(srcVariable.DefinitionsConflict, ok, restoredVariableDefinitionsConflict, &variable.DefinitionsConflict) + + for j, definition := range variable.Definitions { + var srcDefinition *ClusterClassStatusVariableDefinition + for _, d := range srcVariable.Definitions { + if d.From == definition.From { + srcDefinition = &d + } + } + if srcDefinition == nil { + return fmt.Errorf("definition %d for variable %s not found in source data", j, variable.Name) + } + var restoredVariableOpenAPIV3Schema *clusterv1.JSONSchemaProps + if restoredVariable != nil { + for _, d := range restoredVariable.Definitions { + if d.From == definition.From { + restoredVariableOpenAPIV3Schema = &d.Schema.OpenAPIV3Schema + } + } + } + if err := restoreBoolIntentJSONSchemaProps(&srcDefinition.Schema.OpenAPIV3Schema, &definition.Schema.OpenAPIV3Schema, ok, restoredVariableOpenAPIV3Schema); err != nil { + return err + } + variable.Definitions[j] = definition + } + dst.Status.Variables[i] = variable + } + + return nil +} + +func restoreBoolIntentJSONSchemaProps(src *JSONSchemaProps, dst *clusterv1.JSONSchemaProps, hasRestored bool, restored *clusterv1.JSONSchemaProps) error { + var restoredUniqueItems, restoreExclusiveMaximum, restoredExclusiveMinimum, restoreXPreserveUnknownFields, restoredXIntOrString *bool + if restored != nil { + restoredUniqueItems = restored.UniqueItems + restoreExclusiveMaximum = restored.ExclusiveMaximum + restoredExclusiveMinimum = restored.ExclusiveMinimum + restoreXPreserveUnknownFields = restored.XPreserveUnknownFields + restoredXIntOrString = restored.XIntOrString + } + clusterv1.Convert_bool_To_Pointer_bool(src.UniqueItems, hasRestored, restoredUniqueItems, &dst.UniqueItems) + clusterv1.Convert_bool_To_Pointer_bool(src.ExclusiveMaximum, hasRestored, restoreExclusiveMaximum, &dst.ExclusiveMaximum) + clusterv1.Convert_bool_To_Pointer_bool(src.ExclusiveMinimum, hasRestored, restoredExclusiveMinimum, &dst.ExclusiveMinimum) + clusterv1.Convert_bool_To_Pointer_bool(src.XPreserveUnknownFields, hasRestored, restoreXPreserveUnknownFields, &dst.XPreserveUnknownFields) + clusterv1.Convert_bool_To_Pointer_bool(src.XIntOrString, hasRestored, restoredXIntOrString, &dst.XIntOrString) + + for name, property := range dst.Properties { + srcProperty, ok := src.Properties[name] + if !ok { + return fmt.Errorf("property %s not found in source data", name) + } + var restoredPropertyOpenAPIV3Schema *clusterv1.JSONSchemaProps + if restored != nil { + if v, ok := restored.Properties[name]; ok { + restoredPropertyOpenAPIV3Schema = &v + } + } + if err := restoreBoolIntentJSONSchemaProps(&srcProperty, &property, hasRestored, restoredPropertyOpenAPIV3Schema); err != nil { + return err + } + dst.Properties[name] = property + } + if src.AdditionalProperties != nil { + var restoredAdditionalPropertiesOpenAPIV3Schema *clusterv1.JSONSchemaProps + if restored != nil { + restoredAdditionalPropertiesOpenAPIV3Schema = restored.AdditionalProperties + } + if err := restoreBoolIntentJSONSchemaProps(src.AdditionalProperties, dst.AdditionalProperties, hasRestored, restoredAdditionalPropertiesOpenAPIV3Schema); err != nil { + return err + } + } + if src.Items != nil { + var restoreItemsOpenAPIV3Schema *clusterv1.JSONSchemaProps + if restored != nil { + restoreItemsOpenAPIV3Schema = restored.Items + } + if err := restoreBoolIntentJSONSchemaProps(src.Items, dst.Items, hasRestored, restoreItemsOpenAPIV3Schema); err != nil { + return err + } + } + for i, value := range dst.AllOf { + srcValue := src.AllOf[i] + var restoredValueOpenAPIV3Schema *clusterv1.JSONSchemaProps + if restored != nil && len(src.AllOf) == len(dst.AllOf) { + restoredValueOpenAPIV3Schema = &restored.AllOf[i] + } + if err := restoreBoolIntentJSONSchemaProps(&srcValue, &value, hasRestored, restoredValueOpenAPIV3Schema); err != nil { + return err + } + dst.AllOf[i] = value + } + for i, value := range dst.OneOf { + srcValue := src.OneOf[i] + var restoredValueOpenAPIV3Schema *clusterv1.JSONSchemaProps + if restored != nil && len(src.OneOf) == len(dst.OneOf) { + restoredValueOpenAPIV3Schema = &restored.OneOf[i] + } + if err := restoreBoolIntentJSONSchemaProps(&srcValue, &value, hasRestored, restoredValueOpenAPIV3Schema); err != nil { + return err + } + dst.OneOf[i] = value + } + for i, value := range dst.AnyOf { + srcValue := src.AnyOf[i] + var restoredValueOpenAPIV3Schema *clusterv1.JSONSchemaProps + if restored != nil && len(src.AnyOf) == len(dst.AnyOf) { + restoredValueOpenAPIV3Schema = &restored.AnyOf[i] + } + if err := restoreBoolIntentJSONSchemaProps(&srcValue, &value, hasRestored, restoredValueOpenAPIV3Schema); err != nil { + return err + } + dst.AnyOf[i] = value + } + if src.Not != nil { + var restoredNotOpenAPIV3Schema *clusterv1.JSONSchemaProps + if restored != nil { + restoredNotOpenAPIV3Schema = restored.Not + } + if err := restoreBoolIntentJSONSchemaProps(src.Not, dst.Not, hasRestored, restoredNotOpenAPIV3Schema); err != nil { + return err + } + } + return nil +} + +func (dst *ClusterClass) ConvertFrom(srcRaw conversion.Hub) error { + src := srcRaw.(*clusterv1.ClusterClass) + if err := Convert_v1beta2_ClusterClass_To_v1beta1_ClusterClass(src, dst, nil); err != nil { + return err + } + + if dst.Spec.ControlPlane.MachineHealthCheck != nil && dst.Spec.ControlPlane.MachineHealthCheck.RemediationTemplate != nil { + dst.Spec.ControlPlane.MachineHealthCheck.RemediationTemplate.Namespace = dst.Namespace + } + for _, md := range dst.Spec.Workers.MachineDeployments { + if md.MachineHealthCheck != nil && md.MachineHealthCheck.RemediationTemplate != nil { + md.MachineHealthCheck.RemediationTemplate.Namespace = dst.Namespace + } + } + dropEmptyStringsClusterClass(dst) + + return utilconversion.MarshalData(src, dst) +} + +func (src *Machine) ConvertTo(dstRaw conversion.Hub) error { + dst := dstRaw.(*clusterv1.Machine) + + if err := Convert_v1beta1_Machine_To_v1beta2_Machine(src, dst, nil); err != nil { + return err + } + + if err := convertMachineSpecToContractVersionedObjectReference(&src.Spec, &dst.Spec); err != nil { + return err + } + + restored := &clusterv1.Machine{} + ok, err := utilconversion.UnmarshalData(src, restored) + if err != nil { + return err + } + + // Recover intent for bool values converted to *bool. + initialization := clusterv1.MachineInitializationStatus{} + restoredBootstrapDataSecretCreated := restored.Status.Initialization.BootstrapDataSecretCreated + restoredInfrastructureProvisioned := restored.Status.Initialization.InfrastructureProvisioned + clusterv1.Convert_bool_To_Pointer_bool(src.Status.BootstrapReady, ok, restoredBootstrapDataSecretCreated, &initialization.BootstrapDataSecretCreated) + clusterv1.Convert_bool_To_Pointer_bool(src.Status.InfrastructureReady, ok, restoredInfrastructureProvisioned, &initialization.InfrastructureProvisioned) + if !reflect.DeepEqual(initialization, clusterv1.MachineInitializationStatus{}) { + dst.Status.Initialization = initialization + } + + // Recover other values. + if ok { + dst.Spec.MinReadySeconds = restored.Spec.MinReadySeconds + } + + return nil +} + +func (dst *Machine) ConvertFrom(srcRaw conversion.Hub) error { + src := srcRaw.(*clusterv1.Machine) + + if err := Convert_v1beta2_Machine_To_v1beta1_Machine(src, dst, nil); err != nil { + return err + } + + if err := convertMachineSpecToObjectReference(&src.Spec, &dst.Spec, src.Namespace); err != nil { + return err + } + + dropEmptyStringsMachineSpec(&dst.Spec) + + return utilconversion.MarshalData(src, dst) +} + +func (src *MachineSet) ConvertTo(dstRaw conversion.Hub) error { + dst := dstRaw.(*clusterv1.MachineSet) + + if err := Convert_v1beta1_MachineSet_To_v1beta2_MachineSet(src, dst, nil); err != nil { + return err + } + + if err := convertMachineSpecToContractVersionedObjectReference(&src.Spec.Template.Spec, &dst.Spec.Template.Spec); err != nil { + return err + } + + if src.Spec.MinReadySeconds == 0 { + dst.Spec.Template.Spec.MinReadySeconds = nil + } else { + dst.Spec.Template.Spec.MinReadySeconds = &src.Spec.MinReadySeconds + } + + return nil +} + +func (dst *MachineSet) ConvertFrom(srcRaw conversion.Hub) error { + src := srcRaw.(*clusterv1.MachineSet) + + if err := Convert_v1beta2_MachineSet_To_v1beta1_MachineSet(src, dst, nil); err != nil { + return err + } + + if err := convertMachineSpecToObjectReference(&src.Spec.Template.Spec, &dst.Spec.Template.Spec, src.Namespace); err != nil { + return err + } + + dst.Spec.MinReadySeconds = ptr.Deref(src.Spec.Template.Spec.MinReadySeconds, 0) + + dropEmptyStringsMachineSpec(&dst.Spec.Template.Spec) + return nil +} + +func (src *MachineDeployment) ConvertTo(dstRaw conversion.Hub) error { + dst := dstRaw.(*clusterv1.MachineDeployment) + + if err := Convert_v1beta1_MachineDeployment_To_v1beta2_MachineDeployment(src, dst, nil); err != nil { + return err + } + + if err := convertMachineSpecToContractVersionedObjectReference(&src.Spec.Template.Spec, &dst.Spec.Template.Spec); err != nil { + return err + } + + dst.Spec.Template.Spec.MinReadySeconds = src.Spec.MinReadySeconds + + restored := &clusterv1.MachineDeployment{} + ok, err := utilconversion.UnmarshalData(src, restored) + if err != nil { + return err + } + + // Recover intent for bool values converted to *bool. + clusterv1.Convert_bool_To_Pointer_bool(src.Spec.Paused, ok, restored.Spec.Paused, &dst.Spec.Paused) + + return nil +} + +func (dst *MachineDeployment) ConvertFrom(srcRaw conversion.Hub) error { + src := srcRaw.(*clusterv1.MachineDeployment) + + if err := Convert_v1beta2_MachineDeployment_To_v1beta1_MachineDeployment(src, dst, nil); err != nil { + return err + } + + if err := convertMachineSpecToObjectReference(&src.Spec.Template.Spec, &dst.Spec.Template.Spec, src.Namespace); err != nil { + return err + } + + dst.Spec.MinReadySeconds = src.Spec.Template.Spec.MinReadySeconds + + dropEmptyStringsMachineSpec(&dst.Spec.Template.Spec) + + return utilconversion.MarshalData(src, dst) +} + +func (src *MachineHealthCheck) ConvertTo(dstRaw conversion.Hub) error { + dst := dstRaw.(*clusterv1.MachineHealthCheck) + + if err := Convert_v1beta1_MachineHealthCheck_To_v1beta2_MachineHealthCheck(src, dst, nil); err != nil { + return err + } + + // Manually restore data. + restored := &clusterv1.MachineHealthCheck{} + ok, err := utilconversion.UnmarshalData(src, restored) + if err != nil { + return err + } + + clusterv1.Convert_int32_To_Pointer_int32(src.Status.ExpectedMachines, ok, restored.Status.ExpectedMachines, &dst.Status.ExpectedMachines) + clusterv1.Convert_int32_To_Pointer_int32(src.Status.CurrentHealthy, ok, restored.Status.CurrentHealthy, &dst.Status.CurrentHealthy) + clusterv1.Convert_int32_To_Pointer_int32(src.Status.RemediationsAllowed, ok, restored.Status.RemediationsAllowed, &dst.Status.RemediationsAllowed) + + return nil +} + +func (dst *MachineHealthCheck) ConvertFrom(srcRaw conversion.Hub) error { + src := srcRaw.(*clusterv1.MachineHealthCheck) + if err := Convert_v1beta2_MachineHealthCheck_To_v1beta1_MachineHealthCheck(src, dst, nil); err != nil { + return err + } + + if dst.Spec.RemediationTemplate != nil { + dst.Spec.RemediationTemplate.Namespace = src.Namespace + } + + return utilconversion.MarshalData(src, dst) +} + +func (src *MachinePool) ConvertTo(dstRaw conversion.Hub) error { + dst := dstRaw.(*clusterv1.MachinePool) + + if err := Convert_v1beta1_MachinePool_To_v1beta2_MachinePool(src, dst, nil); err != nil { + return err + } + + if err := convertMachineSpecToContractVersionedObjectReference(&src.Spec.Template.Spec, &dst.Spec.Template.Spec); err != nil { + return err + } + + dst.Spec.Template.Spec.MinReadySeconds = src.Spec.MinReadySeconds + + restored := &clusterv1.MachinePool{} + ok, err := utilconversion.UnmarshalData(src, restored) + if err != nil { + return err + } + + // Recover intent for bool values converted to *bool. + initialization := clusterv1.MachinePoolInitializationStatus{} + restoredBootstrapDataSecretCreated := restored.Status.Initialization.BootstrapDataSecretCreated + restoredInfrastructureProvisioned := restored.Status.Initialization.InfrastructureProvisioned + clusterv1.Convert_bool_To_Pointer_bool(src.Status.BootstrapReady, ok, restoredBootstrapDataSecretCreated, &initialization.BootstrapDataSecretCreated) + clusterv1.Convert_bool_To_Pointer_bool(src.Status.InfrastructureReady, ok, restoredInfrastructureProvisioned, &initialization.InfrastructureProvisioned) + if !reflect.DeepEqual(initialization, clusterv1.MachinePoolInitializationStatus{}) { + dst.Status.Initialization = initialization + } + + return nil +} + +func (dst *MachinePool) ConvertFrom(srcRaw conversion.Hub) error { + src := srcRaw.(*clusterv1.MachinePool) + + if err := Convert_v1beta2_MachinePool_To_v1beta1_MachinePool(src, dst, nil); err != nil { + return err + } + + if err := convertMachineSpecToObjectReference(&src.Spec.Template.Spec, &dst.Spec.Template.Spec, src.Namespace); err != nil { + return err + } + + dst.Spec.MinReadySeconds = src.Spec.Template.Spec.MinReadySeconds + + dropEmptyStringsMachineSpec(&dst.Spec.Template.Spec) + + return utilconversion.MarshalData(src, dst) +} + +func (src *MachineDrainRule) ConvertTo(dstRaw conversion.Hub) error { + dst := dstRaw.(*clusterv1.MachineDrainRule) + return Convert_v1beta1_MachineDrainRule_To_v1beta2_MachineDrainRule(src, dst, nil) +} + +func (dst *MachineDrainRule) ConvertFrom(srcRaw conversion.Hub) error { + src := srcRaw.(*clusterv1.MachineDrainRule) + return Convert_v1beta2_MachineDrainRule_To_v1beta1_MachineDrainRule(src, dst, nil) +} + +func Convert_v1beta2_ClusterClass_To_v1beta1_ClusterClass(in *clusterv1.ClusterClass, out *ClusterClass, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ClusterClass_To_v1beta1_ClusterClass(in, out, s); err != nil { + return err + } + + if out.Spec.Infrastructure.Ref != nil { + out.Spec.Infrastructure.Ref.Namespace = in.Namespace + } + if out.Spec.ControlPlane.Ref != nil { + out.Spec.ControlPlane.Ref.Namespace = in.Namespace + } + if out.Spec.ControlPlane.MachineInfrastructure != nil && out.Spec.ControlPlane.MachineInfrastructure.Ref != nil { + out.Spec.ControlPlane.MachineInfrastructure.Ref.Namespace = in.Namespace + } + for _, md := range out.Spec.Workers.MachineDeployments { + if md.Template.Bootstrap.Ref != nil { + md.Template.Bootstrap.Ref.Namespace = in.Namespace + } + if md.Template.Infrastructure.Ref != nil { + md.Template.Infrastructure.Ref.Namespace = in.Namespace + } + } + for _, mp := range out.Spec.Workers.MachinePools { + if mp.Template.Bootstrap.Ref != nil { + mp.Template.Bootstrap.Ref.Namespace = in.Namespace + } + if mp.Template.Infrastructure.Ref != nil { + mp.Template.Infrastructure.Ref.Namespace = in.Namespace + } + } + return nil +} + +func Convert_v1beta2_ClusterClassSpec_To_v1beta1_ClusterClassSpec(in *clusterv1.ClusterClassSpec, out *ClusterClassSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ClusterClassSpec_To_v1beta1_ClusterClassSpec(in, out, s); err != nil { + return err + } + + if in.Infrastructure.Naming.Template != "" { + out.InfrastructureNamingStrategy = &InfrastructureNamingStrategy{ + Template: ptr.To(in.Infrastructure.Naming.Template), + } + } + + return nil +} + +func Convert_v1beta2_InfrastructureClass_To_v1beta1_LocalObjectTemplate(in *clusterv1.InfrastructureClass, out *LocalObjectTemplate, s apimachineryconversion.Scope) error { + if in == nil { + return nil + } + + Convert_v1beta2_ClusterClassTemplateReference_To_v1beta1_LocalObjectTemplate(&in.TemplateRef, out, s) + return nil +} + +func Convert_v1beta1_ClusterClassSpec_To_v1beta2_ClusterClassSpec(in *ClusterClassSpec, out *clusterv1.ClusterClassSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ClusterClassSpec_To_v1beta2_ClusterClassSpec(in, out, s); err != nil { + return err + } + + if in.InfrastructureNamingStrategy != nil { + out.Infrastructure.Naming = clusterv1.InfrastructureClassNamingSpec{ + Template: ptr.Deref(in.InfrastructureNamingStrategy.Template, ""), + } + } + return nil +} + +func Convert_v1beta1_LocalObjectTemplate_To_v1beta2_InfrastructureClass(in *LocalObjectTemplate, out *clusterv1.InfrastructureClass, s apimachineryconversion.Scope) error { + if in == nil { + return nil + } + + convert_v1beta1_LocalObjectTemplate_To_v1beta2_ClusterClassTemplateReference(in, &out.TemplateRef, s) + return nil +} + +func Convert_v1beta1_ControlPlaneClass_To_v1beta2_ControlPlaneClass(in *ControlPlaneClass, out *clusterv1.ControlPlaneClass, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ControlPlaneClass_To_v1beta2_ControlPlaneClass(in, out, s); err != nil { + return err + } + out.Deletion.NodeDrainTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDrainTimeout) + out.Deletion.NodeVolumeDetachTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeVolumeDetachTimeout) + out.Deletion.NodeDeletionTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDeletionTimeout) + convert_v1beta1_LocalObjectTemplate_To_v1beta2_ClusterClassTemplateReference(&in.LocalObjectTemplate, &out.TemplateRef, s) + + if in.MachineHealthCheck != nil { + for _, c := range in.MachineHealthCheck.UnhealthyConditions { + out.HealthCheck.Checks.UnhealthyNodeConditions = append(out.HealthCheck.Checks.UnhealthyNodeConditions, clusterv1.UnhealthyNodeCondition{ + Type: c.Type, + Status: c.Status, + TimeoutSeconds: clusterv1.ConvertToSeconds(&c.Timeout), + }) + } + out.HealthCheck.Checks.NodeStartupTimeoutSeconds = clusterv1.ConvertToSeconds(in.MachineHealthCheck.NodeStartupTimeout) + out.HealthCheck.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo = in.MachineHealthCheck.MaxUnhealthy + out.HealthCheck.Remediation.TriggerIf.UnhealthyInRange = ptr.Deref(in.MachineHealthCheck.UnhealthyRange, "") + if in.MachineHealthCheck.RemediationTemplate != nil { + if err := Convert_v1_ObjectReference_To_v1beta2_MachineHealthCheckRemediationTemplateReference(in.MachineHealthCheck.RemediationTemplate, &out.HealthCheck.Remediation.TemplateRef, s); err != nil { + return err + } + } + } + if in.NamingStrategy != nil { + out.Naming = clusterv1.ControlPlaneClassNamingSpec{ + Template: ptr.Deref(in.NamingStrategy.Template, ""), + } + } + if in.MachineInfrastructure != nil { + if err := Convert_v1beta1_LocalObjectTemplate_To_v1beta2_ControlPlaneClassMachineInfrastructureTemplate(in.MachineInfrastructure, &out.MachineInfrastructure, s); err != nil { + return err + } + } + return nil +} + +func Convert_v1beta2_ControlPlaneClass_To_v1beta1_ControlPlaneClass(in *clusterv1.ControlPlaneClass, out *ControlPlaneClass, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ControlPlaneClass_To_v1beta1_ControlPlaneClass(in, out, s); err != nil { + return err + } + out.NodeDrainTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDrainTimeoutSeconds) + out.NodeVolumeDetachTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeVolumeDetachTimeoutSeconds) + out.NodeDeletionTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDeletionTimeoutSeconds) + Convert_v1beta2_ClusterClassTemplateReference_To_v1beta1_LocalObjectTemplate(&in.TemplateRef, &out.LocalObjectTemplate, s) + + if !reflect.DeepEqual(in.HealthCheck, clusterv1.ControlPlaneClassHealthCheck{}) { + out.MachineHealthCheck = &MachineHealthCheckClass{} + for _, c := range in.HealthCheck.Checks.UnhealthyNodeConditions { + out.MachineHealthCheck.UnhealthyConditions = append(out.MachineHealthCheck.UnhealthyConditions, UnhealthyCondition{ + Type: c.Type, + Status: c.Status, + Timeout: ptr.Deref(clusterv1.ConvertFromSeconds(c.TimeoutSeconds), metav1.Duration{}), + }) + } + out.MachineHealthCheck.NodeStartupTimeout = clusterv1.ConvertFromSeconds(in.HealthCheck.Checks.NodeStartupTimeoutSeconds) + out.MachineHealthCheck.MaxUnhealthy = in.HealthCheck.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo + if in.HealthCheck.Remediation.TriggerIf.UnhealthyInRange != "" { + out.MachineHealthCheck.UnhealthyRange = ptr.To(in.HealthCheck.Remediation.TriggerIf.UnhealthyInRange) + } + if in.HealthCheck.Remediation.TemplateRef.IsDefined() { + out.MachineHealthCheck.RemediationTemplate = &corev1.ObjectReference{} + if err := Convert_v1beta2_MachineHealthCheckRemediationTemplateReference_To_v1_ObjectReference(&in.HealthCheck.Remediation.TemplateRef, out.MachineHealthCheck.RemediationTemplate, s); err != nil { + return err + } + } + } + if in.Naming.Template != "" { + out.NamingStrategy = &ControlPlaneClassNamingStrategy{ + Template: ptr.To(in.Naming.Template), + } + } + if in.MachineInfrastructure.TemplateRef.IsDefined() { + out.MachineInfrastructure = &LocalObjectTemplate{} + if err := Convert_v1beta2_ControlPlaneClassMachineInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(&in.MachineInfrastructure, out.MachineInfrastructure, s); err != nil { + return err + } + } + return nil +} + +func Convert_v1beta1_ControlPlaneTopology_To_v1beta2_ControlPlaneTopology(in *ControlPlaneTopology, out *clusterv1.ControlPlaneTopology, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ControlPlaneTopology_To_v1beta2_ControlPlaneTopology(in, out, s); err != nil { + return err + } + if in.Variables != nil { + if err := autoConvert_v1beta1_ControlPlaneVariables_To_v1beta2_ControlPlaneVariables(in.Variables, &out.Variables, s); err != nil { + return err + } + } + out.Deletion.NodeDrainTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDrainTimeout) + out.Deletion.NodeVolumeDetachTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeVolumeDetachTimeout) + out.Deletion.NodeDeletionTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDeletionTimeout) + + if in.MachineHealthCheck != nil { + out.HealthCheck.Enabled = in.MachineHealthCheck.Enable + for _, c := range in.MachineHealthCheck.UnhealthyConditions { + out.HealthCheck.Checks.UnhealthyNodeConditions = append(out.HealthCheck.Checks.UnhealthyNodeConditions, clusterv1.UnhealthyNodeCondition{ + Type: c.Type, + Status: c.Status, + TimeoutSeconds: clusterv1.ConvertToSeconds(&c.Timeout), + }) + } + out.HealthCheck.Checks.NodeStartupTimeoutSeconds = clusterv1.ConvertToSeconds(in.MachineHealthCheck.NodeStartupTimeout) + out.HealthCheck.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo = in.MachineHealthCheck.MaxUnhealthy + out.HealthCheck.Remediation.TriggerIf.UnhealthyInRange = ptr.Deref(in.MachineHealthCheck.UnhealthyRange, "") + if in.MachineHealthCheck.RemediationTemplate != nil { + if err := Convert_v1_ObjectReference_To_v1beta2_MachineHealthCheckRemediationTemplateReference(in.MachineHealthCheck.RemediationTemplate, &out.HealthCheck.Remediation.TemplateRef, s); err != nil { + return err + } + } + } + return nil +} + +func Convert_v1beta2_ControlPlaneTopology_To_v1beta1_ControlPlaneTopology(in *clusterv1.ControlPlaneTopology, out *ControlPlaneTopology, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ControlPlaneTopology_To_v1beta1_ControlPlaneTopology(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.Variables, clusterv1.ControlPlaneVariables{}) { + out.Variables = &ControlPlaneVariables{} + if err := autoConvert_v1beta2_ControlPlaneVariables_To_v1beta1_ControlPlaneVariables(&in.Variables, out.Variables, s); err != nil { + return err + } + } + out.NodeDrainTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDrainTimeoutSeconds) + out.NodeVolumeDetachTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeVolumeDetachTimeoutSeconds) + out.NodeDeletionTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDeletionTimeoutSeconds) + + if !reflect.DeepEqual(in.HealthCheck, clusterv1.ControlPlaneTopologyHealthCheck{}) { + out.MachineHealthCheck = &MachineHealthCheckTopology{} + out.MachineHealthCheck.Enable = in.HealthCheck.Enabled + for _, c := range in.HealthCheck.Checks.UnhealthyNodeConditions { + out.MachineHealthCheck.UnhealthyConditions = append(out.MachineHealthCheck.UnhealthyConditions, UnhealthyCondition{ + Type: c.Type, + Status: c.Status, + Timeout: ptr.Deref(clusterv1.ConvertFromSeconds(c.TimeoutSeconds), metav1.Duration{}), + }) + } + out.MachineHealthCheck.NodeStartupTimeout = clusterv1.ConvertFromSeconds(in.HealthCheck.Checks.NodeStartupTimeoutSeconds) + out.MachineHealthCheck.MaxUnhealthy = in.HealthCheck.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo + if in.HealthCheck.Remediation.TriggerIf.UnhealthyInRange != "" { + out.MachineHealthCheck.UnhealthyRange = ptr.To(in.HealthCheck.Remediation.TriggerIf.UnhealthyInRange) + } + if in.HealthCheck.Remediation.TemplateRef.IsDefined() { + out.MachineHealthCheck.RemediationTemplate = &corev1.ObjectReference{} + if err := Convert_v1beta2_MachineHealthCheckRemediationTemplateReference_To_v1_ObjectReference(&in.HealthCheck.Remediation.TemplateRef, out.MachineHealthCheck.RemediationTemplate, s); err != nil { + return err + } + } + } + return nil +} + +func Convert_v1beta1_MachineDeploymentClass_To_v1beta2_MachineDeploymentClass(in *MachineDeploymentClass, out *clusterv1.MachineDeploymentClass, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineDeploymentClass_To_v1beta2_MachineDeploymentClass(in, out, s); err != nil { + return err + } + if err := Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(&in.Template.Metadata, &out.Metadata, s); err != nil { + return err + } + if err := Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachineDeploymentClassBootstrapTemplate(&in.Template.Bootstrap, &out.Bootstrap, s); err != nil { + return err + } + if err := Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachineDeploymentClassInfrastructureTemplate(&in.Template.Infrastructure, &out.Infrastructure, s); err != nil { + return err + } + if in.Strategy != nil { + out.Rollout.Strategy.Type = clusterv1.MachineDeploymentRolloutStrategyType(in.Strategy.Type) + if in.Strategy.RollingUpdate != nil { + out.Rollout.Strategy.RollingUpdate.MaxUnavailable = in.Strategy.RollingUpdate.MaxUnavailable + out.Rollout.Strategy.RollingUpdate.MaxSurge = in.Strategy.RollingUpdate.MaxSurge + if in.Strategy.RollingUpdate.DeletePolicy != nil { + out.Deletion.Order = clusterv1.MachineSetDeletionOrder(*in.Strategy.RollingUpdate.DeletePolicy) + } + } + if in.Strategy.Remediation != nil && in.Strategy.Remediation.MaxInFlight != nil { + out.HealthCheck.Remediation.MaxInFlight = in.Strategy.Remediation.MaxInFlight + } + } + out.Deletion.NodeDrainTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDrainTimeout) + out.Deletion.NodeVolumeDetachTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeVolumeDetachTimeout) + out.Deletion.NodeDeletionTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDeletionTimeout) + + if in.MachineHealthCheck != nil { + for _, c := range in.MachineHealthCheck.UnhealthyConditions { + out.HealthCheck.Checks.UnhealthyNodeConditions = append(out.HealthCheck.Checks.UnhealthyNodeConditions, clusterv1.UnhealthyNodeCondition{ + Type: c.Type, + Status: c.Status, + TimeoutSeconds: clusterv1.ConvertToSeconds(&c.Timeout), + }) + } + out.HealthCheck.Checks.NodeStartupTimeoutSeconds = clusterv1.ConvertToSeconds(in.MachineHealthCheck.NodeStartupTimeout) + out.HealthCheck.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo = in.MachineHealthCheck.MaxUnhealthy + out.HealthCheck.Remediation.TriggerIf.UnhealthyInRange = ptr.Deref(in.MachineHealthCheck.UnhealthyRange, "") + if in.MachineHealthCheck.RemediationTemplate != nil { + if err := Convert_v1_ObjectReference_To_v1beta2_MachineHealthCheckRemediationTemplateReference(in.MachineHealthCheck.RemediationTemplate, &out.HealthCheck.Remediation.TemplateRef, s); err != nil { + return err + } + } + } + if in.NamingStrategy != nil { + out.Naming = clusterv1.MachineDeploymentClassNamingSpec{ + Template: ptr.Deref(in.NamingStrategy.Template, ""), + } + } + return nil +} + +func Convert_v1beta2_MachineDeploymentClass_To_v1beta1_MachineDeploymentClass(in *clusterv1.MachineDeploymentClass, out *MachineDeploymentClass, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineDeploymentClass_To_v1beta1_MachineDeploymentClass(in, out, s); err != nil { + return err + } + if err := Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(&in.Metadata, &out.Template.Metadata, s); err != nil { + return err + } + if err := Convert_v1beta2_MachineDeploymentClassBootstrapTemplate_To_v1beta1_LocalObjectTemplate(&in.Bootstrap, &out.Template.Bootstrap, s); err != nil { + return err + } + if err := Convert_v1beta2_MachineDeploymentClassInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(&in.Infrastructure, &out.Template.Infrastructure, s); err != nil { + return err + } + if !reflect.DeepEqual(in.Rollout.Strategy, clusterv1.MachineDeploymentClassRolloutStrategy{}) { + out.Strategy = &MachineDeploymentStrategy{} + out.Strategy.Type = MachineDeploymentStrategyType(in.Rollout.Strategy.Type) + if !reflect.DeepEqual(in.Rollout.Strategy.RollingUpdate, clusterv1.MachineDeploymentClassRolloutStrategyRollingUpdate{}) { + out.Strategy.RollingUpdate = &MachineRollingUpdateDeployment{} + out.Strategy.RollingUpdate.MaxUnavailable = in.Rollout.Strategy.RollingUpdate.MaxUnavailable + out.Strategy.RollingUpdate.MaxSurge = in.Rollout.Strategy.RollingUpdate.MaxSurge + } + } + if in.Deletion.Order != "" { + if out.Strategy == nil { + out.Strategy = &MachineDeploymentStrategy{} + } + if out.Strategy.RollingUpdate == nil { + out.Strategy.RollingUpdate = &MachineRollingUpdateDeployment{} + } + out.Strategy.RollingUpdate.DeletePolicy = ptr.To(string(in.Deletion.Order)) + } + if in.HealthCheck.Remediation.MaxInFlight != nil { + if out.Strategy == nil { + out.Strategy = &MachineDeploymentStrategy{} + } + if out.Strategy.Remediation == nil { + out.Strategy.Remediation = &RemediationStrategy{} + } + out.Strategy.Remediation.MaxInFlight = in.HealthCheck.Remediation.MaxInFlight + } + out.NodeDrainTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDrainTimeoutSeconds) + out.NodeVolumeDetachTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeVolumeDetachTimeoutSeconds) + out.NodeDeletionTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDeletionTimeoutSeconds) + + // Check if HealthCheck is not nil and another field apart from MaxInFlight is set (MaxInFlight is set in Strategy above). + if !reflect.DeepEqual(in.HealthCheck, clusterv1.MachineDeploymentClassHealthCheck{ + Remediation: clusterv1.MachineDeploymentClassHealthCheckRemediation{MaxInFlight: in.HealthCheck.Remediation.MaxInFlight}, + }) { + out.MachineHealthCheck = &MachineHealthCheckClass{} + for _, c := range in.HealthCheck.Checks.UnhealthyNodeConditions { + out.MachineHealthCheck.UnhealthyConditions = append(out.MachineHealthCheck.UnhealthyConditions, UnhealthyCondition{ + Type: c.Type, + Status: c.Status, + Timeout: ptr.Deref(clusterv1.ConvertFromSeconds(c.TimeoutSeconds), metav1.Duration{}), + }) + } + out.MachineHealthCheck.NodeStartupTimeout = clusterv1.ConvertFromSeconds(in.HealthCheck.Checks.NodeStartupTimeoutSeconds) + out.MachineHealthCheck.MaxUnhealthy = in.HealthCheck.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo + if in.HealthCheck.Remediation.TriggerIf.UnhealthyInRange != "" { + out.MachineHealthCheck.UnhealthyRange = ptr.To(in.HealthCheck.Remediation.TriggerIf.UnhealthyInRange) + } + if in.HealthCheck.Remediation.TemplateRef.IsDefined() { + out.MachineHealthCheck.RemediationTemplate = &corev1.ObjectReference{} + if err := Convert_v1beta2_MachineHealthCheckRemediationTemplateReference_To_v1_ObjectReference(&in.HealthCheck.Remediation.TemplateRef, out.MachineHealthCheck.RemediationTemplate, s); err != nil { + return err + } + } + } + if in.Naming.Template != "" { + out.NamingStrategy = &MachineDeploymentClassNamingStrategy{ + Template: ptr.To(in.Naming.Template), + } + } + return nil +} + +func Convert_v1beta1_MachineDeploymentTopology_To_v1beta2_MachineDeploymentTopology(in *MachineDeploymentTopology, out *clusterv1.MachineDeploymentTopology, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineDeploymentTopology_To_v1beta2_MachineDeploymentTopology(in, out, s); err != nil { + return err + } + if in.Variables != nil { + if err := autoConvert_v1beta1_MachineDeploymentVariables_To_v1beta2_MachineDeploymentVariables(in.Variables, &out.Variables, s); err != nil { + return err + } + } + if in.Strategy != nil { + out.Rollout.Strategy.Type = clusterv1.MachineDeploymentRolloutStrategyType(in.Strategy.Type) + if in.Strategy.RollingUpdate != nil { + out.Rollout.Strategy.RollingUpdate.MaxUnavailable = in.Strategy.RollingUpdate.MaxUnavailable + out.Rollout.Strategy.RollingUpdate.MaxSurge = in.Strategy.RollingUpdate.MaxSurge + if in.Strategy.RollingUpdate.DeletePolicy != nil { + out.Deletion.Order = clusterv1.MachineSetDeletionOrder(*in.Strategy.RollingUpdate.DeletePolicy) + } + } + if in.Strategy.Remediation != nil && in.Strategy.Remediation.MaxInFlight != nil { + out.HealthCheck.Remediation.MaxInFlight = in.Strategy.Remediation.MaxInFlight + } + } + out.Deletion.NodeDrainTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDrainTimeout) + out.Deletion.NodeVolumeDetachTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeVolumeDetachTimeout) + out.Deletion.NodeDeletionTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDeletionTimeout) + + if in.MachineHealthCheck != nil { + out.HealthCheck.Enabled = in.MachineHealthCheck.Enable + for _, c := range in.MachineHealthCheck.UnhealthyConditions { + out.HealthCheck.Checks.UnhealthyNodeConditions = append(out.HealthCheck.Checks.UnhealthyNodeConditions, clusterv1.UnhealthyNodeCondition{ + Type: c.Type, + Status: c.Status, + TimeoutSeconds: clusterv1.ConvertToSeconds(&c.Timeout), + }) + } + out.HealthCheck.Checks.NodeStartupTimeoutSeconds = clusterv1.ConvertToSeconds(in.MachineHealthCheck.NodeStartupTimeout) + out.HealthCheck.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo = in.MachineHealthCheck.MaxUnhealthy + out.HealthCheck.Remediation.TriggerIf.UnhealthyInRange = ptr.Deref(in.MachineHealthCheck.UnhealthyRange, "") + if in.MachineHealthCheck.RemediationTemplate != nil { + if err := Convert_v1_ObjectReference_To_v1beta2_MachineHealthCheckRemediationTemplateReference(in.MachineHealthCheck.RemediationTemplate, &out.HealthCheck.Remediation.TemplateRef, s); err != nil { + return err + } + } + } + return nil +} + +func Convert_v1beta2_MachineDeploymentTopology_To_v1beta1_MachineDeploymentTopology(in *clusterv1.MachineDeploymentTopology, out *MachineDeploymentTopology, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineDeploymentTopology_To_v1beta1_MachineDeploymentTopology(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.Variables, clusterv1.MachineDeploymentVariables{}) { + out.Variables = &MachineDeploymentVariables{} + if err := autoConvert_v1beta2_MachineDeploymentVariables_To_v1beta1_MachineDeploymentVariables(&in.Variables, out.Variables, s); err != nil { + return err + } + } + if !reflect.DeepEqual(in.Rollout.Strategy, clusterv1.MachineDeploymentTopologyRolloutStrategy{}) { + out.Strategy = &MachineDeploymentStrategy{} + out.Strategy.Type = MachineDeploymentStrategyType(in.Rollout.Strategy.Type) + if !reflect.DeepEqual(in.Rollout.Strategy.RollingUpdate, clusterv1.MachineDeploymentTopologyRolloutStrategyRollingUpdate{}) { + out.Strategy.RollingUpdate = &MachineRollingUpdateDeployment{} + out.Strategy.RollingUpdate.MaxUnavailable = in.Rollout.Strategy.RollingUpdate.MaxUnavailable + out.Strategy.RollingUpdate.MaxSurge = in.Rollout.Strategy.RollingUpdate.MaxSurge + } + } + if in.Deletion.Order != "" { + if out.Strategy == nil { + out.Strategy = &MachineDeploymentStrategy{} + } + if out.Strategy.RollingUpdate == nil { + out.Strategy.RollingUpdate = &MachineRollingUpdateDeployment{} + } + out.Strategy.RollingUpdate.DeletePolicy = ptr.To(string(in.Deletion.Order)) + } + if in.HealthCheck.Remediation.MaxInFlight != nil { + if out.Strategy == nil { + out.Strategy = &MachineDeploymentStrategy{} + } + if out.Strategy.Remediation == nil { + out.Strategy.Remediation = &RemediationStrategy{} + } + out.Strategy.Remediation.MaxInFlight = in.HealthCheck.Remediation.MaxInFlight + } + out.NodeDrainTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDrainTimeoutSeconds) + out.NodeVolumeDetachTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeVolumeDetachTimeoutSeconds) + out.NodeDeletionTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDeletionTimeoutSeconds) + + // Check if HealthCheck is not nil and another field apart from MaxInFlight is set (MaxInFlight is set in Strategy above). + if !reflect.DeepEqual(in.HealthCheck, clusterv1.MachineDeploymentTopologyHealthCheck{ + Remediation: clusterv1.MachineDeploymentTopologyHealthCheckRemediation{MaxInFlight: in.HealthCheck.Remediation.MaxInFlight}, + }) { + out.MachineHealthCheck = &MachineHealthCheckTopology{} + out.MachineHealthCheck.Enable = in.HealthCheck.Enabled + for _, c := range in.HealthCheck.Checks.UnhealthyNodeConditions { + out.MachineHealthCheck.UnhealthyConditions = append(out.MachineHealthCheck.UnhealthyConditions, UnhealthyCondition{ + Type: c.Type, + Status: c.Status, + Timeout: ptr.Deref(clusterv1.ConvertFromSeconds(c.TimeoutSeconds), metav1.Duration{}), + }) + } + out.MachineHealthCheck.NodeStartupTimeout = clusterv1.ConvertFromSeconds(in.HealthCheck.Checks.NodeStartupTimeoutSeconds) + out.MachineHealthCheck.MaxUnhealthy = in.HealthCheck.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo + if in.HealthCheck.Remediation.TriggerIf.UnhealthyInRange != "" { + out.MachineHealthCheck.UnhealthyRange = ptr.To(in.HealthCheck.Remediation.TriggerIf.UnhealthyInRange) + } + if in.HealthCheck.Remediation.TemplateRef.IsDefined() { + out.MachineHealthCheck.RemediationTemplate = &corev1.ObjectReference{} + if err := Convert_v1beta2_MachineHealthCheckRemediationTemplateReference_To_v1_ObjectReference(&in.HealthCheck.Remediation.TemplateRef, out.MachineHealthCheck.RemediationTemplate, s); err != nil { + return err + } + } + } + return nil +} + +func Convert_v1beta1_MachinePoolClass_To_v1beta2_MachinePoolClass(in *MachinePoolClass, out *clusterv1.MachinePoolClass, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachinePoolClass_To_v1beta2_MachinePoolClass(in, out, s); err != nil { + return err + } + if err := Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(&in.Template.Metadata, &out.Metadata, s); err != nil { + return err + } + if err := Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachinePoolClassBootstrapTemplate(&in.Template.Bootstrap, &out.Bootstrap, s); err != nil { + return err + } + if err := Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachinePoolClassInfrastructureTemplate(&in.Template.Infrastructure, &out.Infrastructure, s); err != nil { + return err + } + out.Deletion.NodeDrainTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDrainTimeout) + out.Deletion.NodeVolumeDetachTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeVolumeDetachTimeout) + out.Deletion.NodeDeletionTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDeletionTimeout) + if in.NamingStrategy != nil { + out.Naming = clusterv1.MachinePoolClassNamingSpec{ + Template: ptr.Deref(in.NamingStrategy.Template, ""), + } + } + return nil +} + +func Convert_v1beta2_MachinePoolClass_To_v1beta1_MachinePoolClass(in *clusterv1.MachinePoolClass, out *MachinePoolClass, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachinePoolClass_To_v1beta1_MachinePoolClass(in, out, s); err != nil { + return err + } + if err := Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(&in.Metadata, &out.Template.Metadata, s); err != nil { + return err + } + if err := Convert_v1beta2_MachinePoolClassBootstrapTemplate_To_v1beta1_LocalObjectTemplate(&in.Bootstrap, &out.Template.Bootstrap, s); err != nil { + return err + } + if err := Convert_v1beta2_MachinePoolClassInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(&in.Infrastructure, &out.Template.Infrastructure, s); err != nil { + return err + } + out.NodeDrainTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDrainTimeoutSeconds) + out.NodeVolumeDetachTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeVolumeDetachTimeoutSeconds) + out.NodeDeletionTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDeletionTimeoutSeconds) + if in.Naming.Template != "" { + out.NamingStrategy = &MachinePoolClassNamingStrategy{ + Template: ptr.To(in.Naming.Template), + } + } + return nil +} + +func Convert_v1beta1_MachinePoolTopology_To_v1beta2_MachinePoolTopology(in *MachinePoolTopology, out *clusterv1.MachinePoolTopology, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachinePoolTopology_To_v1beta2_MachinePoolTopology(in, out, s); err != nil { + return err + } + if in.Variables != nil { + if err := autoConvert_v1beta1_MachinePoolVariables_To_v1beta2_MachinePoolVariables(in.Variables, &out.Variables, s); err != nil { + return err + } + } + out.Deletion.NodeDrainTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDrainTimeout) + out.Deletion.NodeVolumeDetachTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeVolumeDetachTimeout) + out.Deletion.NodeDeletionTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDeletionTimeout) + return nil +} + +func Convert_v1beta2_MachinePoolTopology_To_v1beta1_MachinePoolTopology(in *clusterv1.MachinePoolTopology, out *MachinePoolTopology, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachinePoolTopology_To_v1beta1_MachinePoolTopology(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.Variables, clusterv1.MachinePoolVariables{}) { + out.Variables = &MachinePoolVariables{} + if err := autoConvert_v1beta2_MachinePoolVariables_To_v1beta1_MachinePoolVariables(&in.Variables, out.Variables, s); err != nil { + return err + } + } + out.NodeDrainTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDrainTimeoutSeconds) + out.NodeVolumeDetachTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeVolumeDetachTimeoutSeconds) + out.NodeDeletionTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDeletionTimeoutSeconds) + return nil +} + +func Convert_v1beta1_MachineSpec_To_v1beta2_MachineSpec(in *MachineSpec, out *clusterv1.MachineSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineSpec_To_v1beta2_MachineSpec(in, out, s); err != nil { + return err + } + out.Deletion.NodeDrainTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDrainTimeout) + out.Deletion.NodeVolumeDetachTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeVolumeDetachTimeout) + out.Deletion.NodeDeletionTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeDeletionTimeout) + return nil +} + +func Convert_v1beta2_ClusterClassStatus_To_v1beta1_ClusterClassStatus(in *clusterv1.ClusterClassStatus, out *ClusterClassStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ClusterClassStatus_To_v1beta1_ClusterClassStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta2 conditions should not be automatically be converted into legacy conditions (v1beta1). + out.Conditions = nil + + // Retrieve legacy conditions (v1beta1) from the deprecated field. + if in.Deprecated != nil && in.Deprecated.V1Beta1 != nil { + if in.Deprecated.V1Beta1.Conditions != nil { + Convert_v1beta2_Deprecated_V1Beta1_Conditions_To_v1beta1_Conditions(&in.Deprecated.V1Beta1.Conditions, &out.Conditions) + } + } + + // Move new conditions (v1beta2) to the v1beta2 field. + if in.Conditions == nil { + return nil + } + out.V1Beta2 = &ClusterClassV1Beta2Status{} + out.V1Beta2.Conditions = in.Conditions + return nil +} + +func Convert_v1beta1_ClusterClassStatus_To_v1beta2_ClusterClassStatus(in *ClusterClassStatus, out *clusterv1.ClusterClassStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ClusterClassStatus_To_v1beta2_ClusterClassStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta1 conditions should not be automatically be converted into v1beta2 conditions. + out.Conditions = nil + + // Retrieve new conditions (v1beta2) from the v1beta2 field. + if in.V1Beta2 != nil { + out.Conditions = in.V1Beta2.Conditions + } + + // Move legacy conditions (v1beta1) to the deprecated field. + if in.Conditions == nil { + return nil + } + + if out.Deprecated == nil { + out.Deprecated = &clusterv1.ClusterClassDeprecatedStatus{} + } + if out.Deprecated.V1Beta1 == nil { + out.Deprecated.V1Beta1 = &clusterv1.ClusterClassV1Beta1DeprecatedStatus{} + } + if in.Conditions != nil { + Convert_v1beta1_Conditions_To_v1beta2_Deprecated_V1Beta1_Conditions(&in.Conditions, &out.Deprecated.V1Beta1.Conditions) + } + return nil +} + +func Convert_v1beta2_ClusterStatus_To_v1beta1_ClusterStatus(in *clusterv1.ClusterStatus, out *ClusterStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ClusterStatus_To_v1beta1_ClusterStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta2 conditions should not be automatically be converted into legacy conditions (v1beta1). + out.Conditions = nil + + // Retrieve legacy conditions (v1beta1) from the deprecated field. + if in.Deprecated != nil && in.Deprecated.V1Beta1 != nil { + if in.Deprecated.V1Beta1.Conditions != nil { + Convert_v1beta2_Deprecated_V1Beta1_Conditions_To_v1beta1_Conditions(&in.Deprecated.V1Beta1.Conditions, &out.Conditions) + } + out.FailureReason = in.Deprecated.V1Beta1.FailureReason + out.FailureMessage = in.Deprecated.V1Beta1.FailureMessage + } + + // Move initialization to old fields + out.ControlPlaneReady = ptr.Deref(in.Initialization.ControlPlaneInitialized, false) + out.InfrastructureReady = ptr.Deref(in.Initialization.InfrastructureProvisioned, false) + + // Move FailureDomains + if in.FailureDomains != nil { + out.FailureDomains = FailureDomains{} + for _, fd := range in.FailureDomains { + out.FailureDomains[fd.Name] = FailureDomainSpec{ + ControlPlane: ptr.Deref(fd.ControlPlane, false), + Attributes: fd.Attributes, + } + } + } + + // Move new conditions (v1beta2), controlPlane and workers counters to the v1beta2 field. + if in.Conditions == nil && in.ControlPlane == nil && in.Workers == nil { + return nil + } + out.V1Beta2 = &ClusterV1Beta2Status{} + out.V1Beta2.Conditions = in.Conditions + if in.ControlPlane != nil { + out.V1Beta2.ControlPlane = &ClusterControlPlaneStatus{ + DesiredReplicas: in.ControlPlane.DesiredReplicas, + Replicas: in.ControlPlane.Replicas, + UpToDateReplicas: in.ControlPlane.UpToDateReplicas, + ReadyReplicas: in.ControlPlane.ReadyReplicas, + AvailableReplicas: in.ControlPlane.AvailableReplicas, + } + } + if in.Workers != nil { + out.V1Beta2.Workers = &WorkersStatus{ + DesiredReplicas: in.Workers.DesiredReplicas, + Replicas: in.Workers.Replicas, + UpToDateReplicas: in.Workers.UpToDateReplicas, + ReadyReplicas: in.Workers.ReadyReplicas, + AvailableReplicas: in.Workers.AvailableReplicas, + } + } + return nil +} + +func Convert_v1beta1_Topology_To_v1beta2_Topology(in *Topology, out *clusterv1.Topology, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_Topology_To_v1beta2_Topology(in, out, s); err != nil { + return err + } + if in.Workers != nil { + if err := autoConvert_v1beta1_WorkersTopology_To_v1beta2_WorkersTopology(in.Workers, &out.Workers, s); err != nil { + return err + } + } + out.ClassRef.Name = in.Class + out.ClassRef.Namespace = in.ClassNamespace + return nil +} + +func Convert_v1beta1_ClusterStatus_To_v1beta2_ClusterStatus(in *ClusterStatus, out *clusterv1.ClusterStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ClusterStatus_To_v1beta2_ClusterStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta1 conditions should not be automatically be converted into v1beta2 conditions. + out.Conditions = nil + + // Retrieve new conditions (v1beta2), controlPlane and workers counters from the v1beta2 field. + if in.V1Beta2 != nil { + out.Conditions = in.V1Beta2.Conditions + if in.V1Beta2.ControlPlane != nil { + out.ControlPlane = &clusterv1.ClusterControlPlaneStatus{ + DesiredReplicas: in.V1Beta2.ControlPlane.DesiredReplicas, + Replicas: in.V1Beta2.ControlPlane.Replicas, + UpToDateReplicas: in.V1Beta2.ControlPlane.UpToDateReplicas, + ReadyReplicas: in.V1Beta2.ControlPlane.ReadyReplicas, + AvailableReplicas: in.V1Beta2.ControlPlane.AvailableReplicas, + } + } + if in.V1Beta2.Workers != nil { + out.Workers = &clusterv1.WorkersStatus{ + DesiredReplicas: in.V1Beta2.Workers.DesiredReplicas, + Replicas: in.V1Beta2.Workers.Replicas, + UpToDateReplicas: in.V1Beta2.Workers.UpToDateReplicas, + ReadyReplicas: in.V1Beta2.Workers.ReadyReplicas, + AvailableReplicas: in.V1Beta2.Workers.AvailableReplicas, + } + } + } + + // Move ControlPlaneReady and InfrastructureReady to Initialization is implemented in ConvertTo. + + // Move FailureDomains + if in.FailureDomains != nil { + out.FailureDomains = []clusterv1.FailureDomain{} + domainNames := slices.Collect(maps.Keys(in.FailureDomains)) + sort.Strings(domainNames) + for _, name := range domainNames { + fd := in.FailureDomains[name] + out.FailureDomains = append(out.FailureDomains, clusterv1.FailureDomain{ + Name: name, + ControlPlane: ptr.To(fd.ControlPlane), + Attributes: fd.Attributes, + }) + } + } + + // Move legacy conditions (v1beta1), FailureReason and FailureMessage to the deprecated field. + if in.Conditions == nil && in.FailureReason == nil && in.FailureMessage == nil { + return nil + } + + if out.Deprecated == nil { + out.Deprecated = &clusterv1.ClusterDeprecatedStatus{} + } + if out.Deprecated.V1Beta1 == nil { + out.Deprecated.V1Beta1 = &clusterv1.ClusterV1Beta1DeprecatedStatus{} + } + if in.Conditions != nil { + Convert_v1beta1_Conditions_To_v1beta2_Deprecated_V1Beta1_Conditions(&in.Conditions, &out.Deprecated.V1Beta1.Conditions) + } + out.Deprecated.V1Beta1.FailureReason = in.FailureReason + out.Deprecated.V1Beta1.FailureMessage = in.FailureMessage + return nil +} + +func Convert_v1beta2_Topology_To_v1beta1_Topology(in *clusterv1.Topology, out *Topology, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_Topology_To_v1beta1_Topology(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.Workers, clusterv1.WorkersTopology{}) { + out.Workers = &WorkersTopology{} + if err := autoConvert_v1beta2_WorkersTopology_To_v1beta1_WorkersTopology(&in.Workers, out.Workers, s); err != nil { + return err + } + } + out.Class = in.ClassRef.Name + out.ClassNamespace = in.ClassRef.Namespace + return nil +} + +func Convert_v1beta2_MachineDeploymentStatus_To_v1beta1_MachineDeploymentStatus(in *clusterv1.MachineDeploymentStatus, out *MachineDeploymentStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineDeploymentStatus_To_v1beta1_MachineDeploymentStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta2 conditions should not be automatically be converted into legacy conditions (v1beta1). + out.Conditions = nil + + // Reset replica counters from autogenerated conversions + // NOTE: replica counters with a new semantic should not be automatically be converted into old replica counters. + out.AvailableReplicas = 0 + out.ReadyReplicas = 0 + + // Retrieve legacy conditions (v1beta1) and replica counters from the deprecated field. + if in.Deprecated != nil && in.Deprecated.V1Beta1 != nil { + if in.Deprecated.V1Beta1.Conditions != nil { + Convert_v1beta2_Deprecated_V1Beta1_Conditions_To_v1beta1_Conditions(&in.Deprecated.V1Beta1.Conditions, &out.Conditions) + } + out.AvailableReplicas = in.Deprecated.V1Beta1.AvailableReplicas + out.UnavailableReplicas = in.Deprecated.V1Beta1.UnavailableReplicas + out.UpdatedReplicas = in.Deprecated.V1Beta1.UpdatedReplicas + out.ReadyReplicas = in.Deprecated.V1Beta1.ReadyReplicas + } + + // Move new conditions (v1beta2) and replica counters to the v1beta2 field. + if in.Conditions == nil && in.ReadyReplicas == nil && in.AvailableReplicas == nil && in.UpToDateReplicas == nil { + return nil + } + out.V1Beta2 = &MachineDeploymentV1Beta2Status{} + out.V1Beta2.Conditions = in.Conditions + out.V1Beta2.ReadyReplicas = in.ReadyReplicas + out.V1Beta2.AvailableReplicas = in.AvailableReplicas + out.V1Beta2.UpToDateReplicas = in.UpToDateReplicas + return nil +} + +func Convert_v1beta1_MachineDeploymentStatus_To_v1beta2_MachineDeploymentStatus(in *MachineDeploymentStatus, out *clusterv1.MachineDeploymentStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineDeploymentStatus_To_v1beta2_MachineDeploymentStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta1 conditions should not be automatically be converted into v1beta2 conditions. + out.Conditions = nil + + // Reset replica counters from autogenerated conversions + // NOTE: old replica counters should not be automatically be converted into replica counters with a new semantic. + out.AvailableReplicas = nil + out.ReadyReplicas = nil + + // Retrieve new conditions (v1beta2) and replica counters from the v1beta2 field. + if in.V1Beta2 != nil { + out.Conditions = in.V1Beta2.Conditions + out.ReadyReplicas = in.V1Beta2.ReadyReplicas + out.AvailableReplicas = in.V1Beta2.AvailableReplicas + out.UpToDateReplicas = in.V1Beta2.UpToDateReplicas + } + + // Move legacy conditions (v1beta1) and replica counters to the deprecated field. + if out.Deprecated == nil { + out.Deprecated = &clusterv1.MachineDeploymentDeprecatedStatus{} + } + if out.Deprecated.V1Beta1 == nil { + out.Deprecated.V1Beta1 = &clusterv1.MachineDeploymentV1Beta1DeprecatedStatus{} + } + if in.Conditions != nil { + Convert_v1beta1_Conditions_To_v1beta2_Deprecated_V1Beta1_Conditions(&in.Conditions, &out.Deprecated.V1Beta1.Conditions) + } + out.Deprecated.V1Beta1.AvailableReplicas = in.AvailableReplicas + out.Deprecated.V1Beta1.UnavailableReplicas = in.UnavailableReplicas + out.Deprecated.V1Beta1.UpdatedReplicas = in.UpdatedReplicas + out.Deprecated.V1Beta1.ReadyReplicas = in.ReadyReplicas + return nil +} + +func Convert_v1beta1_MachineHealthCheckSpec_To_v1beta2_MachineHealthCheckSpec(in *MachineHealthCheckSpec, out *clusterv1.MachineHealthCheckSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineHealthCheckSpec_To_v1beta2_MachineHealthCheckSpec(in, out, s); err != nil { + return err + } + + for _, c := range in.UnhealthyConditions { + out.Checks.UnhealthyNodeConditions = append(out.Checks.UnhealthyNodeConditions, clusterv1.UnhealthyNodeCondition{ + Type: c.Type, + Status: c.Status, + TimeoutSeconds: clusterv1.ConvertToSeconds(&c.Timeout), + }) + } + out.Checks.NodeStartupTimeoutSeconds = clusterv1.ConvertToSeconds(in.NodeStartupTimeout) + out.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo = in.MaxUnhealthy + out.Remediation.TriggerIf.UnhealthyInRange = ptr.Deref(in.UnhealthyRange, "") + if in.RemediationTemplate != nil { + if err := Convert_v1_ObjectReference_To_v1beta2_MachineHealthCheckRemediationTemplateReference(in.RemediationTemplate, &out.Remediation.TemplateRef, s); err != nil { + return err + } + } + + return nil +} + +func Convert_v1beta2_MachineHealthCheckSpec_To_v1beta1_MachineHealthCheckSpec(in *clusterv1.MachineHealthCheckSpec, out *MachineHealthCheckSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineHealthCheckSpec_To_v1beta1_MachineHealthCheckSpec(in, out, s); err != nil { + return err + } + + for _, c := range in.Checks.UnhealthyNodeConditions { + out.UnhealthyConditions = append(out.UnhealthyConditions, UnhealthyCondition{ + Type: c.Type, + Status: c.Status, + Timeout: ptr.Deref(clusterv1.ConvertFromSeconds(c.TimeoutSeconds), metav1.Duration{}), + }) + } + out.NodeStartupTimeout = clusterv1.ConvertFromSeconds(in.Checks.NodeStartupTimeoutSeconds) + out.MaxUnhealthy = in.Remediation.TriggerIf.UnhealthyLessThanOrEqualTo + if in.Remediation.TriggerIf.UnhealthyInRange != "" { + out.UnhealthyRange = ptr.To(in.Remediation.TriggerIf.UnhealthyInRange) + } + if in.Remediation.TemplateRef.IsDefined() { + out.RemediationTemplate = &corev1.ObjectReference{} + if err := Convert_v1beta2_MachineHealthCheckRemediationTemplateReference_To_v1_ObjectReference(&in.Remediation.TemplateRef, out.RemediationTemplate, s); err != nil { + return err + } + } + + return nil +} + +func Convert_v1beta2_MachineHealthCheckStatus_To_v1beta1_MachineHealthCheckStatus(in *clusterv1.MachineHealthCheckStatus, out *MachineHealthCheckStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineHealthCheckStatus_To_v1beta1_MachineHealthCheckStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta2 conditions should not be automatically be converted into legacy conditions (v1beta1). + out.Conditions = nil + + // Retrieve legacy conditions (v1beta1) from the deprecated field. + if in.Deprecated != nil && in.Deprecated.V1Beta1 != nil { + if in.Deprecated.V1Beta1.Conditions != nil { + Convert_v1beta2_Deprecated_V1Beta1_Conditions_To_v1beta1_Conditions(&in.Deprecated.V1Beta1.Conditions, &out.Conditions) + } + } + + // Move new conditions (v1beta2) to the v1beta2 field. + if in.Conditions == nil { + return nil + } + out.V1Beta2 = &MachineHealthCheckV1Beta2Status{} + out.V1Beta2.Conditions = in.Conditions + return nil +} + +func Convert_v1beta1_MachineHealthCheckStatus_To_v1beta2_MachineHealthCheckStatus(in *MachineHealthCheckStatus, out *clusterv1.MachineHealthCheckStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineHealthCheckStatus_To_v1beta2_MachineHealthCheckStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta1 conditions should not be automatically be converted into v1beta2 conditions. + out.Conditions = nil + + // Retrieve new conditions (v1beta2) from the v1beta2 field. + if in.V1Beta2 != nil { + out.Conditions = in.V1Beta2.Conditions + } + + // Move legacy conditions (v1beta1) to the deprecated field. + if in.Conditions == nil { + return nil + } + + if out.Deprecated == nil { + out.Deprecated = &clusterv1.MachineHealthCheckDeprecatedStatus{} + } + if out.Deprecated.V1Beta1 == nil { + out.Deprecated.V1Beta1 = &clusterv1.MachineHealthCheckV1Beta1DeprecatedStatus{} + } + if in.Conditions != nil { + Convert_v1beta1_Conditions_To_v1beta2_Deprecated_V1Beta1_Conditions(&in.Conditions, &out.Deprecated.V1Beta1.Conditions) + } + return nil +} + +func Convert_v1beta2_MachineSetStatus_To_v1beta1_MachineSetStatus(in *clusterv1.MachineSetStatus, out *MachineSetStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineSetStatus_To_v1beta1_MachineSetStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta2 conditions should not be automatically be converted into legacy conditions (v1beta1). + out.Conditions = nil + + // Reset replica counters from autogenerated conversions + // NOTE: replica counters with a new semantic should not be automatically be converted into old replica counters. + out.AvailableReplicas = 0 + out.ReadyReplicas = 0 + + // Retrieve legacy conditions (v1beta1), failureReason, failureMessage, and replica counters from the deprecated field. + if in.Deprecated != nil && in.Deprecated.V1Beta1 != nil { + if in.Deprecated.V1Beta1.Conditions != nil { + Convert_v1beta2_Deprecated_V1Beta1_Conditions_To_v1beta1_Conditions(&in.Deprecated.V1Beta1.Conditions, &out.Conditions) + } + out.AvailableReplicas = in.Deprecated.V1Beta1.AvailableReplicas + out.FullyLabeledReplicas = in.Deprecated.V1Beta1.FullyLabeledReplicas + out.ReadyReplicas = in.Deprecated.V1Beta1.ReadyReplicas + out.FailureReason = in.Deprecated.V1Beta1.FailureReason + out.FailureMessage = in.Deprecated.V1Beta1.FailureMessage + } + + // Move new conditions (v1beta2) and replica counters to the v1beta2 field. + if in.Conditions == nil && in.ReadyReplicas == nil && in.AvailableReplicas == nil && in.UpToDateReplicas == nil { + return nil + } + out.V1Beta2 = &MachineSetV1Beta2Status{} + out.V1Beta2.Conditions = in.Conditions + out.V1Beta2.ReadyReplicas = in.ReadyReplicas + out.V1Beta2.AvailableReplicas = in.AvailableReplicas + out.V1Beta2.UpToDateReplicas = in.UpToDateReplicas + return nil +} + +func Convert_v1beta1_MachineSetStatus_To_v1beta2_MachineSetStatus(in *MachineSetStatus, out *clusterv1.MachineSetStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineSetStatus_To_v1beta2_MachineSetStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta1 conditions should not be automatically be converted into v1beta2 conditions. + out.Conditions = nil + + // Reset replica counters from autogenerated conversions + // NOTE: old replica counters should not be automatically be converted into replica counters with a new semantic. + out.AvailableReplicas = nil + out.ReadyReplicas = nil + + // Retrieve new conditions (v1beta2) and replica counters from the v1beta2 field. + if in.V1Beta2 != nil { + out.Conditions = in.V1Beta2.Conditions + out.ReadyReplicas = in.V1Beta2.ReadyReplicas + out.AvailableReplicas = in.V1Beta2.AvailableReplicas + out.UpToDateReplicas = in.V1Beta2.UpToDateReplicas + } + + // Move legacy conditions (v1beta1), failureReason, failureMessage, and replica counters to the deprecated field. + if out.Deprecated == nil { + out.Deprecated = &clusterv1.MachineSetDeprecatedStatus{} + } + if out.Deprecated.V1Beta1 == nil { + out.Deprecated.V1Beta1 = &clusterv1.MachineSetV1Beta1DeprecatedStatus{} + } + if in.Conditions != nil { + Convert_v1beta1_Conditions_To_v1beta2_Deprecated_V1Beta1_Conditions(&in.Conditions, &out.Deprecated.V1Beta1.Conditions) + } + out.Deprecated.V1Beta1.AvailableReplicas = in.AvailableReplicas + out.Deprecated.V1Beta1.FullyLabeledReplicas = in.FullyLabeledReplicas + out.Deprecated.V1Beta1.ReadyReplicas = in.ReadyReplicas + out.Deprecated.V1Beta1.FailureReason = in.FailureReason + out.Deprecated.V1Beta1.FailureMessage = in.FailureMessage + return nil +} + +func Convert_v1beta2_MachineStatus_To_v1beta1_MachineStatus(in *clusterv1.MachineStatus, out *MachineStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineStatus_To_v1beta1_MachineStatus(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.LastUpdated, metav1.Time{}) { + out.LastUpdated = ptr.To(in.LastUpdated) + } + if !reflect.DeepEqual(in.CertificatesExpiryDate, metav1.Time{}) { + out.CertificatesExpiryDate = ptr.To(in.CertificatesExpiryDate) + } + if in.NodeRef.IsDefined() { + out.NodeRef = &corev1.ObjectReference{ + Name: in.NodeRef.Name, + APIVersion: corev1.SchemeGroupVersion.String(), + Kind: "Node", + } + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta2 conditions should not be automatically be converted into legacy conditions (v1beta1). + out.Conditions = nil + + // Retrieve legacy conditions (v1beta1), failureReason and failureMessage from the deprecated field. + if in.Deprecated != nil && in.Deprecated.V1Beta1 != nil { + if in.Deprecated.V1Beta1.Conditions != nil { + Convert_v1beta2_Deprecated_V1Beta1_Conditions_To_v1beta1_Conditions(&in.Deprecated.V1Beta1.Conditions, &out.Conditions) + } + out.FailureReason = in.Deprecated.V1Beta1.FailureReason + out.FailureMessage = in.Deprecated.V1Beta1.FailureMessage + } + + // Move initialization to old fields + out.BootstrapReady = ptr.Deref(in.Initialization.BootstrapDataSecretCreated, false) + out.InfrastructureReady = ptr.Deref(in.Initialization.InfrastructureProvisioned, false) + + // Move new conditions (v1beta2) to the v1beta2 field. + if in.Conditions == nil { + return nil + } + out.V1Beta2 = &MachineV1Beta2Status{} + out.V1Beta2.Conditions = in.Conditions + return nil +} + +func Convert_v1beta1_MachineStatus_To_v1beta2_MachineStatus(in *MachineStatus, out *clusterv1.MachineStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineStatus_To_v1beta2_MachineStatus(in, out, s); err != nil { + return err + } + + if in.LastUpdated != nil && !reflect.DeepEqual(in.LastUpdated, &metav1.Time{}) { + out.LastUpdated = *in.LastUpdated + } + if in.CertificatesExpiryDate != nil && !reflect.DeepEqual(in.CertificatesExpiryDate, &metav1.Time{}) { + out.CertificatesExpiryDate = *in.CertificatesExpiryDate + } + if in.NodeRef != nil && !reflect.DeepEqual(in.NodeRef, &corev1.ObjectReference{}) { + out.NodeRef.Name = in.NodeRef.Name + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta1 conditions should not be automatically be converted into v1beta2 conditions. + out.Conditions = nil + + // Retrieve new conditions (v1beta2) from the v1beta2 field. + if in.V1Beta2 != nil { + out.Conditions = in.V1Beta2.Conditions + } + + // Move BootstrapReady and InfrastructureReady to Initialization is implemented in ConvertTo. + + // Move legacy conditions (v1beta1), failureReason and failureMessage to the deprecated field. + if in.Conditions == nil && in.FailureReason == nil && in.FailureMessage == nil { + return nil + } + + if out.Deprecated == nil { + out.Deprecated = &clusterv1.MachineDeprecatedStatus{} + } + if out.Deprecated.V1Beta1 == nil { + out.Deprecated.V1Beta1 = &clusterv1.MachineV1Beta1DeprecatedStatus{} + } + if in.Conditions != nil { + Convert_v1beta1_Conditions_To_v1beta2_Deprecated_V1Beta1_Conditions(&in.Conditions, &out.Deprecated.V1Beta1.Conditions) + } + out.Deprecated.V1Beta1.FailureReason = in.FailureReason + out.Deprecated.V1Beta1.FailureMessage = in.FailureMessage + return nil +} + +func Convert_v1beta2_Deprecated_V1Beta1_Conditions_To_v1beta1_Conditions(in *clusterv1.Conditions, out *Conditions) { + *out = make(Conditions, len(*in)) + for i := range *in { + (*out)[i] = *(*Condition)(unsafe.Pointer(&(*in)[i])) //nolint:gosec + } +} + +func Convert_v1beta1_Conditions_To_v1beta2_Deprecated_V1Beta1_Conditions(in *Conditions, out *clusterv1.Conditions) { + *out = make(clusterv1.Conditions, len(*in)) + for i := range *in { + (*out)[i] = *(*clusterv1.Condition)(unsafe.Pointer(&(*in)[i])) //nolint:gosec + } +} + +func Convert_v1_Condition_To_v1beta1_Condition(_ *metav1.Condition, _ *Condition, _ apimachineryconversion.Scope) error { + // NOTE: v1beta2 conditions should not be automatically converted into legacy (v1beta1) conditions. + return nil +} + +func Convert_v1beta1_Condition_To_v1_Condition(_ *Condition, _ *metav1.Condition, _ apimachineryconversion.Scope) error { + // NOTE: legacy (v1beta1) conditions should not be automatically converted into v1beta2 conditions. + return nil +} + +func Convert_v1beta1_ClusterVariable_To_v1beta2_ClusterVariable(in *ClusterVariable, out *clusterv1.ClusterVariable, s apimachineryconversion.Scope) error { + // NOTE: v1beta2 ClusterVariable does not have DefinitionFrom anymore. But it's fine to just lose this field, + // because it was already not possible to set it anymore with v1beta1. + return autoConvert_v1beta1_ClusterVariable_To_v1beta2_ClusterVariable(in, out, s) +} + +func Convert_v1beta2_MachineSpec_To_v1beta1_MachineSpec(in *clusterv1.MachineSpec, out *MachineSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineSpec_To_v1beta1_MachineSpec(in, out, s); err != nil { + return err + } + out.NodeDrainTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDrainTimeoutSeconds) + out.NodeVolumeDetachTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeVolumeDetachTimeoutSeconds) + out.NodeDeletionTimeout = clusterv1.ConvertFromSeconds(in.Deletion.NodeDeletionTimeoutSeconds) + return nil +} + +func Convert_v1beta2_MachinePoolStatus_To_v1beta1_MachinePoolStatus(in *clusterv1.MachinePoolStatus, out *MachinePoolStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachinePoolStatus_To_v1beta1_MachinePoolStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta2 conditions should not be automatically be converted into legacy conditions (v1beta1). + out.Conditions = nil + + // Reset replica counters from autogenerated conversions + // NOTE: replica counters with a new semantic should not be automatically be converted into old replica counters. + out.ReadyReplicas = 0 + out.AvailableReplicas = 0 + + // Retrieve legacy conditions (v1beta1), failureReason, failureMessage and replica counters from the deprecated field. + if in.Deprecated != nil && in.Deprecated.V1Beta1 != nil { + if in.Deprecated.V1Beta1.Conditions != nil { + Convert_v1beta2_Deprecated_V1Beta1_Conditions_To_v1beta1_Conditions(&in.Deprecated.V1Beta1.Conditions, &out.Conditions) + } + out.FailureReason = in.Deprecated.V1Beta1.FailureReason + out.FailureMessage = in.Deprecated.V1Beta1.FailureMessage + out.ReadyReplicas = in.Deprecated.V1Beta1.ReadyReplicas + out.AvailableReplicas = in.Deprecated.V1Beta1.AvailableReplicas + out.UnavailableReplicas = in.Deprecated.V1Beta1.UnavailableReplicas + } + + // Move initialization to old fields + out.BootstrapReady = ptr.Deref(in.Initialization.BootstrapDataSecretCreated, false) + out.InfrastructureReady = ptr.Deref(in.Initialization.InfrastructureProvisioned, false) + + // Move new conditions (v1beta2) and replica counters to the v1beta2 field. + if in.Conditions == nil && in.ReadyReplicas == nil && in.AvailableReplicas == nil && in.UpToDateReplicas == nil { + return nil + } + out.V1Beta2 = &MachinePoolV1Beta2Status{} + out.V1Beta2.Conditions = in.Conditions + out.V1Beta2.ReadyReplicas = in.ReadyReplicas + out.V1Beta2.AvailableReplicas = in.AvailableReplicas + out.V1Beta2.UpToDateReplicas = in.UpToDateReplicas + return nil +} + +func Convert_v1beta1_MachinePoolStatus_To_v1beta2_MachinePoolStatus(in *MachinePoolStatus, out *clusterv1.MachinePoolStatus, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachinePoolStatus_To_v1beta2_MachinePoolStatus(in, out, s); err != nil { + return err + } + + // Reset conditions from autogenerated conversions + // NOTE: v1beta1 conditions should not be automatically be converted into v1beta2 conditions. + out.Conditions = nil + + // Reset replica counters from autogenerated conversions + // NOTE: old replica counters should not be automatically be converted into replica counters with a new semantic. + out.ReadyReplicas = nil + out.AvailableReplicas = nil + + // Retrieve new conditions (v1beta2) and replica counters from the v1beta2 field. + if in.V1Beta2 != nil { + out.Conditions = in.V1Beta2.Conditions + out.ReadyReplicas = in.V1Beta2.ReadyReplicas + out.AvailableReplicas = in.V1Beta2.AvailableReplicas + out.UpToDateReplicas = in.V1Beta2.UpToDateReplicas + } + + // Move BootstrapReady and InfrastructureReady to Initialization is implemented in ConvertTo. + + // Move legacy conditions (v1beta1), failureReason, failureMessage and replica counters to the deprecated field. + if out.Deprecated == nil { + out.Deprecated = &clusterv1.MachinePoolDeprecatedStatus{} + } + if out.Deprecated.V1Beta1 == nil { + out.Deprecated.V1Beta1 = &clusterv1.MachinePoolV1Beta1DeprecatedStatus{} + } + if in.Conditions != nil { + Convert_v1beta1_Conditions_To_v1beta2_Deprecated_V1Beta1_Conditions(&in.Conditions, &out.Deprecated.V1Beta1.Conditions) + } + out.Deprecated.V1Beta1.FailureReason = in.FailureReason + out.Deprecated.V1Beta1.FailureMessage = in.FailureMessage + out.Deprecated.V1Beta1.ReadyReplicas = in.ReadyReplicas + out.Deprecated.V1Beta1.AvailableReplicas = in.AvailableReplicas + out.Deprecated.V1Beta1.UnavailableReplicas = in.UnavailableReplicas + return nil +} + +func Convert_v1beta1_MachinePoolSpec_To_v1beta2_MachinePoolSpec(in *MachinePoolSpec, out *clusterv1.MachinePoolSpec, s apimachineryconversion.Scope) error { + return autoConvert_v1beta1_MachinePoolSpec_To_v1beta2_MachinePoolSpec(in, out, s) +} + +func Convert_v1beta1_ClusterClassStatusVariableDefinition_To_v1beta2_ClusterClassStatusVariableDefinition(in *ClusterClassStatusVariableDefinition, out *clusterv1.ClusterClassStatusVariableDefinition, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ClusterClassStatusVariableDefinition_To_v1beta2_ClusterClassStatusVariableDefinition(in, out, s); err != nil { + return err + } + return autoConvert_v1beta1_ClusterClassVariableMetadata_To_v1beta2_ClusterClassVariableMetadata(&in.Metadata, &out.DeprecatedV1Beta1Metadata, s) +} + +func Convert_v1beta2_ClusterClassStatusVariableDefinition_To_v1beta1_ClusterClassStatusVariableDefinition(in *clusterv1.ClusterClassStatusVariableDefinition, out *ClusterClassStatusVariableDefinition, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ClusterClassStatusVariableDefinition_To_v1beta1_ClusterClassStatusVariableDefinition(in, out, s); err != nil { + return err + } + return autoConvert_v1beta2_ClusterClassVariableMetadata_To_v1beta1_ClusterClassVariableMetadata(&in.DeprecatedV1Beta1Metadata, &out.Metadata, s) +} + +func Convert_v1beta1_ClusterClassVariable_To_v1beta2_ClusterClassVariable(in *ClusterClassVariable, out *clusterv1.ClusterClassVariable, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ClusterClassVariable_To_v1beta2_ClusterClassVariable(in, out, s); err != nil { + return err + } + return autoConvert_v1beta1_ClusterClassVariableMetadata_To_v1beta2_ClusterClassVariableMetadata(&in.Metadata, &out.DeprecatedV1Beta1Metadata, s) +} + +func Convert_v1beta2_ClusterClassVariable_To_v1beta1_ClusterClassVariable(in *clusterv1.ClusterClassVariable, out *ClusterClassVariable, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ClusterClassVariable_To_v1beta1_ClusterClassVariable(in, out, s); err != nil { + return err + } + return autoConvert_v1beta2_ClusterClassVariableMetadata_To_v1beta1_ClusterClassVariableMetadata(&in.DeprecatedV1Beta1Metadata, &out.Metadata, s) +} + +func Convert_v1beta1_ExternalPatchDefinition_To_v1beta2_ExternalPatchDefinition(in *ExternalPatchDefinition, out *clusterv1.ExternalPatchDefinition, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ExternalPatchDefinition_To_v1beta2_ExternalPatchDefinition(in, out, s); err != nil { + return err + } + + out.GeneratePatchesExtension = ptr.Deref(in.GenerateExtension, "") + out.ValidateTopologyExtension = ptr.Deref(in.ValidateExtension, "") + return nil +} + +func Convert_v1beta2_ExternalPatchDefinition_To_v1beta1_ExternalPatchDefinition(in *clusterv1.ExternalPatchDefinition, out *ExternalPatchDefinition, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ExternalPatchDefinition_To_v1beta1_ExternalPatchDefinition(in, out, s); err != nil { + return err + } + + if in.GeneratePatchesExtension != "" { + out.GenerateExtension = ptr.To(in.GeneratePatchesExtension) + } + if in.ValidateTopologyExtension != "" { + out.ValidateExtension = ptr.To(in.ValidateTopologyExtension) + } + return nil +} + +func Convert_v1_ObjectReference_To_v1beta2_MachineHealthCheckRemediationTemplateReference(in *corev1.ObjectReference, out *clusterv1.MachineHealthCheckRemediationTemplateReference, _ apimachineryconversion.Scope) error { + out.Name = in.Name + out.Kind = in.Kind + out.APIVersion = in.APIVersion + return nil +} + +func Convert_v1beta2_MachineHealthCheckRemediationTemplateReference_To_v1_ObjectReference(in *clusterv1.MachineHealthCheckRemediationTemplateReference, out *corev1.ObjectReference, _ apimachineryconversion.Scope) error { + out.Name = in.Name + out.Kind = in.Kind + out.APIVersion = in.APIVersion + return nil +} + +func Convert_v1_ObjectReference_To_v1beta2_ContractVersionedObjectReference(_ *corev1.ObjectReference, _ *clusterv1.ContractVersionedObjectReference, _ apimachineryconversion.Scope) error { + // This is implemented in ConvertTo/ConvertFrom as we have all necessary information available there. + return nil +} + +func Convert_v1beta2_ContractVersionedObjectReference_To_v1_ObjectReference(_ *clusterv1.ContractVersionedObjectReference, _ *corev1.ObjectReference, _ apimachineryconversion.Scope) error { + // This is implemented in ConvertTo/ConvertFrom as we have all necessary information available there. + return nil +} + +func Convert_v1_ObjectReference_To_v1beta2_MachineNodeReference(in *corev1.ObjectReference, out *clusterv1.MachineNodeReference, _ apimachineryconversion.Scope) error { + out.Name = in.Name + return nil +} + +func Convert_v1beta2_MachineNodeReference_To_v1_ObjectReference(in *clusterv1.MachineNodeReference, out *corev1.ObjectReference, _ apimachineryconversion.Scope) error { + out.Name = in.Name + out.APIVersion = corev1.SchemeGroupVersion.String() + out.Kind = "Node" + return nil +} + +func Convert_v1beta1_LocalObjectTemplate_To_v1beta2_ControlPlaneClassMachineInfrastructureTemplate(in *LocalObjectTemplate, out *clusterv1.ControlPlaneClassMachineInfrastructureTemplate, s apimachineryconversion.Scope) error { + convert_v1beta1_LocalObjectTemplate_To_v1beta2_ClusterClassTemplateReference(in, &out.TemplateRef, s) + return nil +} + +func Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachineDeploymentClassBootstrapTemplate(in *LocalObjectTemplate, out *clusterv1.MachineDeploymentClassBootstrapTemplate, s apimachineryconversion.Scope) error { + convert_v1beta1_LocalObjectTemplate_To_v1beta2_ClusterClassTemplateReference(in, &out.TemplateRef, s) + return nil +} + +func Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachineDeploymentClassInfrastructureTemplate(in *LocalObjectTemplate, out *clusterv1.MachineDeploymentClassInfrastructureTemplate, s apimachineryconversion.Scope) error { + convert_v1beta1_LocalObjectTemplate_To_v1beta2_ClusterClassTemplateReference(in, &out.TemplateRef, s) + return nil +} + +func Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachinePoolClassBootstrapTemplate(in *LocalObjectTemplate, out *clusterv1.MachinePoolClassBootstrapTemplate, s apimachineryconversion.Scope) error { + convert_v1beta1_LocalObjectTemplate_To_v1beta2_ClusterClassTemplateReference(in, &out.TemplateRef, s) + return nil +} + +func Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachinePoolClassInfrastructureTemplate(in *LocalObjectTemplate, out *clusterv1.MachinePoolClassInfrastructureTemplate, s apimachineryconversion.Scope) error { + convert_v1beta1_LocalObjectTemplate_To_v1beta2_ClusterClassTemplateReference(in, &out.TemplateRef, s) + return nil +} + +func convert_v1beta1_LocalObjectTemplate_To_v1beta2_ClusterClassTemplateReference(in *LocalObjectTemplate, out *clusterv1.ClusterClassTemplateReference, _ apimachineryconversion.Scope) { + if in == nil || in.Ref == nil { + return + } + + *out = clusterv1.ClusterClassTemplateReference{ + Kind: in.Ref.Kind, + Name: in.Ref.Name, + APIVersion: in.Ref.APIVersion, + } +} + +func Convert_v1beta2_ControlPlaneClassMachineInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(in *clusterv1.ControlPlaneClassMachineInfrastructureTemplate, out *LocalObjectTemplate, s apimachineryconversion.Scope) error { + Convert_v1beta2_ClusterClassTemplateReference_To_v1beta1_LocalObjectTemplate(&in.TemplateRef, out, s) + return nil +} + +func Convert_v1beta2_MachineDeploymentClassBootstrapTemplate_To_v1beta1_LocalObjectTemplate(in *clusterv1.MachineDeploymentClassBootstrapTemplate, out *LocalObjectTemplate, s apimachineryconversion.Scope) error { + Convert_v1beta2_ClusterClassTemplateReference_To_v1beta1_LocalObjectTemplate(&in.TemplateRef, out, s) + return nil +} + +func Convert_v1beta2_MachineDeploymentClassInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(in *clusterv1.MachineDeploymentClassInfrastructureTemplate, out *LocalObjectTemplate, s apimachineryconversion.Scope) error { + Convert_v1beta2_ClusterClassTemplateReference_To_v1beta1_LocalObjectTemplate(&in.TemplateRef, out, s) + return nil +} + +func Convert_v1beta2_MachinePoolClassBootstrapTemplate_To_v1beta1_LocalObjectTemplate(in *clusterv1.MachinePoolClassBootstrapTemplate, out *LocalObjectTemplate, s apimachineryconversion.Scope) error { + Convert_v1beta2_ClusterClassTemplateReference_To_v1beta1_LocalObjectTemplate(&in.TemplateRef, out, s) + return nil +} + +func Convert_v1beta2_MachinePoolClassInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(in *clusterv1.MachinePoolClassInfrastructureTemplate, out *LocalObjectTemplate, s apimachineryconversion.Scope) error { + Convert_v1beta2_ClusterClassTemplateReference_To_v1beta1_LocalObjectTemplate(&in.TemplateRef, out, s) + return nil +} + +func Convert_v1beta2_ClusterClassTemplateReference_To_v1beta1_LocalObjectTemplate(in *clusterv1.ClusterClassTemplateReference, out *LocalObjectTemplate, _ apimachineryconversion.Scope) { + if in == nil { + return + } + + out.Ref = &corev1.ObjectReference{ + Kind: in.Kind, + Name: in.Name, + APIVersion: in.APIVersion, + } +} + +func Convert_v1beta1_MachineSetSpec_To_v1beta2_MachineSetSpec(in *MachineSetSpec, out *clusterv1.MachineSetSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_MachineSetSpec_To_v1beta2_MachineSetSpec(in, out, s); err != nil { + return err + } + + out.Deletion.Order = clusterv1.MachineSetDeletionOrder(in.DeletePolicy) + if in.MachineNamingStrategy != nil { + out.MachineNaming = clusterv1.MachineNamingSpec{ + Template: in.MachineNamingStrategy.Template, + } + } + return nil +} + +func Convert_v1beta2_MachineSetSpec_To_v1beta1_MachineSetSpec(in *clusterv1.MachineSetSpec, out *MachineSetSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineSetSpec_To_v1beta1_MachineSetSpec(in, out, s); err != nil { + return err + } + + out.DeletePolicy = string(in.Deletion.Order) + if in.MachineNaming.Template != "" { + out.MachineNamingStrategy = &MachineNamingStrategy{ + Template: in.MachineNaming.Template, + } + } + return nil +} + +func Convert_v1beta1_ClusterSpec_To_v1beta2_ClusterSpec(in *ClusterSpec, out *clusterv1.ClusterSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ClusterSpec_To_v1beta2_ClusterSpec(in, out, s); err != nil { + return err + } + if in.ClusterNetwork != nil { + if err := Convert_v1beta1_ClusterNetwork_To_v1beta2_ClusterNetwork(in.ClusterNetwork, &out.ClusterNetwork, s); err != nil { + return err + } + } + if in.Topology != nil { + if err := Convert_v1beta1_Topology_To_v1beta2_Topology(in.Topology, &out.Topology, s); err != nil { + return err + } + } + + return nil +} + +func Convert_v1beta2_ClusterSpec_To_v1beta1_ClusterSpec(in *clusterv1.ClusterSpec, out *ClusterSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ClusterSpec_To_v1beta1_ClusterSpec(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.ClusterNetwork, clusterv1.ClusterNetwork{}) { + out.ClusterNetwork = &ClusterNetwork{} + if err := Convert_v1beta2_ClusterNetwork_To_v1beta1_ClusterNetwork(&in.ClusterNetwork, out.ClusterNetwork, s); err != nil { + return err + } + } + if !reflect.DeepEqual(in.Topology, clusterv1.Topology{}) { + out.Topology = &Topology{} + if err := Convert_v1beta2_Topology_To_v1beta1_Topology(&in.Topology, out.Topology, s); err != nil { + return err + } + } + + return nil +} + +func Convert_v1beta1_ClusterNetwork_To_v1beta2_ClusterNetwork(in *ClusterNetwork, out *clusterv1.ClusterNetwork, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_ClusterNetwork_To_v1beta2_ClusterNetwork(in, out, s); err != nil { + return err + } + if in.Services != nil { + if err := autoConvert_v1beta1_NetworkRanges_To_v1beta2_NetworkRanges(in.Services, &out.Services, s); err != nil { + return err + } + } + if in.Pods != nil { + if err := autoConvert_v1beta1_NetworkRanges_To_v1beta2_NetworkRanges(in.Pods, &out.Pods, s); err != nil { + return err + } + } + + return nil +} + +func Convert_v1beta2_ClusterNetwork_To_v1beta1_ClusterNetwork(in *clusterv1.ClusterNetwork, out *ClusterNetwork, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_ClusterNetwork_To_v1beta1_ClusterNetwork(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.Services, clusterv1.NetworkRanges{}) { + out.Services = &NetworkRanges{} + if err := autoConvert_v1beta2_NetworkRanges_To_v1beta1_NetworkRanges(&in.Services, out.Services, s); err != nil { + return err + } + } + + if !reflect.DeepEqual(in.Pods, clusterv1.NetworkRanges{}) { + out.Pods = &NetworkRanges{} + if err := autoConvert_v1beta2_NetworkRanges_To_v1beta1_NetworkRanges(&in.Pods, out.Pods, s); err != nil { + return err + } + } + + return nil +} + +func Convert_v1beta1_MachineDeploymentSpec_To_v1beta2_MachineDeploymentSpec(in *MachineDeploymentSpec, out *clusterv1.MachineDeploymentSpec, s apimachineryconversion.Scope) error { + // NOTE: v1beta2 MachineDeploymentSpec does not have ProgressDeadlineSeconds anymore. But it's fine to just lose this field it was never used. + if err := autoConvert_v1beta1_MachineDeploymentSpec_To_v1beta2_MachineDeploymentSpec(in, out, s); err != nil { + return err + } + if in.Strategy != nil { + out.Rollout.Strategy.Type = clusterv1.MachineDeploymentRolloutStrategyType(in.Strategy.Type) + if in.Strategy.RollingUpdate != nil { + out.Rollout.Strategy.RollingUpdate.MaxUnavailable = in.Strategy.RollingUpdate.MaxUnavailable + out.Rollout.Strategy.RollingUpdate.MaxSurge = in.Strategy.RollingUpdate.MaxSurge + if in.Strategy.RollingUpdate.DeletePolicy != nil { + out.Deletion.Order = clusterv1.MachineSetDeletionOrder(*in.Strategy.RollingUpdate.DeletePolicy) + } + } + if in.Strategy.Remediation != nil && in.Strategy.Remediation.MaxInFlight != nil { + out.Remediation.MaxInFlight = in.Strategy.Remediation.MaxInFlight + } + } + if in.RolloutAfter != nil && !reflect.DeepEqual(in.RolloutAfter, &metav1.Time{}) { + out.Rollout.After = *in.RolloutAfter + } + if in.MachineNamingStrategy != nil { + out.MachineNaming = clusterv1.MachineNamingSpec{ + Template: in.MachineNamingStrategy.Template, + } + } + + return nil +} + +func Convert_v1beta2_MachineDeploymentSpec_To_v1beta1_MachineDeploymentSpec(in *clusterv1.MachineDeploymentSpec, out *MachineDeploymentSpec, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_MachineDeploymentSpec_To_v1beta1_MachineDeploymentSpec(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.Rollout.Strategy, clusterv1.MachineDeploymentRolloutStrategy{}) { + out.Strategy = &MachineDeploymentStrategy{} + out.Strategy.Type = MachineDeploymentStrategyType(in.Rollout.Strategy.Type) + if !reflect.DeepEqual(in.Rollout.Strategy.RollingUpdate, clusterv1.MachineDeploymentRolloutStrategyRollingUpdate{}) { + out.Strategy.RollingUpdate = &MachineRollingUpdateDeployment{} + out.Strategy.RollingUpdate.MaxUnavailable = in.Rollout.Strategy.RollingUpdate.MaxUnavailable + out.Strategy.RollingUpdate.MaxSurge = in.Rollout.Strategy.RollingUpdate.MaxSurge + } + } + if in.Deletion.Order != "" { + if out.Strategy == nil { + out.Strategy = &MachineDeploymentStrategy{} + } + if out.Strategy.RollingUpdate == nil { + out.Strategy.RollingUpdate = &MachineRollingUpdateDeployment{} + } + out.Strategy.RollingUpdate.DeletePolicy = ptr.To(string(in.Deletion.Order)) + } + if in.Remediation.MaxInFlight != nil { + if out.Strategy == nil { + out.Strategy = &MachineDeploymentStrategy{} + } + if out.Strategy.Remediation == nil { + out.Strategy.Remediation = &RemediationStrategy{} + } + out.Strategy.Remediation.MaxInFlight = in.Remediation.MaxInFlight + } + if !reflect.DeepEqual(in.Rollout.After, metav1.Time{}) { + out.RolloutAfter = ptr.To(in.Rollout.After) + } + if in.MachineNaming.Template != "" { + out.MachineNamingStrategy = &MachineNamingStrategy{ + Template: in.MachineNaming.Template, + } + } + return nil +} + +func Convert_v1beta1_Bootstrap_To_v1beta2_Bootstrap(in *Bootstrap, out *clusterv1.Bootstrap, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta1_Bootstrap_To_v1beta2_Bootstrap(in, out, s); err != nil { + return err + } + if in.ConfigRef != nil { + if err := Convert_v1_ObjectReference_To_v1beta2_ContractVersionedObjectReference(in.ConfigRef, &out.ConfigRef, s); err != nil { + return err + } + } + return nil +} + +func Convert_v1beta2_Bootstrap_To_v1beta1_Bootstrap(in *clusterv1.Bootstrap, out *Bootstrap, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_Bootstrap_To_v1beta1_Bootstrap(in, out, s); err != nil { + return err + } + if in.ConfigRef.IsDefined() { + out.ConfigRef = &corev1.ObjectReference{} + if err := Convert_v1beta2_ContractVersionedObjectReference_To_v1_ObjectReference(&in.ConfigRef, out.ConfigRef, s); err != nil { + return err + } + } + return nil +} + +func convertMachineSpecToContractVersionedObjectReference(src *MachineSpec, dst *clusterv1.MachineSpec) error { + infraRef, err := convertToContractVersionedObjectReference(&src.InfrastructureRef) + if err != nil { + return err + } + dst.InfrastructureRef = infraRef + + if src.Bootstrap.ConfigRef != nil { + bootstrapRef, err := convertToContractVersionedObjectReference(src.Bootstrap.ConfigRef) + if err != nil { + return err + } + dst.Bootstrap.ConfigRef = bootstrapRef + } + + return nil +} + +func convertMachineSpecToObjectReference(src *clusterv1.MachineSpec, dst *MachineSpec, namespace string) error { + if src.InfrastructureRef.IsDefined() { + infraRef, err := convertToObjectReference(src.InfrastructureRef, namespace) + if err != nil { + return err + } + dst.InfrastructureRef = *infraRef + } + + if src.Bootstrap.ConfigRef.IsDefined() { + bootstrapRef, err := convertToObjectReference(src.Bootstrap.ConfigRef, namespace) + if err != nil { + return err + } + dst.Bootstrap.ConfigRef = bootstrapRef + } + + return nil +} + +func convertToContractVersionedObjectReference(ref *corev1.ObjectReference) (clusterv1.ContractVersionedObjectReference, error) { + var apiGroup string + if ref.APIVersion != "" { + gv, err := schema.ParseGroupVersion(ref.APIVersion) + if err != nil { + return clusterv1.ContractVersionedObjectReference{}, fmt.Errorf("failed to convert object: failed to parse apiVersion: %v", err) + } + apiGroup = gv.Group + } + return clusterv1.ContractVersionedObjectReference{ + APIGroup: apiGroup, + Kind: ref.Kind, + Name: ref.Name, + }, nil +} + +func convertToObjectReference(ref clusterv1.ContractVersionedObjectReference, namespace string) (*corev1.ObjectReference, error) { + apiVersion, err := apiVersionGetter(schema.GroupKind{ + Group: ref.APIGroup, + Kind: ref.Kind, + }) + if err != nil { + return nil, fmt.Errorf("failed to convert object: %v", err) + } + return &corev1.ObjectReference{ + APIVersion: apiVersion, + Kind: ref.Kind, + Namespace: namespace, + Name: ref.Name, + }, nil +} + +func Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(in *JSONSchemaProps, out *clusterv1.JSONSchemaProps, s apimachineryconversion.Scope) error { + // This conversion func is also required due to a bug in conversion gen that does not recognize the changes for converting bool to *bool. + // By implementing this func, autoConvert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps is generated properly. + if err := autoConvert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(in, out, s); err != nil { + return err + } + if in.XMetadata != nil { + if err := Convert_v1beta1_VariableSchemaMetadata_To_v1beta2_VariableSchemaMetadata(in.XMetadata, &out.XMetadata, s); err != nil { + return err + } + } + return nil +} + +func Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *clusterv1.JSONSchemaProps, out *JSONSchemaProps, s apimachineryconversion.Scope) error { + if err := autoConvert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in, out, s); err != nil { + return err + } + if !reflect.DeepEqual(in.XMetadata, clusterv1.VariableSchemaMetadata{}) { + out.XMetadata = &VariableSchemaMetadata{} + if err := Convert_v1beta2_VariableSchemaMetadata_To_v1beta1_VariableSchemaMetadata(&in.XMetadata, out.XMetadata, s); err != nil { + return err + } + } + return nil +} + +func dropEmptyStringsCluster(dst *Cluster) { + if dst.Spec.Topology != nil { + if dst.Spec.Topology.Workers != nil { + for i, md := range dst.Spec.Topology.Workers.MachineDeployments { + dropEmptyString(&md.FailureDomain) + dst.Spec.Topology.Workers.MachineDeployments[i] = md + } + } + } +} + +func dropEmptyStringsClusterClass(dst *ClusterClass) { + if dst.Spec.InfrastructureNamingStrategy != nil { + dropEmptyString(&dst.Spec.InfrastructureNamingStrategy.Template) + } + + if dst.Spec.ControlPlane.NamingStrategy != nil { + dropEmptyString(&dst.Spec.ControlPlane.NamingStrategy.Template) + } + + for i, md := range dst.Spec.Workers.MachineDeployments { + if md.NamingStrategy != nil { + dropEmptyString(&md.NamingStrategy.Template) + } + dropEmptyString(&md.FailureDomain) + dst.Spec.Workers.MachineDeployments[i] = md + } + + for i, mp := range dst.Spec.Workers.MachinePools { + if mp.NamingStrategy != nil { + dropEmptyString(&mp.NamingStrategy.Template) + } + + dst.Spec.Workers.MachinePools[i] = mp + } + + for i, p := range dst.Spec.Patches { + dropEmptyString(&p.EnabledIf) + if p.External != nil { + dropEmptyString(&p.External.GenerateExtension) + dropEmptyString(&p.External.ValidateExtension) + dropEmptyString(&p.External.DiscoverVariablesExtension) + } + + for j, d := range p.Definitions { + for k, jp := range d.JSONPatches { + if jp.ValueFrom != nil { + dropEmptyString(&jp.ValueFrom.Variable) + dropEmptyString(&jp.ValueFrom.Template) + } + d.JSONPatches[k] = jp + } + p.Definitions[j] = d + } + + dst.Spec.Patches[i] = p + } +} + +func dropEmptyStringsMachineSpec(spec *MachineSpec) { + dropEmptyString(&spec.Version) + dropEmptyString(&spec.ProviderID) + dropEmptyString(&spec.FailureDomain) +} + +func dropEmptyString(s **string) { + if *s != nil && **s == "" { + *s = nil + } +} + +func Convert_v1beta1_MachineDeletionStatus_To_v1beta2_MachineDeletionStatus(in *MachineDeletionStatus, out *clusterv1.MachineDeletionStatus, _ apimachineryconversion.Scope) error { + if in.NodeDrainStartTime != nil && !reflect.DeepEqual(in.NodeDrainStartTime, &metav1.Time{}) { + out.NodeDrainStartTime = *in.NodeDrainStartTime + } + if in.WaitForNodeVolumeDetachStartTime != nil && !reflect.DeepEqual(in.WaitForNodeVolumeDetachStartTime, &metav1.Time{}) { + out.WaitForNodeVolumeDetachStartTime = *in.WaitForNodeVolumeDetachStartTime + } + return nil +} + +func Convert_v1beta2_MachineDeletionStatus_To_v1beta1_MachineDeletionStatus(in *clusterv1.MachineDeletionStatus, out *MachineDeletionStatus, _ apimachineryconversion.Scope) error { + if !reflect.DeepEqual(in.NodeDrainStartTime, metav1.Time{}) { + out.NodeDrainStartTime = ptr.To(in.NodeDrainStartTime) + } + if !reflect.DeepEqual(in.WaitForNodeVolumeDetachStartTime, metav1.Time{}) { + out.WaitForNodeVolumeDetachStartTime = ptr.To(in.WaitForNodeVolumeDetachStartTime) + } + return nil +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/conversion.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/doc.go similarity index 62% rename from vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/conversion.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/doc.go index cdb792fc34f4..1df77151b575 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/conversion.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/doc.go @@ -14,9 +14,11 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package v1beta1 contains API Schema definitions for the cluster v1beta1 API group +// +k8s:openapi-gen=true +// +k8s:conversion-gen=sigs.k8s.io/cluster-api/api/core/v1beta2 +// +kubebuilder:object:generate=true +// +groupName=cluster.x-k8s.io +// +// Deprecated: This package is deprecated and is going to be removed when support for v1beta1 will be dropped. package v1beta1 - -func (*ClusterResourceSet) Hub() {} -func (*ClusterResourceSetList) Hub() {} -func (*ClusterResourceSetBinding) Hub() {} -func (*ClusterResourceSetBindingList) Hub() {} diff --git a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/groupversion_info.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/groupversion_info.go similarity index 66% rename from vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/groupversion_info.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/groupversion_info.go index fd5c24e955a8..63ef4c408b01 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/groupversion_info.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/groupversion_info.go @@ -14,9 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1beta1 contains API Schema definitions for the exp v1beta1 API group -// +kubebuilder:object:generate=true -// +groupName=cluster.x-k8s.io package v1beta1 import ( @@ -35,7 +32,19 @@ var ( // AddToScheme adds the types in this group-version to the given scheme. AddToScheme = schemeBuilder.AddToScheme + // localSchemeBuilder is used for type conversions. + localSchemeBuilder = &schemeBuilder + objectTypes = []runtime.Object{} + + // GroupVersionInfrastructure is the recommended group version for infrastructure objects. + GroupVersionInfrastructure = schema.GroupVersion{Group: "infrastructure.cluster.x-k8s.io", Version: "v1beta1"} + + // GroupVersionBootstrap is the recommended group version for bootstrap objects. + GroupVersionBootstrap = schema.GroupVersion{Group: "bootstrap.cluster.x-k8s.io", Version: "v1beta1"} + + // GroupVersionControlPlane is the recommended group version for controlplane objects. + GroupVersionControlPlane = schema.GroupVersion{Group: "controlplane.cluster.x-k8s.io", Version: "v1beta1"} ) func addKnownTypes(scheme *runtime.Scheme) error { diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machine_phase_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machine_phase_types.go similarity index 100% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/machine_phase_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machine_phase_types.go diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machine_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machine_types.go similarity index 97% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/machine_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machine_types.go index f4a1cdee5609..9665953dd4d0 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machine_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machine_types.go @@ -375,8 +375,6 @@ const ( MachineDeletingDeletionCompletedV1Beta2Reason = DeletionCompletedV1Beta2Reason ) -// ANCHOR: MachineSpec - // MachineSpec defines the desired state of Machine. type MachineSpec struct { // clusterName is the name of the Cluster this object belongs to. @@ -424,14 +422,6 @@ type MachineSpec struct { // +kubebuilder:validation:MaxLength=256 FailureDomain *string `json:"failureDomain,omitempty"` - // The minimum number of seconds for which a Machine should be ready before considering it available. - // Defaults to 0 (Machine will be considered available as soon as the Machine is ready) - // NOTE: this field will be considered only for computing v1beta2 conditions. - // +optional - // TODO: This field will be added in the v1beta2 API, and act as a replacement of existing MinReadySeconds in - // MachineDeployment, MachineSet and MachinePool - // MinReadySeconds int32 `json:"minReadySeconds,omitempty"` - // readinessGates specifies additional conditions to include when evaluating Machine Ready condition. // // This field can be used e.g. by Cluster API control plane providers to extend the semantic of the @@ -491,10 +481,6 @@ type MachineReadinessGate struct { Polarity ConditionPolarity `json:"polarity,omitempty"` } -// ANCHOR_END: MachineSpec - -// ANCHOR: MachineStatus - // MachineStatus defines the observed state of Machine. type MachineStatus struct { // nodeRef will point to the corresponding Node if it exists. @@ -527,7 +513,7 @@ type MachineStatus struct { // can be added as events to the Machine object and/or logged in the // controller's output. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional FailureReason *capierrors.MachineStatusError `json:"failureReason,omitempty"` @@ -549,7 +535,7 @@ type MachineStatus struct { // can be added as events to the Machine object and/or logged in the // controller's output. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional // +kubebuilder:validation:MinLength=1 @@ -613,8 +599,6 @@ type MachineV1Beta2Status struct { Conditions []metav1.Condition `json:"conditions,omitempty"` } -// ANCHOR_END: MachineStatus - // MachineDeletionStatus is the deletion state of the Machine. type MachineDeletionStatus struct { // nodeDrainStartTime is the time when the drain of the node started and is used to determine @@ -655,8 +639,6 @@ func (m *MachineStatus) GetTypedPhase() MachinePhase { } } -// ANCHOR: Bootstrap - // Bootstrap encapsulates fields to configure the Machine’s bootstrapping mechanism. type Bootstrap struct { // configRef is a reference to a bootstrap provider-specific resource @@ -674,12 +656,10 @@ type Bootstrap struct { DataSecretName *string `json:"dataSecretName,omitempty"` } -// ANCHOR_END: Bootstrap - // +kubebuilder:object:root=true // +kubebuilder:resource:path=machines,shortName=ma,scope=Namespaced,categories=cluster-api // +kubebuilder:subresource:status -// +kubebuilder:storageversion +// +kubebuilder:deprecatedversion // +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" // +kubebuilder:printcolumn:name="NodeName",type="string",JSONPath=".status.nodeRef.name",description="Node name associated with this machine" // +kubebuilder:printcolumn:name="ProviderID",type="string",JSONPath=".spec.providerID",description="Provider ID" diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinedeployment_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinedeployment_types.go similarity index 98% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinedeployment_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinedeployment_types.go index 80307605d5ac..4abb03a9aace 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinedeployment_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinedeployment_types.go @@ -236,8 +236,6 @@ const ( MachineDeploymentDeletingInternalErrorV1Beta2Reason = InternalErrorV1Beta2Reason ) -// ANCHOR: MachineDeploymentSpec - // MachineDeploymentSpec defines the desired state of MachineDeployment. type MachineDeploymentSpec struct { // clusterName is the name of the Cluster this object belongs to. @@ -325,10 +323,6 @@ type MachineDeploymentSpec struct { ProgressDeadlineSeconds *int32 `json:"progressDeadlineSeconds,omitempty"` } -// ANCHOR_END: MachineDeploymentSpec - -// ANCHOR: MachineDeploymentStrategy - // MachineDeploymentStrategy describes how to replace existing machines // with new ones. type MachineDeploymentStrategy struct { @@ -349,10 +343,6 @@ type MachineDeploymentStrategy struct { Remediation *RemediationStrategy `json:"remediation,omitempty"` } -// ANCHOR_END: MachineDeploymentStrategy - -// ANCHOR: MachineRollingUpdateDeployment - // MachineRollingUpdateDeployment is used to control the desired behavior of rolling update. type MachineRollingUpdateDeployment struct { // maxUnavailable is the maximum number of machines that can be unavailable during the update. @@ -394,10 +384,6 @@ type MachineRollingUpdateDeployment struct { DeletePolicy *string `json:"deletePolicy,omitempty"` } -// ANCHOR_END: MachineRollingUpdateDeployment - -// ANCHOR: RemediationStrategy - // RemediationStrategy allows to define how the MachineSet can control scaling operations. type RemediationStrategy struct { // maxInFlight determines how many in flight remediations should happen at the same time. @@ -419,8 +405,6 @@ type RemediationStrategy struct { MaxInFlight *intstr.IntOrString `json:"maxInFlight,omitempty"` } -// ANCHOR_END: RemediationStrategy - // MachineNamingStrategy allows changing the naming pattern used when creating // Machines. // Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines. @@ -447,8 +431,6 @@ type MachineNamingStrategy struct { Template string `json:"template,omitempty"` } -// ANCHOR: MachineDeploymentStatus - // MachineDeploymentStatus defines the observed state of MachineDeployment. type MachineDeploymentStatus struct { // observedGeneration is the generation observed by the deployment controller. @@ -488,7 +470,7 @@ type MachineDeploymentStatus struct { // be machines that are running but not yet available or machines // that still have not been created. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional UnavailableReplicas int32 `json:"unavailableReplicas"` @@ -531,8 +513,6 @@ type MachineDeploymentV1Beta2Status struct { UpToDateReplicas *int32 `json:"upToDateReplicas,omitempty"` } -// ANCHOR_END: MachineDeploymentStatus - // MachineDeploymentPhase indicates the progress of the machine deployment. type MachineDeploymentPhase string @@ -575,7 +555,7 @@ func (md *MachineDeploymentStatus) GetTypedPhase() MachineDeploymentPhase { // +kubebuilder:object:root=true // +kubebuilder:resource:path=machinedeployments,shortName=md,scope=Namespaced,categories=cluster-api -// +kubebuilder:storageversion +// +kubebuilder:deprecatedversion // +kubebuilder:subresource:status // +kubebuilder:subresource:scale:specpath=.spec.replicas,statuspath=.status.replicas,selectorpath=.status.selector // +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinedrainrules_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinedrainrules_types.go similarity index 99% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinedrainrules_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinedrainrules_types.go index ac9aeb415e01..ff653dca0568 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinedrainrules_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinedrainrules_types.go @@ -196,7 +196,7 @@ type MachineDrainRulePodSelector struct { // +kubebuilder:object:root=true // +kubebuilder:resource:path=machinedrainrules,scope=Namespaced,categories=cluster-api -// +kubebuilder:storageversion +// +kubebuilder:deprecatedversion // +kubebuilder:printcolumn:name="Behavior",type="string",JSONPath=".spec.drain.behavior",description="Drain behavior" // +kubebuilder:printcolumn:name="Order",type="string",JSONPath=".spec.drain.order",description="Drain order" // +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of the MachineDrainRule" diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinehealthcheck_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinehealthcheck_types.go similarity index 97% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinehealthcheck_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinehealthcheck_types.go index 0646bad1169c..c8e4d27046a1 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machinehealthcheck_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinehealthcheck_types.go @@ -47,8 +47,6 @@ var ( DefaultNodeStartupTimeout = metav1.Duration{Duration: 10 * time.Minute} ) -// ANCHOR: MachineHealthCheckSpec - // MachineHealthCheckSpec defines the desired state of MachineHealthCheck. type MachineHealthCheckSpec struct { // clusterName is the name of the Cluster this object belongs to. @@ -118,10 +116,6 @@ type MachineHealthCheckSpec struct { RemediationTemplate *corev1.ObjectReference `json:"remediationTemplate,omitempty"` } -// ANCHOR_END: MachineHealthCHeckSpec - -// ANCHOR: UnhealthyCondition - // UnhealthyCondition represents a Node condition type and value with a timeout // specified as a duration. When the named condition has been in the given // status for at least the timeout value, a node is considered unhealthy. @@ -146,10 +140,6 @@ type UnhealthyCondition struct { Timeout metav1.Duration `json:"timeout"` } -// ANCHOR_END: UnhealthyCondition - -// ANCHOR: MachineHealthCheckStatus - // MachineHealthCheckStatus defines the observed state of MachineHealthCheck. type MachineHealthCheckStatus struct { // expectedMachines is the total number of machines counted by this machine health check @@ -200,11 +190,9 @@ type MachineHealthCheckV1Beta2Status struct { Conditions []metav1.Condition `json:"conditions,omitempty"` } -// ANCHOR_END: MachineHealthCheckStatus - // +kubebuilder:object:root=true // +kubebuilder:resource:path=machinehealthchecks,shortName=mhc;mhcs,scope=Namespaced,categories=cluster-api -// +kubebuilder:storageversion +// +kubebuilder:deprecatedversion // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" // +kubebuilder:printcolumn:name="ExpectedMachines",type="integer",JSONPath=".status.expectedMachines",description="Number of machines currently monitored" diff --git a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/machinepool_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinepool_types.go similarity index 80% rename from vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/machinepool_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinepool_types.go index be97236182d4..5ecd8fa227c9 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/machinepool_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machinepool_types.go @@ -20,7 +20,6 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" capierrors "sigs.k8s.io/cluster-api/errors" ) @@ -29,7 +28,41 @@ const ( MachinePoolFinalizer = "machinepool.cluster.x-k8s.io" ) -// ANCHOR: MachinePoolSpec +/* +NOTE: we are commenting const for MachinePool's V1Beta2 conditions and reasons because not yet implemented for the 1.9 CAPI release. +However, we are keeping the v1beta2 struct in the MachinePool struct because the code that will collect conditions and replica +counters at cluster level is already implemented. + +// Conditions that will be used for the MachinePool object in v1Beta2 API version. +const ( + // MachinePoolAvailableV1Beta2Condition is true when InfrastructureReady and available replicas >= desired replicas. + MachinePoolAvailableV1Beta2Condition = clusterv1beta1.AvailableV1Beta2Condition + + // MachinePoolBootstrapConfigReadyV1Beta2Condition mirrors the corresponding condition from the MachinePool's BootstrapConfig resource. + MachinePoolBootstrapConfigReadyV1Beta2Condition = clusterv1beta1.BootstrapConfigReadyV1Beta2Condition + + // MachinePoolInfrastructureReadyV1Beta2Condition mirrors the corresponding condition from the MachinePool's Infrastructure resource. + MachinePoolInfrastructureReadyV1Beta2Condition = clusterv1beta1.InfrastructureReadyV1Beta2Condition + + // MachinePoolMachinesReadyV1Beta2Condition surfaces detail of issues on the controlled machines, if any. + MachinePoolMachinesReadyV1Beta2Condition = clusterv1beta1.MachinesReadyV1Beta2Condition + + // MachinePoolMachinesUpToDateV1Beta2Condition surfaces details of controlled machines not up to date, if any. + MachinePoolMachinesUpToDateV1Beta2Condition = clusterv1beta1.MachinesUpToDateV1Beta2Condition + + // MachinePoolScalingUpV1Beta2Condition is true if available replicas < desired replicas. + MachinePoolScalingUpV1Beta2Condition = clusterv1beta1.ScalingUpV1Beta2Condition + + // MachinePoolScalingDownV1Beta2Condition is true if replicas > desired replicas. + MachinePoolScalingDownV1Beta2Condition = clusterv1beta1.ScalingDownV1Beta2Condition + + // MachinePoolRemediatingV1Beta2Condition surfaces details about ongoing remediation of the controlled machines, if any. + MachinePoolRemediatingV1Beta2Condition = clusterv1beta1.RemediatingV1Beta2Condition + + // MachinePoolDeletingV1Beta2Condition surfaces details about ongoing deletion of the controlled machines. + MachinePoolDeletingV1Beta2Condition = clusterv1beta1.DeletingV1Beta2Condition +). +*/ // MachinePoolSpec defines the desired state of MachinePool. type MachinePoolSpec struct { @@ -46,7 +79,7 @@ type MachinePoolSpec struct { // template describes the machines that will be created. // +required - Template clusterv1.MachineTemplateSpec `json:"template"` + Template MachineTemplateSpec `json:"template"` // minReadySeconds is the minimum number of seconds for which a newly created machine instances should // be ready. @@ -71,10 +104,6 @@ type MachinePoolSpec struct { FailureDomains []string `json:"failureDomains,omitempty"` } -// ANCHOR_END: MachinePoolSpec - -// ANCHOR: MachinePoolStatus - // MachinePoolStatus defines the observed state of MachinePool. type MachinePoolStatus struct { // nodeRefs will point to the corresponding Nodes if it they exist. @@ -100,7 +129,7 @@ type MachinePoolStatus struct { // be machine instances that are running but not yet available or machine instances // that still have not been created. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional UnavailableReplicas int32 `json:"unavailableReplicas,omitempty"` @@ -108,7 +137,7 @@ type MachinePoolStatus struct { // failureReason indicates that there is a problem reconciling the state, and // will be set to a token value suitable for programmatic interpretation. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional FailureReason *capierrors.MachinePoolStatusFailure `json:"failureReason,omitempty"` @@ -116,7 +145,7 @@ type MachinePoolStatus struct { // failureMessage indicates that there is a problem reconciling the state, // and will be set to a descriptive error message. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional // +kubebuilder:validation:MinLength=1 @@ -142,7 +171,7 @@ type MachinePoolStatus struct { // conditions define the current service state of the MachinePool. // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` + Conditions Conditions `json:"conditions,omitempty"` // v1beta2 groups all the fields that will be added or modified in MachinePool's status with the V1Beta2 version. // +optional @@ -174,8 +203,6 @@ type MachinePoolV1Beta2Status struct { UpToDateReplicas *int32 `json:"upToDateReplicas,omitempty"` } -// ANCHOR_END: MachinePoolStatus - // MachinePoolPhase is a string representation of a MachinePool Phase. // // This type is a high-level indicator of the status of the MachinePool as it is provisioned, @@ -260,7 +287,7 @@ func (m *MachinePoolStatus) GetTypedPhase() MachinePoolPhase { // +kubebuilder:resource:path=machinepools,shortName=mp,scope=Namespaced,categories=cluster-api // +kubebuilder:subresource:status // +kubebuilder:subresource:scale:specpath=.spec.replicas,statuspath=.status.replicas -// +kubebuilder:storageversion +// +kubebuilder:deprecatedversion // +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" // +kubebuilder:printcolumn:name="Desired",type=integer,JSONPath=".spec.replicas",description="Total number of machines desired by this MachinePool",priority=10 // +kubebuilder:printcolumn:name="Replicas",type="string",JSONPath=".status.replicas",description="MachinePool replicas count" @@ -286,12 +313,12 @@ type MachinePool struct { } // GetConditions returns the set of conditions for this object. -func (m *MachinePool) GetConditions() clusterv1.Conditions { +func (m *MachinePool) GetConditions() Conditions { return m.Status.Conditions } // SetConditions sets the conditions on this object. -func (m *MachinePool) SetConditions(conditions clusterv1.Conditions) { +func (m *MachinePool) SetConditions(conditions Conditions) { m.Status.Conditions = conditions } diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machineset_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machineset_types.go similarity index 96% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/machineset_types.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machineset_types.go index cf52f70a1680..e302d020d3ec 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/machineset_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/machineset_types.go @@ -35,8 +35,6 @@ const ( MachineSetFinalizer = "cluster.x-k8s.io/machineset" ) -// ANCHOR: MachineSetSpec - // MachineSetSpec defines the desired state of MachineSet. type MachineSetSpec struct { // clusterName is the name of the Cluster this object belongs to. @@ -233,10 +231,6 @@ const ( MachineSetDeletingInternalErrorV1Beta2Reason = InternalErrorV1Beta2Reason ) -// ANCHOR_END: MachineSetSpec - -// ANCHOR: MachineTemplateSpec - // MachineTemplateSpec describes the data needed to create a Machine from a template. type MachineTemplateSpec struct { // metadata is the standard object's metadata. @@ -250,8 +244,6 @@ type MachineTemplateSpec struct { Spec MachineSpec `json:"spec,omitempty"` } -// ANCHOR_END: MachineTemplateSpec - // MachineSetDeletePolicy defines how priority is assigned to nodes to delete when // downscaling a MachineSet. Defaults to "Random". type MachineSetDeletePolicy string @@ -279,8 +271,6 @@ const ( OldestMachineSetDeletePolicy MachineSetDeletePolicy = "Oldest" ) -// ANCHOR: MachineSetStatus - // MachineSetStatus defines the observed state of MachineSet. type MachineSetStatus struct { // selector is the same as the label selector but in the string format to avoid introspection @@ -297,7 +287,7 @@ type MachineSetStatus struct { // fullyLabeledReplicas is the number of replicas that have labels matching the labels of the machine template of the MachineSet. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional FullyLabeledReplicas int32 `json:"fullyLabeledReplicas"` @@ -337,7 +327,7 @@ type MachineSetStatus struct { // can be added as events to the MachineSet object and/or logged in the // controller's output. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional FailureReason *capierrors.MachineSetStatusError `json:"failureReason,omitempty"` @@ -346,7 +336,7 @@ type MachineSetStatus struct { // reconciling the Machine and will contain a more verbose string suitable // for logging and human consumption. // - // Deprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. // // +optional // +kubebuilder:validation:MinLength=1 @@ -386,8 +376,6 @@ type MachineSetV1Beta2Status struct { UpToDateReplicas *int32 `json:"upToDateReplicas,omitempty"` } -// ANCHOR_END: MachineSetStatus - // Validate validates the MachineSet fields. func (m *MachineSet) Validate() field.ErrorList { errors := field.ErrorList{} @@ -413,7 +401,7 @@ func (m *MachineSet) Validate() field.ErrorList { // +kubebuilder:object:root=true // +kubebuilder:resource:path=machinesets,shortName=ms,scope=Namespaced,categories=cluster-api -// +kubebuilder:storageversion +// +kubebuilder:deprecatedversion // +kubebuilder:subresource:status // +kubebuilder:subresource:scale:specpath=.spec.replicas,statuspath=.status.replicas,selectorpath=.status.selector // +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/v1beta2_condition_consts.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/v1beta2_condition_consts.go similarity index 100% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/v1beta2_condition_consts.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/v1beta2_condition_consts.go diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.conversion.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.conversion.go new file mode 100644 index 000000000000..eb54f254dd5a --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.conversion.go @@ -0,0 +1,3728 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by conversion-gen. DO NOT EDIT. + +package v1beta1 + +import ( + unsafe "unsafe" + + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + conversion "k8s.io/apimachinery/pkg/conversion" + runtime "k8s.io/apimachinery/pkg/runtime" + v1beta2 "sigs.k8s.io/cluster-api/api/core/v1beta2" +) + +func init() { + localSchemeBuilder.Register(RegisterConversions) +} + +// RegisterConversions adds conversion functions to the given scheme. +// Public to allow building arbitrary schemes. +func RegisterConversions(s *runtime.Scheme) error { + if err := s.AddGeneratedConversionFunc((*APIEndpoint)(nil), (*v1beta2.APIEndpoint)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_APIEndpoint_To_v1beta2_APIEndpoint(a.(*APIEndpoint), b.(*v1beta2.APIEndpoint), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.APIEndpoint)(nil), (*APIEndpoint)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_APIEndpoint_To_v1beta1_APIEndpoint(a.(*v1beta2.APIEndpoint), b.(*APIEndpoint), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Cluster)(nil), (*v1beta2.Cluster)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Cluster_To_v1beta2_Cluster(a.(*Cluster), b.(*v1beta2.Cluster), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.Cluster)(nil), (*Cluster)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_Cluster_To_v1beta1_Cluster(a.(*v1beta2.Cluster), b.(*Cluster), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ClusterAvailabilityGate)(nil), (*v1beta2.ClusterAvailabilityGate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterAvailabilityGate_To_v1beta2_ClusterAvailabilityGate(a.(*ClusterAvailabilityGate), b.(*v1beta2.ClusterAvailabilityGate), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ClusterAvailabilityGate)(nil), (*ClusterAvailabilityGate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterAvailabilityGate_To_v1beta1_ClusterAvailabilityGate(a.(*v1beta2.ClusterAvailabilityGate), b.(*ClusterAvailabilityGate), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ClusterClass)(nil), (*v1beta2.ClusterClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClass_To_v1beta2_ClusterClass(a.(*ClusterClass), b.(*v1beta2.ClusterClass), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ClusterClassList)(nil), (*v1beta2.ClusterClassList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClassList_To_v1beta2_ClusterClassList(a.(*ClusterClassList), b.(*v1beta2.ClusterClassList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ClusterClassList)(nil), (*ClusterClassList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClassList_To_v1beta1_ClusterClassList(a.(*v1beta2.ClusterClassList), b.(*ClusterClassList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ClusterClassPatch)(nil), (*v1beta2.ClusterClassPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClassPatch_To_v1beta2_ClusterClassPatch(a.(*ClusterClassPatch), b.(*v1beta2.ClusterClassPatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ClusterClassPatch)(nil), (*ClusterClassPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClassPatch_To_v1beta1_ClusterClassPatch(a.(*v1beta2.ClusterClassPatch), b.(*ClusterClassPatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ClusterClassStatusVariable)(nil), (*v1beta2.ClusterClassStatusVariable)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClassStatusVariable_To_v1beta2_ClusterClassStatusVariable(a.(*ClusterClassStatusVariable), b.(*v1beta2.ClusterClassStatusVariable), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ClusterClassStatusVariable)(nil), (*ClusterClassStatusVariable)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClassStatusVariable_To_v1beta1_ClusterClassStatusVariable(a.(*v1beta2.ClusterClassStatusVariable), b.(*ClusterClassStatusVariable), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ClusterClassVariableMetadata)(nil), (*v1beta2.ClusterClassVariableMetadata)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClassVariableMetadata_To_v1beta2_ClusterClassVariableMetadata(a.(*ClusterClassVariableMetadata), b.(*v1beta2.ClusterClassVariableMetadata), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ClusterClassVariableMetadata)(nil), (*ClusterClassVariableMetadata)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClassVariableMetadata_To_v1beta1_ClusterClassVariableMetadata(a.(*v1beta2.ClusterClassVariableMetadata), b.(*ClusterClassVariableMetadata), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ClusterControlPlaneStatus)(nil), (*v1beta2.ClusterControlPlaneStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterControlPlaneStatus_To_v1beta2_ClusterControlPlaneStatus(a.(*ClusterControlPlaneStatus), b.(*v1beta2.ClusterControlPlaneStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ClusterControlPlaneStatus)(nil), (*ClusterControlPlaneStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterControlPlaneStatus_To_v1beta1_ClusterControlPlaneStatus(a.(*v1beta2.ClusterControlPlaneStatus), b.(*ClusterControlPlaneStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ClusterList)(nil), (*v1beta2.ClusterList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterList_To_v1beta2_ClusterList(a.(*ClusterList), b.(*v1beta2.ClusterList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ClusterList)(nil), (*ClusterList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterList_To_v1beta1_ClusterList(a.(*v1beta2.ClusterList), b.(*ClusterList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ClusterVariable)(nil), (*ClusterVariable)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable(a.(*v1beta2.ClusterVariable), b.(*ClusterVariable), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Condition)(nil), (*v1beta2.Condition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Condition_To_v1beta2_Condition(a.(*Condition), b.(*v1beta2.Condition), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.Condition)(nil), (*Condition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_Condition_To_v1beta1_Condition(a.(*v1beta2.Condition), b.(*Condition), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ControlPlaneVariables)(nil), (*v1beta2.ControlPlaneVariables)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ControlPlaneVariables_To_v1beta2_ControlPlaneVariables(a.(*ControlPlaneVariables), b.(*v1beta2.ControlPlaneVariables), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ControlPlaneVariables)(nil), (*ControlPlaneVariables)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ControlPlaneVariables_To_v1beta1_ControlPlaneVariables(a.(*v1beta2.ControlPlaneVariables), b.(*ControlPlaneVariables), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*JSONPatch)(nil), (*v1beta2.JSONPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_JSONPatch_To_v1beta2_JSONPatch(a.(*JSONPatch), b.(*v1beta2.JSONPatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.JSONPatch)(nil), (*JSONPatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_JSONPatch_To_v1beta1_JSONPatch(a.(*v1beta2.JSONPatch), b.(*JSONPatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*JSONPatchValue)(nil), (*v1beta2.JSONPatchValue)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_JSONPatchValue_To_v1beta2_JSONPatchValue(a.(*JSONPatchValue), b.(*v1beta2.JSONPatchValue), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.JSONPatchValue)(nil), (*JSONPatchValue)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_JSONPatchValue_To_v1beta1_JSONPatchValue(a.(*v1beta2.JSONPatchValue), b.(*JSONPatchValue), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*Machine)(nil), (*v1beta2.Machine)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Machine_To_v1beta2_Machine(a.(*Machine), b.(*v1beta2.Machine), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.Machine)(nil), (*Machine)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_Machine_To_v1beta1_Machine(a.(*v1beta2.Machine), b.(*Machine), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineAddress)(nil), (*v1beta2.MachineAddress)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineAddress_To_v1beta2_MachineAddress(a.(*MachineAddress), b.(*v1beta2.MachineAddress), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineAddress)(nil), (*MachineAddress)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineAddress_To_v1beta1_MachineAddress(a.(*v1beta2.MachineAddress), b.(*MachineAddress), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDeployment)(nil), (*v1beta2.MachineDeployment)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDeployment_To_v1beta2_MachineDeployment(a.(*MachineDeployment), b.(*v1beta2.MachineDeployment), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDeployment)(nil), (*MachineDeployment)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeployment_To_v1beta1_MachineDeployment(a.(*v1beta2.MachineDeployment), b.(*MachineDeployment), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDeploymentList)(nil), (*v1beta2.MachineDeploymentList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDeploymentList_To_v1beta2_MachineDeploymentList(a.(*MachineDeploymentList), b.(*v1beta2.MachineDeploymentList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDeploymentList)(nil), (*MachineDeploymentList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeploymentList_To_v1beta1_MachineDeploymentList(a.(*v1beta2.MachineDeploymentList), b.(*MachineDeploymentList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDeploymentVariables)(nil), (*v1beta2.MachineDeploymentVariables)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDeploymentVariables_To_v1beta2_MachineDeploymentVariables(a.(*MachineDeploymentVariables), b.(*v1beta2.MachineDeploymentVariables), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDeploymentVariables)(nil), (*MachineDeploymentVariables)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeploymentVariables_To_v1beta1_MachineDeploymentVariables(a.(*v1beta2.MachineDeploymentVariables), b.(*MachineDeploymentVariables), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDrainRule)(nil), (*v1beta2.MachineDrainRule)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDrainRule_To_v1beta2_MachineDrainRule(a.(*MachineDrainRule), b.(*v1beta2.MachineDrainRule), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDrainRule)(nil), (*MachineDrainRule)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDrainRule_To_v1beta1_MachineDrainRule(a.(*v1beta2.MachineDrainRule), b.(*MachineDrainRule), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDrainRuleDrainConfig)(nil), (*v1beta2.MachineDrainRuleDrainConfig)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDrainRuleDrainConfig_To_v1beta2_MachineDrainRuleDrainConfig(a.(*MachineDrainRuleDrainConfig), b.(*v1beta2.MachineDrainRuleDrainConfig), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDrainRuleDrainConfig)(nil), (*MachineDrainRuleDrainConfig)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDrainRuleDrainConfig_To_v1beta1_MachineDrainRuleDrainConfig(a.(*v1beta2.MachineDrainRuleDrainConfig), b.(*MachineDrainRuleDrainConfig), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDrainRuleList)(nil), (*v1beta2.MachineDrainRuleList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDrainRuleList_To_v1beta2_MachineDrainRuleList(a.(*MachineDrainRuleList), b.(*v1beta2.MachineDrainRuleList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDrainRuleList)(nil), (*MachineDrainRuleList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDrainRuleList_To_v1beta1_MachineDrainRuleList(a.(*v1beta2.MachineDrainRuleList), b.(*MachineDrainRuleList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDrainRuleMachineSelector)(nil), (*v1beta2.MachineDrainRuleMachineSelector)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDrainRuleMachineSelector_To_v1beta2_MachineDrainRuleMachineSelector(a.(*MachineDrainRuleMachineSelector), b.(*v1beta2.MachineDrainRuleMachineSelector), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDrainRuleMachineSelector)(nil), (*MachineDrainRuleMachineSelector)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDrainRuleMachineSelector_To_v1beta1_MachineDrainRuleMachineSelector(a.(*v1beta2.MachineDrainRuleMachineSelector), b.(*MachineDrainRuleMachineSelector), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDrainRulePodSelector)(nil), (*v1beta2.MachineDrainRulePodSelector)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDrainRulePodSelector_To_v1beta2_MachineDrainRulePodSelector(a.(*MachineDrainRulePodSelector), b.(*v1beta2.MachineDrainRulePodSelector), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDrainRulePodSelector)(nil), (*MachineDrainRulePodSelector)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDrainRulePodSelector_To_v1beta1_MachineDrainRulePodSelector(a.(*v1beta2.MachineDrainRulePodSelector), b.(*MachineDrainRulePodSelector), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineDrainRuleSpec)(nil), (*v1beta2.MachineDrainRuleSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDrainRuleSpec_To_v1beta2_MachineDrainRuleSpec(a.(*MachineDrainRuleSpec), b.(*v1beta2.MachineDrainRuleSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineDrainRuleSpec)(nil), (*MachineDrainRuleSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDrainRuleSpec_To_v1beta1_MachineDrainRuleSpec(a.(*v1beta2.MachineDrainRuleSpec), b.(*MachineDrainRuleSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineHealthCheck)(nil), (*v1beta2.MachineHealthCheck)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineHealthCheck_To_v1beta2_MachineHealthCheck(a.(*MachineHealthCheck), b.(*v1beta2.MachineHealthCheck), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineHealthCheck)(nil), (*MachineHealthCheck)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineHealthCheck_To_v1beta1_MachineHealthCheck(a.(*v1beta2.MachineHealthCheck), b.(*MachineHealthCheck), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineHealthCheckList)(nil), (*v1beta2.MachineHealthCheckList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineHealthCheckList_To_v1beta2_MachineHealthCheckList(a.(*MachineHealthCheckList), b.(*v1beta2.MachineHealthCheckList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineHealthCheckList)(nil), (*MachineHealthCheckList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineHealthCheckList_To_v1beta1_MachineHealthCheckList(a.(*v1beta2.MachineHealthCheckList), b.(*MachineHealthCheckList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineList)(nil), (*v1beta2.MachineList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineList_To_v1beta2_MachineList(a.(*MachineList), b.(*v1beta2.MachineList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineList)(nil), (*MachineList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineList_To_v1beta1_MachineList(a.(*v1beta2.MachineList), b.(*MachineList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachinePool)(nil), (*v1beta2.MachinePool)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachinePool_To_v1beta2_MachinePool(a.(*MachinePool), b.(*v1beta2.MachinePool), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachinePool)(nil), (*MachinePool)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePool_To_v1beta1_MachinePool(a.(*v1beta2.MachinePool), b.(*MachinePool), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachinePoolList)(nil), (*v1beta2.MachinePoolList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachinePoolList_To_v1beta2_MachinePoolList(a.(*MachinePoolList), b.(*v1beta2.MachinePoolList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachinePoolList)(nil), (*MachinePoolList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePoolList_To_v1beta1_MachinePoolList(a.(*v1beta2.MachinePoolList), b.(*MachinePoolList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachinePoolSpec)(nil), (*MachinePoolSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePoolSpec_To_v1beta1_MachinePoolSpec(a.(*v1beta2.MachinePoolSpec), b.(*MachinePoolSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachinePoolVariables)(nil), (*v1beta2.MachinePoolVariables)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachinePoolVariables_To_v1beta2_MachinePoolVariables(a.(*MachinePoolVariables), b.(*v1beta2.MachinePoolVariables), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachinePoolVariables)(nil), (*MachinePoolVariables)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePoolVariables_To_v1beta1_MachinePoolVariables(a.(*v1beta2.MachinePoolVariables), b.(*MachinePoolVariables), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineReadinessGate)(nil), (*v1beta2.MachineReadinessGate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineReadinessGate_To_v1beta2_MachineReadinessGate(a.(*MachineReadinessGate), b.(*v1beta2.MachineReadinessGate), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineReadinessGate)(nil), (*MachineReadinessGate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineReadinessGate_To_v1beta1_MachineReadinessGate(a.(*v1beta2.MachineReadinessGate), b.(*MachineReadinessGate), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineSet)(nil), (*v1beta2.MachineSet)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineSet_To_v1beta2_MachineSet(a.(*MachineSet), b.(*v1beta2.MachineSet), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineSet)(nil), (*MachineSet)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineSet_To_v1beta1_MachineSet(a.(*v1beta2.MachineSet), b.(*MachineSet), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineSetList)(nil), (*v1beta2.MachineSetList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineSetList_To_v1beta2_MachineSetList(a.(*MachineSetList), b.(*v1beta2.MachineSetList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineSetList)(nil), (*MachineSetList)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineSetList_To_v1beta1_MachineSetList(a.(*v1beta2.MachineSetList), b.(*MachineSetList), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*MachineTemplateSpec)(nil), (*v1beta2.MachineTemplateSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineTemplateSpec_To_v1beta2_MachineTemplateSpec(a.(*MachineTemplateSpec), b.(*v1beta2.MachineTemplateSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.MachineTemplateSpec)(nil), (*MachineTemplateSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineTemplateSpec_To_v1beta1_MachineTemplateSpec(a.(*v1beta2.MachineTemplateSpec), b.(*MachineTemplateSpec), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*NetworkRanges)(nil), (*v1beta2.NetworkRanges)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_NetworkRanges_To_v1beta2_NetworkRanges(a.(*NetworkRanges), b.(*v1beta2.NetworkRanges), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.NetworkRanges)(nil), (*NetworkRanges)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_NetworkRanges_To_v1beta1_NetworkRanges(a.(*v1beta2.NetworkRanges), b.(*NetworkRanges), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ObjectMeta)(nil), (*v1beta2.ObjectMeta)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(a.(*ObjectMeta), b.(*v1beta2.ObjectMeta), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ObjectMeta)(nil), (*ObjectMeta)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(a.(*v1beta2.ObjectMeta), b.(*ObjectMeta), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*PatchDefinition)(nil), (*v1beta2.PatchDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_PatchDefinition_To_v1beta2_PatchDefinition(a.(*PatchDefinition), b.(*v1beta2.PatchDefinition), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.PatchDefinition)(nil), (*PatchDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_PatchDefinition_To_v1beta1_PatchDefinition(a.(*v1beta2.PatchDefinition), b.(*PatchDefinition), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*PatchSelector)(nil), (*v1beta2.PatchSelector)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_PatchSelector_To_v1beta2_PatchSelector(a.(*PatchSelector), b.(*v1beta2.PatchSelector), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.PatchSelector)(nil), (*PatchSelector)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_PatchSelector_To_v1beta1_PatchSelector(a.(*v1beta2.PatchSelector), b.(*PatchSelector), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*PatchSelectorMatch)(nil), (*v1beta2.PatchSelectorMatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_PatchSelectorMatch_To_v1beta2_PatchSelectorMatch(a.(*PatchSelectorMatch), b.(*v1beta2.PatchSelectorMatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.PatchSelectorMatch)(nil), (*PatchSelectorMatch)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_PatchSelectorMatch_To_v1beta1_PatchSelectorMatch(a.(*v1beta2.PatchSelectorMatch), b.(*PatchSelectorMatch), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*PatchSelectorMatchMachineDeploymentClass)(nil), (*v1beta2.PatchSelectorMatchMachineDeploymentClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_PatchSelectorMatchMachineDeploymentClass_To_v1beta2_PatchSelectorMatchMachineDeploymentClass(a.(*PatchSelectorMatchMachineDeploymentClass), b.(*v1beta2.PatchSelectorMatchMachineDeploymentClass), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.PatchSelectorMatchMachineDeploymentClass)(nil), (*PatchSelectorMatchMachineDeploymentClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_PatchSelectorMatchMachineDeploymentClass_To_v1beta1_PatchSelectorMatchMachineDeploymentClass(a.(*v1beta2.PatchSelectorMatchMachineDeploymentClass), b.(*PatchSelectorMatchMachineDeploymentClass), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*PatchSelectorMatchMachinePoolClass)(nil), (*v1beta2.PatchSelectorMatchMachinePoolClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_PatchSelectorMatchMachinePoolClass_To_v1beta2_PatchSelectorMatchMachinePoolClass(a.(*PatchSelectorMatchMachinePoolClass), b.(*v1beta2.PatchSelectorMatchMachinePoolClass), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.PatchSelectorMatchMachinePoolClass)(nil), (*PatchSelectorMatchMachinePoolClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_PatchSelectorMatchMachinePoolClass_To_v1beta1_PatchSelectorMatchMachinePoolClass(a.(*v1beta2.PatchSelectorMatchMachinePoolClass), b.(*PatchSelectorMatchMachinePoolClass), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*ValidationRule)(nil), (*v1beta2.ValidationRule)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ValidationRule_To_v1beta2_ValidationRule(a.(*ValidationRule), b.(*v1beta2.ValidationRule), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.ValidationRule)(nil), (*ValidationRule)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ValidationRule_To_v1beta1_ValidationRule(a.(*v1beta2.ValidationRule), b.(*ValidationRule), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*VariableSchema)(nil), (*v1beta2.VariableSchema)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_VariableSchema_To_v1beta2_VariableSchema(a.(*VariableSchema), b.(*v1beta2.VariableSchema), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.VariableSchema)(nil), (*VariableSchema)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_VariableSchema_To_v1beta1_VariableSchema(a.(*v1beta2.VariableSchema), b.(*VariableSchema), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*VariableSchemaMetadata)(nil), (*v1beta2.VariableSchemaMetadata)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_VariableSchemaMetadata_To_v1beta2_VariableSchemaMetadata(a.(*VariableSchemaMetadata), b.(*v1beta2.VariableSchemaMetadata), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.VariableSchemaMetadata)(nil), (*VariableSchemaMetadata)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_VariableSchemaMetadata_To_v1beta1_VariableSchemaMetadata(a.(*v1beta2.VariableSchemaMetadata), b.(*VariableSchemaMetadata), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*WorkersClass)(nil), (*v1beta2.WorkersClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_WorkersClass_To_v1beta2_WorkersClass(a.(*WorkersClass), b.(*v1beta2.WorkersClass), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.WorkersClass)(nil), (*WorkersClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_WorkersClass_To_v1beta1_WorkersClass(a.(*v1beta2.WorkersClass), b.(*WorkersClass), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*WorkersStatus)(nil), (*v1beta2.WorkersStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_WorkersStatus_To_v1beta2_WorkersStatus(a.(*WorkersStatus), b.(*v1beta2.WorkersStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.WorkersStatus)(nil), (*WorkersStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_WorkersStatus_To_v1beta1_WorkersStatus(a.(*v1beta2.WorkersStatus), b.(*WorkersStatus), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*WorkersTopology)(nil), (*v1beta2.WorkersTopology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_WorkersTopology_To_v1beta2_WorkersTopology(a.(*WorkersTopology), b.(*v1beta2.WorkersTopology), scope) + }); err != nil { + return err + } + if err := s.AddGeneratedConversionFunc((*v1beta2.WorkersTopology)(nil), (*WorkersTopology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_WorkersTopology_To_v1beta1_WorkersTopology(a.(*v1beta2.WorkersTopology), b.(*WorkersTopology), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1.Condition)(nil), (*Condition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_Condition_To_v1beta1_Condition(a.(*v1.Condition), b.(*Condition), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*corev1.ObjectReference)(nil), (*v1beta2.ContractVersionedObjectReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_ObjectReference_To_v1beta2_ContractVersionedObjectReference(a.(*corev1.ObjectReference), b.(*v1beta2.ContractVersionedObjectReference), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*corev1.ObjectReference)(nil), (*v1beta2.MachineHealthCheckRemediationTemplateReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_ObjectReference_To_v1beta2_MachineHealthCheckRemediationTemplateReference(a.(*corev1.ObjectReference), b.(*v1beta2.MachineHealthCheckRemediationTemplateReference), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*corev1.ObjectReference)(nil), (*v1beta2.MachineNodeReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_ObjectReference_To_v1beta2_MachineNodeReference(a.(*corev1.ObjectReference), b.(*v1beta2.MachineNodeReference), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*Bootstrap)(nil), (*v1beta2.Bootstrap)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Bootstrap_To_v1beta2_Bootstrap(a.(*Bootstrap), b.(*v1beta2.Bootstrap), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClusterClassSpec)(nil), (*v1beta2.ClusterClassSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClassSpec_To_v1beta2_ClusterClassSpec(a.(*ClusterClassSpec), b.(*v1beta2.ClusterClassSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClusterClassStatusVariableDefinition)(nil), (*v1beta2.ClusterClassStatusVariableDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClassStatusVariableDefinition_To_v1beta2_ClusterClassStatusVariableDefinition(a.(*ClusterClassStatusVariableDefinition), b.(*v1beta2.ClusterClassStatusVariableDefinition), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClusterClassStatus)(nil), (*v1beta2.ClusterClassStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClassStatus_To_v1beta2_ClusterClassStatus(a.(*ClusterClassStatus), b.(*v1beta2.ClusterClassStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClusterClassVariable)(nil), (*v1beta2.ClusterClassVariable)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterClassVariable_To_v1beta2_ClusterClassVariable(a.(*ClusterClassVariable), b.(*v1beta2.ClusterClassVariable), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClusterNetwork)(nil), (*v1beta2.ClusterNetwork)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterNetwork_To_v1beta2_ClusterNetwork(a.(*ClusterNetwork), b.(*v1beta2.ClusterNetwork), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClusterSpec)(nil), (*v1beta2.ClusterSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterSpec_To_v1beta2_ClusterSpec(a.(*ClusterSpec), b.(*v1beta2.ClusterSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClusterStatus)(nil), (*v1beta2.ClusterStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterStatus_To_v1beta2_ClusterStatus(a.(*ClusterStatus), b.(*v1beta2.ClusterStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ClusterVariable)(nil), (*v1beta2.ClusterVariable)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ClusterVariable_To_v1beta2_ClusterVariable(a.(*ClusterVariable), b.(*v1beta2.ClusterVariable), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*Condition)(nil), (*v1.Condition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Condition_To_v1_Condition(a.(*Condition), b.(*v1.Condition), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ControlPlaneClass)(nil), (*v1beta2.ControlPlaneClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ControlPlaneClass_To_v1beta2_ControlPlaneClass(a.(*ControlPlaneClass), b.(*v1beta2.ControlPlaneClass), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ControlPlaneTopology)(nil), (*v1beta2.ControlPlaneTopology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ControlPlaneTopology_To_v1beta2_ControlPlaneTopology(a.(*ControlPlaneTopology), b.(*v1beta2.ControlPlaneTopology), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*ExternalPatchDefinition)(nil), (*v1beta2.ExternalPatchDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_ExternalPatchDefinition_To_v1beta2_ExternalPatchDefinition(a.(*ExternalPatchDefinition), b.(*v1beta2.ExternalPatchDefinition), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*JSONSchemaProps)(nil), (*v1beta2.JSONSchemaProps)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(a.(*JSONSchemaProps), b.(*v1beta2.JSONSchemaProps), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*LocalObjectTemplate)(nil), (*v1beta2.ControlPlaneClassMachineInfrastructureTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_LocalObjectTemplate_To_v1beta2_ControlPlaneClassMachineInfrastructureTemplate(a.(*LocalObjectTemplate), b.(*v1beta2.ControlPlaneClassMachineInfrastructureTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*LocalObjectTemplate)(nil), (*v1beta2.InfrastructureClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_LocalObjectTemplate_To_v1beta2_InfrastructureClass(a.(*LocalObjectTemplate), b.(*v1beta2.InfrastructureClass), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*LocalObjectTemplate)(nil), (*v1beta2.MachineDeploymentClassBootstrapTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachineDeploymentClassBootstrapTemplate(a.(*LocalObjectTemplate), b.(*v1beta2.MachineDeploymentClassBootstrapTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*LocalObjectTemplate)(nil), (*v1beta2.MachineDeploymentClassInfrastructureTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachineDeploymentClassInfrastructureTemplate(a.(*LocalObjectTemplate), b.(*v1beta2.MachineDeploymentClassInfrastructureTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*LocalObjectTemplate)(nil), (*v1beta2.MachinePoolClassBootstrapTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachinePoolClassBootstrapTemplate(a.(*LocalObjectTemplate), b.(*v1beta2.MachinePoolClassBootstrapTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*LocalObjectTemplate)(nil), (*v1beta2.MachinePoolClassInfrastructureTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_LocalObjectTemplate_To_v1beta2_MachinePoolClassInfrastructureTemplate(a.(*LocalObjectTemplate), b.(*v1beta2.MachinePoolClassInfrastructureTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineDeletionStatus)(nil), (*v1beta2.MachineDeletionStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDeletionStatus_To_v1beta2_MachineDeletionStatus(a.(*MachineDeletionStatus), b.(*v1beta2.MachineDeletionStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineDeploymentClass)(nil), (*v1beta2.MachineDeploymentClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDeploymentClass_To_v1beta2_MachineDeploymentClass(a.(*MachineDeploymentClass), b.(*v1beta2.MachineDeploymentClass), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineDeploymentSpec)(nil), (*v1beta2.MachineDeploymentSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDeploymentSpec_To_v1beta2_MachineDeploymentSpec(a.(*MachineDeploymentSpec), b.(*v1beta2.MachineDeploymentSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineDeploymentStatus)(nil), (*v1beta2.MachineDeploymentStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDeploymentStatus_To_v1beta2_MachineDeploymentStatus(a.(*MachineDeploymentStatus), b.(*v1beta2.MachineDeploymentStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineDeploymentTopology)(nil), (*v1beta2.MachineDeploymentTopology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineDeploymentTopology_To_v1beta2_MachineDeploymentTopology(a.(*MachineDeploymentTopology), b.(*v1beta2.MachineDeploymentTopology), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineHealthCheckSpec)(nil), (*v1beta2.MachineHealthCheckSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineHealthCheckSpec_To_v1beta2_MachineHealthCheckSpec(a.(*MachineHealthCheckSpec), b.(*v1beta2.MachineHealthCheckSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineHealthCheckStatus)(nil), (*v1beta2.MachineHealthCheckStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineHealthCheckStatus_To_v1beta2_MachineHealthCheckStatus(a.(*MachineHealthCheckStatus), b.(*v1beta2.MachineHealthCheckStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachinePoolClass)(nil), (*v1beta2.MachinePoolClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachinePoolClass_To_v1beta2_MachinePoolClass(a.(*MachinePoolClass), b.(*v1beta2.MachinePoolClass), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachinePoolSpec)(nil), (*v1beta2.MachinePoolSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachinePoolSpec_To_v1beta2_MachinePoolSpec(a.(*MachinePoolSpec), b.(*v1beta2.MachinePoolSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachinePoolStatus)(nil), (*v1beta2.MachinePoolStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachinePoolStatus_To_v1beta2_MachinePoolStatus(a.(*MachinePoolStatus), b.(*v1beta2.MachinePoolStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachinePoolTopology)(nil), (*v1beta2.MachinePoolTopology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachinePoolTopology_To_v1beta2_MachinePoolTopology(a.(*MachinePoolTopology), b.(*v1beta2.MachinePoolTopology), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineSetSpec)(nil), (*v1beta2.MachineSetSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineSetSpec_To_v1beta2_MachineSetSpec(a.(*MachineSetSpec), b.(*v1beta2.MachineSetSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineSetStatus)(nil), (*v1beta2.MachineSetStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineSetStatus_To_v1beta2_MachineSetStatus(a.(*MachineSetStatus), b.(*v1beta2.MachineSetStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineSpec)(nil), (*v1beta2.MachineSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineSpec_To_v1beta2_MachineSpec(a.(*MachineSpec), b.(*v1beta2.MachineSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*MachineStatus)(nil), (*v1beta2.MachineStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_MachineStatus_To_v1beta2_MachineStatus(a.(*MachineStatus), b.(*v1beta2.MachineStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*Topology)(nil), (*v1beta2.Topology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta1_Topology_To_v1beta2_Topology(a.(*Topology), b.(*v1beta2.Topology), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.Bootstrap)(nil), (*Bootstrap)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_Bootstrap_To_v1beta1_Bootstrap(a.(*v1beta2.Bootstrap), b.(*Bootstrap), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ClusterClassSpec)(nil), (*ClusterClassSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClassSpec_To_v1beta1_ClusterClassSpec(a.(*v1beta2.ClusterClassSpec), b.(*ClusterClassSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ClusterClassStatusVariableDefinition)(nil), (*ClusterClassStatusVariableDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClassStatusVariableDefinition_To_v1beta1_ClusterClassStatusVariableDefinition(a.(*v1beta2.ClusterClassStatusVariableDefinition), b.(*ClusterClassStatusVariableDefinition), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ClusterClassStatus)(nil), (*ClusterClassStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClassStatus_To_v1beta1_ClusterClassStatus(a.(*v1beta2.ClusterClassStatus), b.(*ClusterClassStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ClusterClassVariable)(nil), (*ClusterClassVariable)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClassVariable_To_v1beta1_ClusterClassVariable(a.(*v1beta2.ClusterClassVariable), b.(*ClusterClassVariable), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ClusterClass)(nil), (*ClusterClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterClass_To_v1beta1_ClusterClass(a.(*v1beta2.ClusterClass), b.(*ClusterClass), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ClusterNetwork)(nil), (*ClusterNetwork)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterNetwork_To_v1beta1_ClusterNetwork(a.(*v1beta2.ClusterNetwork), b.(*ClusterNetwork), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ClusterSpec)(nil), (*ClusterSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterSpec_To_v1beta1_ClusterSpec(a.(*v1beta2.ClusterSpec), b.(*ClusterSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ClusterStatus)(nil), (*ClusterStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ClusterStatus_To_v1beta1_ClusterStatus(a.(*v1beta2.ClusterStatus), b.(*ClusterStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ContractVersionedObjectReference)(nil), (*corev1.ObjectReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ContractVersionedObjectReference_To_v1_ObjectReference(a.(*v1beta2.ContractVersionedObjectReference), b.(*corev1.ObjectReference), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ControlPlaneClassMachineInfrastructureTemplate)(nil), (*LocalObjectTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ControlPlaneClassMachineInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(a.(*v1beta2.ControlPlaneClassMachineInfrastructureTemplate), b.(*LocalObjectTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ControlPlaneClass)(nil), (*ControlPlaneClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ControlPlaneClass_To_v1beta1_ControlPlaneClass(a.(*v1beta2.ControlPlaneClass), b.(*ControlPlaneClass), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ControlPlaneTopology)(nil), (*ControlPlaneTopology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ControlPlaneTopology_To_v1beta1_ControlPlaneTopology(a.(*v1beta2.ControlPlaneTopology), b.(*ControlPlaneTopology), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.ExternalPatchDefinition)(nil), (*ExternalPatchDefinition)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_ExternalPatchDefinition_To_v1beta1_ExternalPatchDefinition(a.(*v1beta2.ExternalPatchDefinition), b.(*ExternalPatchDefinition), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.InfrastructureClass)(nil), (*LocalObjectTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_InfrastructureClass_To_v1beta1_LocalObjectTemplate(a.(*v1beta2.InfrastructureClass), b.(*LocalObjectTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.JSONSchemaProps)(nil), (*JSONSchemaProps)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(a.(*v1beta2.JSONSchemaProps), b.(*JSONSchemaProps), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineDeletionStatus)(nil), (*MachineDeletionStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeletionStatus_To_v1beta1_MachineDeletionStatus(a.(*v1beta2.MachineDeletionStatus), b.(*MachineDeletionStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineDeploymentClassBootstrapTemplate)(nil), (*LocalObjectTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeploymentClassBootstrapTemplate_To_v1beta1_LocalObjectTemplate(a.(*v1beta2.MachineDeploymentClassBootstrapTemplate), b.(*LocalObjectTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineDeploymentClassInfrastructureTemplate)(nil), (*LocalObjectTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeploymentClassInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(a.(*v1beta2.MachineDeploymentClassInfrastructureTemplate), b.(*LocalObjectTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineDeploymentClass)(nil), (*MachineDeploymentClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeploymentClass_To_v1beta1_MachineDeploymentClass(a.(*v1beta2.MachineDeploymentClass), b.(*MachineDeploymentClass), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineDeploymentSpec)(nil), (*MachineDeploymentSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeploymentSpec_To_v1beta1_MachineDeploymentSpec(a.(*v1beta2.MachineDeploymentSpec), b.(*MachineDeploymentSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineDeploymentStatus)(nil), (*MachineDeploymentStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeploymentStatus_To_v1beta1_MachineDeploymentStatus(a.(*v1beta2.MachineDeploymentStatus), b.(*MachineDeploymentStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineDeploymentTopology)(nil), (*MachineDeploymentTopology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineDeploymentTopology_To_v1beta1_MachineDeploymentTopology(a.(*v1beta2.MachineDeploymentTopology), b.(*MachineDeploymentTopology), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineHealthCheckRemediationTemplateReference)(nil), (*corev1.ObjectReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineHealthCheckRemediationTemplateReference_To_v1_ObjectReference(a.(*v1beta2.MachineHealthCheckRemediationTemplateReference), b.(*corev1.ObjectReference), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineHealthCheckSpec)(nil), (*MachineHealthCheckSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineHealthCheckSpec_To_v1beta1_MachineHealthCheckSpec(a.(*v1beta2.MachineHealthCheckSpec), b.(*MachineHealthCheckSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineHealthCheckStatus)(nil), (*MachineHealthCheckStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineHealthCheckStatus_To_v1beta1_MachineHealthCheckStatus(a.(*v1beta2.MachineHealthCheckStatus), b.(*MachineHealthCheckStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineNodeReference)(nil), (*corev1.ObjectReference)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineNodeReference_To_v1_ObjectReference(a.(*v1beta2.MachineNodeReference), b.(*corev1.ObjectReference), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachinePoolClassBootstrapTemplate)(nil), (*LocalObjectTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePoolClassBootstrapTemplate_To_v1beta1_LocalObjectTemplate(a.(*v1beta2.MachinePoolClassBootstrapTemplate), b.(*LocalObjectTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachinePoolClassInfrastructureTemplate)(nil), (*LocalObjectTemplate)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePoolClassInfrastructureTemplate_To_v1beta1_LocalObjectTemplate(a.(*v1beta2.MachinePoolClassInfrastructureTemplate), b.(*LocalObjectTemplate), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachinePoolClass)(nil), (*MachinePoolClass)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePoolClass_To_v1beta1_MachinePoolClass(a.(*v1beta2.MachinePoolClass), b.(*MachinePoolClass), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachinePoolStatus)(nil), (*MachinePoolStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePoolStatus_To_v1beta1_MachinePoolStatus(a.(*v1beta2.MachinePoolStatus), b.(*MachinePoolStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachinePoolTopology)(nil), (*MachinePoolTopology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachinePoolTopology_To_v1beta1_MachinePoolTopology(a.(*v1beta2.MachinePoolTopology), b.(*MachinePoolTopology), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineSetSpec)(nil), (*MachineSetSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineSetSpec_To_v1beta1_MachineSetSpec(a.(*v1beta2.MachineSetSpec), b.(*MachineSetSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineSetStatus)(nil), (*MachineSetStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineSetStatus_To_v1beta1_MachineSetStatus(a.(*v1beta2.MachineSetStatus), b.(*MachineSetStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineSpec)(nil), (*MachineSpec)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineSpec_To_v1beta1_MachineSpec(a.(*v1beta2.MachineSpec), b.(*MachineSpec), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.MachineStatus)(nil), (*MachineStatus)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_MachineStatus_To_v1beta1_MachineStatus(a.(*v1beta2.MachineStatus), b.(*MachineStatus), scope) + }); err != nil { + return err + } + if err := s.AddConversionFunc((*v1beta2.Topology)(nil), (*Topology)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1beta2_Topology_To_v1beta1_Topology(a.(*v1beta2.Topology), b.(*Topology), scope) + }); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta1_APIEndpoint_To_v1beta2_APIEndpoint(in *APIEndpoint, out *v1beta2.APIEndpoint, s conversion.Scope) error { + out.Host = in.Host + out.Port = in.Port + return nil +} + +// Convert_v1beta1_APIEndpoint_To_v1beta2_APIEndpoint is an autogenerated conversion function. +func Convert_v1beta1_APIEndpoint_To_v1beta2_APIEndpoint(in *APIEndpoint, out *v1beta2.APIEndpoint, s conversion.Scope) error { + return autoConvert_v1beta1_APIEndpoint_To_v1beta2_APIEndpoint(in, out, s) +} + +func autoConvert_v1beta2_APIEndpoint_To_v1beta1_APIEndpoint(in *v1beta2.APIEndpoint, out *APIEndpoint, s conversion.Scope) error { + out.Host = in.Host + out.Port = in.Port + return nil +} + +// Convert_v1beta2_APIEndpoint_To_v1beta1_APIEndpoint is an autogenerated conversion function. +func Convert_v1beta2_APIEndpoint_To_v1beta1_APIEndpoint(in *v1beta2.APIEndpoint, out *APIEndpoint, s conversion.Scope) error { + return autoConvert_v1beta2_APIEndpoint_To_v1beta1_APIEndpoint(in, out, s) +} + +func autoConvert_v1beta1_Bootstrap_To_v1beta2_Bootstrap(in *Bootstrap, out *v1beta2.Bootstrap, s conversion.Scope) error { + // WARNING: in.ConfigRef requires manual conversion: inconvertible types (*k8s.io/api/core/v1.ObjectReference vs sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference) + out.DataSecretName = (*string)(unsafe.Pointer(in.DataSecretName)) + return nil +} + +func autoConvert_v1beta2_Bootstrap_To_v1beta1_Bootstrap(in *v1beta2.Bootstrap, out *Bootstrap, s conversion.Scope) error { + // WARNING: in.ConfigRef requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference vs *k8s.io/api/core/v1.ObjectReference) + out.DataSecretName = (*string)(unsafe.Pointer(in.DataSecretName)) + return nil +} + +func autoConvert_v1beta1_Cluster_To_v1beta2_Cluster(in *Cluster, out *v1beta2.Cluster, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_ClusterSpec_To_v1beta2_ClusterSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta1_ClusterStatus_To_v1beta2_ClusterStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_Cluster_To_v1beta2_Cluster is an autogenerated conversion function. +func Convert_v1beta1_Cluster_To_v1beta2_Cluster(in *Cluster, out *v1beta2.Cluster, s conversion.Scope) error { + return autoConvert_v1beta1_Cluster_To_v1beta2_Cluster(in, out, s) +} + +func autoConvert_v1beta2_Cluster_To_v1beta1_Cluster(in *v1beta2.Cluster, out *Cluster, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta2_ClusterSpec_To_v1beta1_ClusterSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta2_ClusterStatus_To_v1beta1_ClusterStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_Cluster_To_v1beta1_Cluster is an autogenerated conversion function. +func Convert_v1beta2_Cluster_To_v1beta1_Cluster(in *v1beta2.Cluster, out *Cluster, s conversion.Scope) error { + return autoConvert_v1beta2_Cluster_To_v1beta1_Cluster(in, out, s) +} + +func autoConvert_v1beta1_ClusterAvailabilityGate_To_v1beta2_ClusterAvailabilityGate(in *ClusterAvailabilityGate, out *v1beta2.ClusterAvailabilityGate, s conversion.Scope) error { + out.ConditionType = in.ConditionType + out.Polarity = v1beta2.ConditionPolarity(in.Polarity) + return nil +} + +// Convert_v1beta1_ClusterAvailabilityGate_To_v1beta2_ClusterAvailabilityGate is an autogenerated conversion function. +func Convert_v1beta1_ClusterAvailabilityGate_To_v1beta2_ClusterAvailabilityGate(in *ClusterAvailabilityGate, out *v1beta2.ClusterAvailabilityGate, s conversion.Scope) error { + return autoConvert_v1beta1_ClusterAvailabilityGate_To_v1beta2_ClusterAvailabilityGate(in, out, s) +} + +func autoConvert_v1beta2_ClusterAvailabilityGate_To_v1beta1_ClusterAvailabilityGate(in *v1beta2.ClusterAvailabilityGate, out *ClusterAvailabilityGate, s conversion.Scope) error { + out.ConditionType = in.ConditionType + out.Polarity = ConditionPolarity(in.Polarity) + return nil +} + +// Convert_v1beta2_ClusterAvailabilityGate_To_v1beta1_ClusterAvailabilityGate is an autogenerated conversion function. +func Convert_v1beta2_ClusterAvailabilityGate_To_v1beta1_ClusterAvailabilityGate(in *v1beta2.ClusterAvailabilityGate, out *ClusterAvailabilityGate, s conversion.Scope) error { + return autoConvert_v1beta2_ClusterAvailabilityGate_To_v1beta1_ClusterAvailabilityGate(in, out, s) +} + +func autoConvert_v1beta1_ClusterClass_To_v1beta2_ClusterClass(in *ClusterClass, out *v1beta2.ClusterClass, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_ClusterClassSpec_To_v1beta2_ClusterClassSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta1_ClusterClassStatus_To_v1beta2_ClusterClassStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_ClusterClass_To_v1beta2_ClusterClass is an autogenerated conversion function. +func Convert_v1beta1_ClusterClass_To_v1beta2_ClusterClass(in *ClusterClass, out *v1beta2.ClusterClass, s conversion.Scope) error { + return autoConvert_v1beta1_ClusterClass_To_v1beta2_ClusterClass(in, out, s) +} + +func autoConvert_v1beta2_ClusterClass_To_v1beta1_ClusterClass(in *v1beta2.ClusterClass, out *ClusterClass, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta2_ClusterClassSpec_To_v1beta1_ClusterClassSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta2_ClusterClassStatus_To_v1beta1_ClusterClassStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta1_ClusterClassList_To_v1beta2_ClusterClassList(in *ClusterClassList, out *v1beta2.ClusterClassList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]v1beta2.ClusterClass, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterClass_To_v1beta2_ClusterClass(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta1_ClusterClassList_To_v1beta2_ClusterClassList is an autogenerated conversion function. +func Convert_v1beta1_ClusterClassList_To_v1beta2_ClusterClassList(in *ClusterClassList, out *v1beta2.ClusterClassList, s conversion.Scope) error { + return autoConvert_v1beta1_ClusterClassList_To_v1beta2_ClusterClassList(in, out, s) +} + +func autoConvert_v1beta2_ClusterClassList_To_v1beta1_ClusterClassList(in *v1beta2.ClusterClassList, out *ClusterClassList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterClass, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterClass_To_v1beta1_ClusterClass(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta2_ClusterClassList_To_v1beta1_ClusterClassList is an autogenerated conversion function. +func Convert_v1beta2_ClusterClassList_To_v1beta1_ClusterClassList(in *v1beta2.ClusterClassList, out *ClusterClassList, s conversion.Scope) error { + return autoConvert_v1beta2_ClusterClassList_To_v1beta1_ClusterClassList(in, out, s) +} + +func autoConvert_v1beta1_ClusterClassPatch_To_v1beta2_ClusterClassPatch(in *ClusterClassPatch, out *v1beta2.ClusterClassPatch, s conversion.Scope) error { + out.Name = in.Name + out.Description = in.Description + if err := v1.Convert_Pointer_string_To_string(&in.EnabledIf, &out.EnabledIf, s); err != nil { + return err + } + if in.Definitions != nil { + in, out := &in.Definitions, &out.Definitions + *out = make([]v1beta2.PatchDefinition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_PatchDefinition_To_v1beta2_PatchDefinition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Definitions = nil + } + if in.External != nil { + in, out := &in.External, &out.External + *out = new(v1beta2.ExternalPatchDefinition) + if err := Convert_v1beta1_ExternalPatchDefinition_To_v1beta2_ExternalPatchDefinition(*in, *out, s); err != nil { + return err + } + } else { + out.External = nil + } + return nil +} + +// Convert_v1beta1_ClusterClassPatch_To_v1beta2_ClusterClassPatch is an autogenerated conversion function. +func Convert_v1beta1_ClusterClassPatch_To_v1beta2_ClusterClassPatch(in *ClusterClassPatch, out *v1beta2.ClusterClassPatch, s conversion.Scope) error { + return autoConvert_v1beta1_ClusterClassPatch_To_v1beta2_ClusterClassPatch(in, out, s) +} + +func autoConvert_v1beta2_ClusterClassPatch_To_v1beta1_ClusterClassPatch(in *v1beta2.ClusterClassPatch, out *ClusterClassPatch, s conversion.Scope) error { + out.Name = in.Name + out.Description = in.Description + if err := v1.Convert_string_To_Pointer_string(&in.EnabledIf, &out.EnabledIf, s); err != nil { + return err + } + if in.Definitions != nil { + in, out := &in.Definitions, &out.Definitions + *out = make([]PatchDefinition, len(*in)) + for i := range *in { + if err := Convert_v1beta2_PatchDefinition_To_v1beta1_PatchDefinition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Definitions = nil + } + if in.External != nil { + in, out := &in.External, &out.External + *out = new(ExternalPatchDefinition) + if err := Convert_v1beta2_ExternalPatchDefinition_To_v1beta1_ExternalPatchDefinition(*in, *out, s); err != nil { + return err + } + } else { + out.External = nil + } + return nil +} + +// Convert_v1beta2_ClusterClassPatch_To_v1beta1_ClusterClassPatch is an autogenerated conversion function. +func Convert_v1beta2_ClusterClassPatch_To_v1beta1_ClusterClassPatch(in *v1beta2.ClusterClassPatch, out *ClusterClassPatch, s conversion.Scope) error { + return autoConvert_v1beta2_ClusterClassPatch_To_v1beta1_ClusterClassPatch(in, out, s) +} + +func autoConvert_v1beta1_ClusterClassSpec_To_v1beta2_ClusterClassSpec(in *ClusterClassSpec, out *v1beta2.ClusterClassSpec, s conversion.Scope) error { + out.AvailabilityGates = *(*[]v1beta2.ClusterAvailabilityGate)(unsafe.Pointer(&in.AvailabilityGates)) + if err := Convert_v1beta1_LocalObjectTemplate_To_v1beta2_InfrastructureClass(&in.Infrastructure, &out.Infrastructure, s); err != nil { + return err + } + // WARNING: in.InfrastructureNamingStrategy requires manual conversion: does not exist in peer-type + if err := Convert_v1beta1_ControlPlaneClass_To_v1beta2_ControlPlaneClass(&in.ControlPlane, &out.ControlPlane, s); err != nil { + return err + } + if err := Convert_v1beta1_WorkersClass_To_v1beta2_WorkersClass(&in.Workers, &out.Workers, s); err != nil { + return err + } + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]v1beta2.ClusterClassVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterClassVariable_To_v1beta2_ClusterClassVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Variables = nil + } + if in.Patches != nil { + in, out := &in.Patches, &out.Patches + *out = make([]v1beta2.ClusterClassPatch, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterClassPatch_To_v1beta2_ClusterClassPatch(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Patches = nil + } + return nil +} + +func autoConvert_v1beta2_ClusterClassSpec_To_v1beta1_ClusterClassSpec(in *v1beta2.ClusterClassSpec, out *ClusterClassSpec, s conversion.Scope) error { + out.AvailabilityGates = *(*[]ClusterAvailabilityGate)(unsafe.Pointer(&in.AvailabilityGates)) + if err := Convert_v1beta2_InfrastructureClass_To_v1beta1_LocalObjectTemplate(&in.Infrastructure, &out.Infrastructure, s); err != nil { + return err + } + if err := Convert_v1beta2_ControlPlaneClass_To_v1beta1_ControlPlaneClass(&in.ControlPlane, &out.ControlPlane, s); err != nil { + return err + } + if err := Convert_v1beta2_WorkersClass_To_v1beta1_WorkersClass(&in.Workers, &out.Workers, s); err != nil { + return err + } + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]ClusterClassVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterClassVariable_To_v1beta1_ClusterClassVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Variables = nil + } + if in.Patches != nil { + in, out := &in.Patches, &out.Patches + *out = make([]ClusterClassPatch, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterClassPatch_To_v1beta1_ClusterClassPatch(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Patches = nil + } + return nil +} + +func autoConvert_v1beta1_ClusterClassStatus_To_v1beta2_ClusterClassStatus(in *ClusterClassStatus, out *v1beta2.ClusterClassStatus, s conversion.Scope) error { + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]v1beta2.ClusterClassStatusVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterClassStatusVariable_To_v1beta2_ClusterClassStatusVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Variables = nil + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Condition_To_v1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + out.ObservedGeneration = in.ObservedGeneration + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_ClusterClassStatus_To_v1beta1_ClusterClassStatus(in *v1beta2.ClusterClassStatus, out *ClusterClassStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + if err := Convert_v1_Condition_To_v1beta1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]ClusterClassStatusVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterClassStatusVariable_To_v1beta1_ClusterClassStatusVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Variables = nil + } + out.ObservedGeneration = in.ObservedGeneration + // WARNING: in.Deprecated requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_ClusterClassStatusVariable_To_v1beta2_ClusterClassStatusVariable(in *ClusterClassStatusVariable, out *v1beta2.ClusterClassStatusVariable, s conversion.Scope) error { + out.Name = in.Name + if err := v1.Convert_bool_To_Pointer_bool(&in.DefinitionsConflict, &out.DefinitionsConflict, s); err != nil { + return err + } + if in.Definitions != nil { + in, out := &in.Definitions, &out.Definitions + *out = make([]v1beta2.ClusterClassStatusVariableDefinition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterClassStatusVariableDefinition_To_v1beta2_ClusterClassStatusVariableDefinition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Definitions = nil + } + return nil +} + +// Convert_v1beta1_ClusterClassStatusVariable_To_v1beta2_ClusterClassStatusVariable is an autogenerated conversion function. +func Convert_v1beta1_ClusterClassStatusVariable_To_v1beta2_ClusterClassStatusVariable(in *ClusterClassStatusVariable, out *v1beta2.ClusterClassStatusVariable, s conversion.Scope) error { + return autoConvert_v1beta1_ClusterClassStatusVariable_To_v1beta2_ClusterClassStatusVariable(in, out, s) +} + +func autoConvert_v1beta2_ClusterClassStatusVariable_To_v1beta1_ClusterClassStatusVariable(in *v1beta2.ClusterClassStatusVariable, out *ClusterClassStatusVariable, s conversion.Scope) error { + out.Name = in.Name + if err := v1.Convert_Pointer_bool_To_bool(&in.DefinitionsConflict, &out.DefinitionsConflict, s); err != nil { + return err + } + if in.Definitions != nil { + in, out := &in.Definitions, &out.Definitions + *out = make([]ClusterClassStatusVariableDefinition, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterClassStatusVariableDefinition_To_v1beta1_ClusterClassStatusVariableDefinition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Definitions = nil + } + return nil +} + +// Convert_v1beta2_ClusterClassStatusVariable_To_v1beta1_ClusterClassStatusVariable is an autogenerated conversion function. +func Convert_v1beta2_ClusterClassStatusVariable_To_v1beta1_ClusterClassStatusVariable(in *v1beta2.ClusterClassStatusVariable, out *ClusterClassStatusVariable, s conversion.Scope) error { + return autoConvert_v1beta2_ClusterClassStatusVariable_To_v1beta1_ClusterClassStatusVariable(in, out, s) +} + +func autoConvert_v1beta1_ClusterClassStatusVariableDefinition_To_v1beta2_ClusterClassStatusVariableDefinition(in *ClusterClassStatusVariableDefinition, out *v1beta2.ClusterClassStatusVariableDefinition, s conversion.Scope) error { + out.From = in.From + if err := v1.Convert_bool_To_Pointer_bool(&in.Required, &out.Required, s); err != nil { + return err + } + // WARNING: in.Metadata requires manual conversion: does not exist in peer-type + if err := Convert_v1beta1_VariableSchema_To_v1beta2_VariableSchema(&in.Schema, &out.Schema, s); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta2_ClusterClassStatusVariableDefinition_To_v1beta1_ClusterClassStatusVariableDefinition(in *v1beta2.ClusterClassStatusVariableDefinition, out *ClusterClassStatusVariableDefinition, s conversion.Scope) error { + out.From = in.From + if err := v1.Convert_Pointer_bool_To_bool(&in.Required, &out.Required, s); err != nil { + return err + } + // WARNING: in.DeprecatedV1Beta1Metadata requires manual conversion: does not exist in peer-type + if err := Convert_v1beta2_VariableSchema_To_v1beta1_VariableSchema(&in.Schema, &out.Schema, s); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta1_ClusterClassVariable_To_v1beta2_ClusterClassVariable(in *ClusterClassVariable, out *v1beta2.ClusterClassVariable, s conversion.Scope) error { + out.Name = in.Name + if err := v1.Convert_bool_To_Pointer_bool(&in.Required, &out.Required, s); err != nil { + return err + } + // WARNING: in.Metadata requires manual conversion: does not exist in peer-type + if err := Convert_v1beta1_VariableSchema_To_v1beta2_VariableSchema(&in.Schema, &out.Schema, s); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta2_ClusterClassVariable_To_v1beta1_ClusterClassVariable(in *v1beta2.ClusterClassVariable, out *ClusterClassVariable, s conversion.Scope) error { + out.Name = in.Name + if err := v1.Convert_Pointer_bool_To_bool(&in.Required, &out.Required, s); err != nil { + return err + } + // WARNING: in.DeprecatedV1Beta1Metadata requires manual conversion: does not exist in peer-type + if err := Convert_v1beta2_VariableSchema_To_v1beta1_VariableSchema(&in.Schema, &out.Schema, s); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta1_ClusterClassVariableMetadata_To_v1beta2_ClusterClassVariableMetadata(in *ClusterClassVariableMetadata, out *v1beta2.ClusterClassVariableMetadata, s conversion.Scope) error { + out.Labels = *(*map[string]string)(unsafe.Pointer(&in.Labels)) + out.Annotations = *(*map[string]string)(unsafe.Pointer(&in.Annotations)) + return nil +} + +// Convert_v1beta1_ClusterClassVariableMetadata_To_v1beta2_ClusterClassVariableMetadata is an autogenerated conversion function. +func Convert_v1beta1_ClusterClassVariableMetadata_To_v1beta2_ClusterClassVariableMetadata(in *ClusterClassVariableMetadata, out *v1beta2.ClusterClassVariableMetadata, s conversion.Scope) error { + return autoConvert_v1beta1_ClusterClassVariableMetadata_To_v1beta2_ClusterClassVariableMetadata(in, out, s) +} + +func autoConvert_v1beta2_ClusterClassVariableMetadata_To_v1beta1_ClusterClassVariableMetadata(in *v1beta2.ClusterClassVariableMetadata, out *ClusterClassVariableMetadata, s conversion.Scope) error { + out.Labels = *(*map[string]string)(unsafe.Pointer(&in.Labels)) + out.Annotations = *(*map[string]string)(unsafe.Pointer(&in.Annotations)) + return nil +} + +// Convert_v1beta2_ClusterClassVariableMetadata_To_v1beta1_ClusterClassVariableMetadata is an autogenerated conversion function. +func Convert_v1beta2_ClusterClassVariableMetadata_To_v1beta1_ClusterClassVariableMetadata(in *v1beta2.ClusterClassVariableMetadata, out *ClusterClassVariableMetadata, s conversion.Scope) error { + return autoConvert_v1beta2_ClusterClassVariableMetadata_To_v1beta1_ClusterClassVariableMetadata(in, out, s) +} + +func autoConvert_v1beta1_ClusterControlPlaneStatus_To_v1beta2_ClusterControlPlaneStatus(in *ClusterControlPlaneStatus, out *v1beta2.ClusterControlPlaneStatus, s conversion.Scope) error { + out.DesiredReplicas = (*int32)(unsafe.Pointer(in.DesiredReplicas)) + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + out.UpToDateReplicas = (*int32)(unsafe.Pointer(in.UpToDateReplicas)) + out.ReadyReplicas = (*int32)(unsafe.Pointer(in.ReadyReplicas)) + out.AvailableReplicas = (*int32)(unsafe.Pointer(in.AvailableReplicas)) + return nil +} + +// Convert_v1beta1_ClusterControlPlaneStatus_To_v1beta2_ClusterControlPlaneStatus is an autogenerated conversion function. +func Convert_v1beta1_ClusterControlPlaneStatus_To_v1beta2_ClusterControlPlaneStatus(in *ClusterControlPlaneStatus, out *v1beta2.ClusterControlPlaneStatus, s conversion.Scope) error { + return autoConvert_v1beta1_ClusterControlPlaneStatus_To_v1beta2_ClusterControlPlaneStatus(in, out, s) +} + +func autoConvert_v1beta2_ClusterControlPlaneStatus_To_v1beta1_ClusterControlPlaneStatus(in *v1beta2.ClusterControlPlaneStatus, out *ClusterControlPlaneStatus, s conversion.Scope) error { + out.DesiredReplicas = (*int32)(unsafe.Pointer(in.DesiredReplicas)) + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + out.UpToDateReplicas = (*int32)(unsafe.Pointer(in.UpToDateReplicas)) + out.ReadyReplicas = (*int32)(unsafe.Pointer(in.ReadyReplicas)) + out.AvailableReplicas = (*int32)(unsafe.Pointer(in.AvailableReplicas)) + return nil +} + +// Convert_v1beta2_ClusterControlPlaneStatus_To_v1beta1_ClusterControlPlaneStatus is an autogenerated conversion function. +func Convert_v1beta2_ClusterControlPlaneStatus_To_v1beta1_ClusterControlPlaneStatus(in *v1beta2.ClusterControlPlaneStatus, out *ClusterControlPlaneStatus, s conversion.Scope) error { + return autoConvert_v1beta2_ClusterControlPlaneStatus_To_v1beta1_ClusterControlPlaneStatus(in, out, s) +} + +func autoConvert_v1beta1_ClusterList_To_v1beta2_ClusterList(in *ClusterList, out *v1beta2.ClusterList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]v1beta2.Cluster, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Cluster_To_v1beta2_Cluster(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta1_ClusterList_To_v1beta2_ClusterList is an autogenerated conversion function. +func Convert_v1beta1_ClusterList_To_v1beta2_ClusterList(in *ClusterList, out *v1beta2.ClusterList, s conversion.Scope) error { + return autoConvert_v1beta1_ClusterList_To_v1beta2_ClusterList(in, out, s) +} + +func autoConvert_v1beta2_ClusterList_To_v1beta1_ClusterList(in *v1beta2.ClusterList, out *ClusterList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Cluster, len(*in)) + for i := range *in { + if err := Convert_v1beta2_Cluster_To_v1beta1_Cluster(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta2_ClusterList_To_v1beta1_ClusterList is an autogenerated conversion function. +func Convert_v1beta2_ClusterList_To_v1beta1_ClusterList(in *v1beta2.ClusterList, out *ClusterList, s conversion.Scope) error { + return autoConvert_v1beta2_ClusterList_To_v1beta1_ClusterList(in, out, s) +} + +func autoConvert_v1beta1_ClusterNetwork_To_v1beta2_ClusterNetwork(in *ClusterNetwork, out *v1beta2.ClusterNetwork, s conversion.Scope) error { + if err := v1.Convert_Pointer_int32_To_int32(&in.APIServerPort, &out.APIServerPort, s); err != nil { + return err + } + // WARNING: in.Services requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.NetworkRanges vs sigs.k8s.io/cluster-api/api/core/v1beta2.NetworkRanges) + // WARNING: in.Pods requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.NetworkRanges vs sigs.k8s.io/cluster-api/api/core/v1beta2.NetworkRanges) + out.ServiceDomain = in.ServiceDomain + return nil +} + +func autoConvert_v1beta2_ClusterNetwork_To_v1beta1_ClusterNetwork(in *v1beta2.ClusterNetwork, out *ClusterNetwork, s conversion.Scope) error { + if err := v1.Convert_int32_To_Pointer_int32(&in.APIServerPort, &out.APIServerPort, s); err != nil { + return err + } + // WARNING: in.Services requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.NetworkRanges vs *sigs.k8s.io/cluster-api/api/core/v1beta1.NetworkRanges) + // WARNING: in.Pods requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.NetworkRanges vs *sigs.k8s.io/cluster-api/api/core/v1beta1.NetworkRanges) + out.ServiceDomain = in.ServiceDomain + return nil +} + +func autoConvert_v1beta1_ClusterSpec_To_v1beta2_ClusterSpec(in *ClusterSpec, out *v1beta2.ClusterSpec, s conversion.Scope) error { + if err := v1.Convert_bool_To_Pointer_bool(&in.Paused, &out.Paused, s); err != nil { + return err + } + // WARNING: in.ClusterNetwork requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterNetwork vs sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterNetwork) + if err := Convert_v1beta1_APIEndpoint_To_v1beta2_APIEndpoint(&in.ControlPlaneEndpoint, &out.ControlPlaneEndpoint, s); err != nil { + return err + } + // WARNING: in.ControlPlaneRef requires manual conversion: inconvertible types (*k8s.io/api/core/v1.ObjectReference vs sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference) + // WARNING: in.InfrastructureRef requires manual conversion: inconvertible types (*k8s.io/api/core/v1.ObjectReference vs sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference) + // WARNING: in.Topology requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.Topology vs sigs.k8s.io/cluster-api/api/core/v1beta2.Topology) + out.AvailabilityGates = *(*[]v1beta2.ClusterAvailabilityGate)(unsafe.Pointer(&in.AvailabilityGates)) + return nil +} + +func autoConvert_v1beta2_ClusterSpec_To_v1beta1_ClusterSpec(in *v1beta2.ClusterSpec, out *ClusterSpec, s conversion.Scope) error { + if err := v1.Convert_Pointer_bool_To_bool(&in.Paused, &out.Paused, s); err != nil { + return err + } + // WARNING: in.ClusterNetwork requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterNetwork vs *sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterNetwork) + if err := Convert_v1beta2_APIEndpoint_To_v1beta1_APIEndpoint(&in.ControlPlaneEndpoint, &out.ControlPlaneEndpoint, s); err != nil { + return err + } + // WARNING: in.ControlPlaneRef requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference vs *k8s.io/api/core/v1.ObjectReference) + // WARNING: in.InfrastructureRef requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference vs *k8s.io/api/core/v1.ObjectReference) + // WARNING: in.Topology requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.Topology vs *sigs.k8s.io/cluster-api/api/core/v1beta1.Topology) + out.AvailabilityGates = *(*[]ClusterAvailabilityGate)(unsafe.Pointer(&in.AvailabilityGates)) + return nil +} + +func autoConvert_v1beta1_ClusterStatus_To_v1beta2_ClusterStatus(in *ClusterStatus, out *v1beta2.ClusterStatus, s conversion.Scope) error { + // WARNING: in.FailureDomains requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta1.FailureDomains vs []sigs.k8s.io/cluster-api/api/core/v1beta2.FailureDomain) + // WARNING: in.FailureReason requires manual conversion: does not exist in peer-type + // WARNING: in.FailureMessage requires manual conversion: does not exist in peer-type + out.Phase = in.Phase + // WARNING: in.InfrastructureReady requires manual conversion: does not exist in peer-type + // WARNING: in.ControlPlaneReady requires manual conversion: does not exist in peer-type + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Condition_To_v1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + out.ObservedGeneration = in.ObservedGeneration + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_ClusterStatus_To_v1beta1_ClusterStatus(in *v1beta2.ClusterStatus, out *ClusterStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + if err := Convert_v1_Condition_To_v1beta1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // WARNING: in.Initialization requires manual conversion: does not exist in peer-type + // WARNING: in.ControlPlane requires manual conversion: does not exist in peer-type + // WARNING: in.Workers requires manual conversion: does not exist in peer-type + // WARNING: in.FailureDomains requires manual conversion: inconvertible types ([]sigs.k8s.io/cluster-api/api/core/v1beta2.FailureDomain vs sigs.k8s.io/cluster-api/api/core/v1beta1.FailureDomains) + out.Phase = in.Phase + out.ObservedGeneration = in.ObservedGeneration + // WARNING: in.Deprecated requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_ClusterVariable_To_v1beta2_ClusterVariable(in *ClusterVariable, out *v1beta2.ClusterVariable, s conversion.Scope) error { + out.Name = in.Name + // WARNING: in.DefinitionFrom requires manual conversion: does not exist in peer-type + out.Value = in.Value + return nil +} + +func autoConvert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable(in *v1beta2.ClusterVariable, out *ClusterVariable, s conversion.Scope) error { + out.Name = in.Name + out.Value = in.Value + return nil +} + +// Convert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable is an autogenerated conversion function. +func Convert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable(in *v1beta2.ClusterVariable, out *ClusterVariable, s conversion.Scope) error { + return autoConvert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable(in, out, s) +} + +func autoConvert_v1beta1_Condition_To_v1beta2_Condition(in *Condition, out *v1beta2.Condition, s conversion.Scope) error { + out.Type = v1beta2.ConditionType(in.Type) + out.Status = corev1.ConditionStatus(in.Status) + out.Severity = v1beta2.ConditionSeverity(in.Severity) + out.LastTransitionTime = in.LastTransitionTime + out.Reason = in.Reason + out.Message = in.Message + return nil +} + +// Convert_v1beta1_Condition_To_v1beta2_Condition is an autogenerated conversion function. +func Convert_v1beta1_Condition_To_v1beta2_Condition(in *Condition, out *v1beta2.Condition, s conversion.Scope) error { + return autoConvert_v1beta1_Condition_To_v1beta2_Condition(in, out, s) +} + +func autoConvert_v1beta2_Condition_To_v1beta1_Condition(in *v1beta2.Condition, out *Condition, s conversion.Scope) error { + out.Type = ConditionType(in.Type) + out.Status = corev1.ConditionStatus(in.Status) + out.Severity = ConditionSeverity(in.Severity) + out.LastTransitionTime = in.LastTransitionTime + out.Reason = in.Reason + out.Message = in.Message + return nil +} + +// Convert_v1beta2_Condition_To_v1beta1_Condition is an autogenerated conversion function. +func Convert_v1beta2_Condition_To_v1beta1_Condition(in *v1beta2.Condition, out *Condition, s conversion.Scope) error { + return autoConvert_v1beta2_Condition_To_v1beta1_Condition(in, out, s) +} + +func autoConvert_v1beta1_ControlPlaneClass_To_v1beta2_ControlPlaneClass(in *ControlPlaneClass, out *v1beta2.ControlPlaneClass, s conversion.Scope) error { + if err := Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(&in.Metadata, &out.Metadata, s); err != nil { + return err + } + // WARNING: in.LocalObjectTemplate requires manual conversion: does not exist in peer-type + // WARNING: in.MachineInfrastructure requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate vs sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassMachineInfrastructureTemplate) + // WARNING: in.MachineHealthCheck requires manual conversion: does not exist in peer-type + // WARNING: in.NamingStrategy requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDrainTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeVolumeDetachTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDeletionTimeout requires manual conversion: does not exist in peer-type + out.ReadinessGates = *(*[]v1beta2.MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + return nil +} + +func autoConvert_v1beta2_ControlPlaneClass_To_v1beta1_ControlPlaneClass(in *v1beta2.ControlPlaneClass, out *ControlPlaneClass, s conversion.Scope) error { + if err := Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(&in.Metadata, &out.Metadata, s); err != nil { + return err + } + // WARNING: in.TemplateRef requires manual conversion: does not exist in peer-type + // WARNING: in.MachineInfrastructure requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassMachineInfrastructureTemplate vs *sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate) + // WARNING: in.HealthCheck requires manual conversion: does not exist in peer-type + // WARNING: in.Naming requires manual conversion: does not exist in peer-type + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + out.ReadinessGates = *(*[]MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + return nil +} + +func autoConvert_v1beta1_ControlPlaneTopology_To_v1beta2_ControlPlaneTopology(in *ControlPlaneTopology, out *v1beta2.ControlPlaneTopology, s conversion.Scope) error { + if err := Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(&in.Metadata, &out.Metadata, s); err != nil { + return err + } + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.MachineHealthCheck requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDrainTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeVolumeDetachTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDeletionTimeout requires manual conversion: does not exist in peer-type + out.ReadinessGates = *(*[]v1beta2.MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + // WARNING: in.Variables requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneVariables vs sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneVariables) + return nil +} + +func autoConvert_v1beta2_ControlPlaneTopology_To_v1beta1_ControlPlaneTopology(in *v1beta2.ControlPlaneTopology, out *ControlPlaneTopology, s conversion.Scope) error { + if err := Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(&in.Metadata, &out.Metadata, s); err != nil { + return err + } + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.HealthCheck requires manual conversion: does not exist in peer-type + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + out.ReadinessGates = *(*[]MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + // WARNING: in.Variables requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneVariables vs *sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneVariables) + return nil +} + +func autoConvert_v1beta1_ControlPlaneVariables_To_v1beta2_ControlPlaneVariables(in *ControlPlaneVariables, out *v1beta2.ControlPlaneVariables, s conversion.Scope) error { + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]v1beta2.ClusterVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterVariable_To_v1beta2_ClusterVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Overrides = nil + } + return nil +} + +// Convert_v1beta1_ControlPlaneVariables_To_v1beta2_ControlPlaneVariables is an autogenerated conversion function. +func Convert_v1beta1_ControlPlaneVariables_To_v1beta2_ControlPlaneVariables(in *ControlPlaneVariables, out *v1beta2.ControlPlaneVariables, s conversion.Scope) error { + return autoConvert_v1beta1_ControlPlaneVariables_To_v1beta2_ControlPlaneVariables(in, out, s) +} + +func autoConvert_v1beta2_ControlPlaneVariables_To_v1beta1_ControlPlaneVariables(in *v1beta2.ControlPlaneVariables, out *ControlPlaneVariables, s conversion.Scope) error { + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]ClusterVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Overrides = nil + } + return nil +} + +// Convert_v1beta2_ControlPlaneVariables_To_v1beta1_ControlPlaneVariables is an autogenerated conversion function. +func Convert_v1beta2_ControlPlaneVariables_To_v1beta1_ControlPlaneVariables(in *v1beta2.ControlPlaneVariables, out *ControlPlaneVariables, s conversion.Scope) error { + return autoConvert_v1beta2_ControlPlaneVariables_To_v1beta1_ControlPlaneVariables(in, out, s) +} + +func autoConvert_v1beta1_ExternalPatchDefinition_To_v1beta2_ExternalPatchDefinition(in *ExternalPatchDefinition, out *v1beta2.ExternalPatchDefinition, s conversion.Scope) error { + // WARNING: in.GenerateExtension requires manual conversion: does not exist in peer-type + // WARNING: in.ValidateExtension requires manual conversion: does not exist in peer-type + if err := v1.Convert_Pointer_string_To_string(&in.DiscoverVariablesExtension, &out.DiscoverVariablesExtension, s); err != nil { + return err + } + out.Settings = *(*map[string]string)(unsafe.Pointer(&in.Settings)) + return nil +} + +func autoConvert_v1beta2_ExternalPatchDefinition_To_v1beta1_ExternalPatchDefinition(in *v1beta2.ExternalPatchDefinition, out *ExternalPatchDefinition, s conversion.Scope) error { + // WARNING: in.GeneratePatchesExtension requires manual conversion: does not exist in peer-type + // WARNING: in.ValidateTopologyExtension requires manual conversion: does not exist in peer-type + if err := v1.Convert_string_To_Pointer_string(&in.DiscoverVariablesExtension, &out.DiscoverVariablesExtension, s); err != nil { + return err + } + out.Settings = *(*map[string]string)(unsafe.Pointer(&in.Settings)) + return nil +} + +func autoConvert_v1beta1_JSONPatch_To_v1beta2_JSONPatch(in *JSONPatch, out *v1beta2.JSONPatch, s conversion.Scope) error { + out.Op = in.Op + out.Path = in.Path + out.Value = (*apiextensionsv1.JSON)(unsafe.Pointer(in.Value)) + if in.ValueFrom != nil { + in, out := &in.ValueFrom, &out.ValueFrom + *out = new(v1beta2.JSONPatchValue) + if err := Convert_v1beta1_JSONPatchValue_To_v1beta2_JSONPatchValue(*in, *out, s); err != nil { + return err + } + } else { + out.ValueFrom = nil + } + return nil +} + +// Convert_v1beta1_JSONPatch_To_v1beta2_JSONPatch is an autogenerated conversion function. +func Convert_v1beta1_JSONPatch_To_v1beta2_JSONPatch(in *JSONPatch, out *v1beta2.JSONPatch, s conversion.Scope) error { + return autoConvert_v1beta1_JSONPatch_To_v1beta2_JSONPatch(in, out, s) +} + +func autoConvert_v1beta2_JSONPatch_To_v1beta1_JSONPatch(in *v1beta2.JSONPatch, out *JSONPatch, s conversion.Scope) error { + out.Op = in.Op + out.Path = in.Path + out.Value = (*apiextensionsv1.JSON)(unsafe.Pointer(in.Value)) + if in.ValueFrom != nil { + in, out := &in.ValueFrom, &out.ValueFrom + *out = new(JSONPatchValue) + if err := Convert_v1beta2_JSONPatchValue_To_v1beta1_JSONPatchValue(*in, *out, s); err != nil { + return err + } + } else { + out.ValueFrom = nil + } + return nil +} + +// Convert_v1beta2_JSONPatch_To_v1beta1_JSONPatch is an autogenerated conversion function. +func Convert_v1beta2_JSONPatch_To_v1beta1_JSONPatch(in *v1beta2.JSONPatch, out *JSONPatch, s conversion.Scope) error { + return autoConvert_v1beta2_JSONPatch_To_v1beta1_JSONPatch(in, out, s) +} + +func autoConvert_v1beta1_JSONPatchValue_To_v1beta2_JSONPatchValue(in *JSONPatchValue, out *v1beta2.JSONPatchValue, s conversion.Scope) error { + if err := v1.Convert_Pointer_string_To_string(&in.Variable, &out.Variable, s); err != nil { + return err + } + if err := v1.Convert_Pointer_string_To_string(&in.Template, &out.Template, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_JSONPatchValue_To_v1beta2_JSONPatchValue is an autogenerated conversion function. +func Convert_v1beta1_JSONPatchValue_To_v1beta2_JSONPatchValue(in *JSONPatchValue, out *v1beta2.JSONPatchValue, s conversion.Scope) error { + return autoConvert_v1beta1_JSONPatchValue_To_v1beta2_JSONPatchValue(in, out, s) +} + +func autoConvert_v1beta2_JSONPatchValue_To_v1beta1_JSONPatchValue(in *v1beta2.JSONPatchValue, out *JSONPatchValue, s conversion.Scope) error { + if err := v1.Convert_string_To_Pointer_string(&in.Variable, &out.Variable, s); err != nil { + return err + } + if err := v1.Convert_string_To_Pointer_string(&in.Template, &out.Template, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_JSONPatchValue_To_v1beta1_JSONPatchValue is an autogenerated conversion function. +func Convert_v1beta2_JSONPatchValue_To_v1beta1_JSONPatchValue(in *v1beta2.JSONPatchValue, out *JSONPatchValue, s conversion.Scope) error { + return autoConvert_v1beta2_JSONPatchValue_To_v1beta1_JSONPatchValue(in, out, s) +} + +func autoConvert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(in *JSONSchemaProps, out *v1beta2.JSONSchemaProps, s conversion.Scope) error { + out.Description = in.Description + out.Example = (*apiextensionsv1.JSON)(unsafe.Pointer(in.Example)) + out.Type = in.Type + if in.Properties != nil { + in, out := &in.Properties, &out.Properties + *out = make(map[string]v1beta2.JSONSchemaProps, len(*in)) + for key, val := range *in { + newVal := new(v1beta2.JSONSchemaProps) + if err := Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(&val, newVal, s); err != nil { + return err + } + (*out)[key] = *newVal + } + } else { + out.Properties = nil + } + if in.AdditionalProperties != nil { + in, out := &in.AdditionalProperties, &out.AdditionalProperties + *out = new(v1beta2.JSONSchemaProps) + if err := Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(*in, *out, s); err != nil { + return err + } + } else { + out.AdditionalProperties = nil + } + out.MaxProperties = (*int64)(unsafe.Pointer(in.MaxProperties)) + out.MinProperties = (*int64)(unsafe.Pointer(in.MinProperties)) + out.Required = *(*[]string)(unsafe.Pointer(&in.Required)) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = new(v1beta2.JSONSchemaProps) + if err := Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(*in, *out, s); err != nil { + return err + } + } else { + out.Items = nil + } + out.MaxItems = (*int64)(unsafe.Pointer(in.MaxItems)) + out.MinItems = (*int64)(unsafe.Pointer(in.MinItems)) + if err := v1.Convert_bool_To_Pointer_bool(&in.UniqueItems, &out.UniqueItems, s); err != nil { + return err + } + out.Format = in.Format + out.MaxLength = (*int64)(unsafe.Pointer(in.MaxLength)) + out.MinLength = (*int64)(unsafe.Pointer(in.MinLength)) + out.Pattern = in.Pattern + out.Maximum = (*int64)(unsafe.Pointer(in.Maximum)) + if err := v1.Convert_bool_To_Pointer_bool(&in.ExclusiveMaximum, &out.ExclusiveMaximum, s); err != nil { + return err + } + out.Minimum = (*int64)(unsafe.Pointer(in.Minimum)) + if err := v1.Convert_bool_To_Pointer_bool(&in.ExclusiveMinimum, &out.ExclusiveMinimum, s); err != nil { + return err + } + if err := v1.Convert_bool_To_Pointer_bool(&in.XPreserveUnknownFields, &out.XPreserveUnknownFields, s); err != nil { + return err + } + out.Enum = *(*[]apiextensionsv1.JSON)(unsafe.Pointer(&in.Enum)) + out.Default = (*apiextensionsv1.JSON)(unsafe.Pointer(in.Default)) + out.XValidations = *(*[]v1beta2.ValidationRule)(unsafe.Pointer(&in.XValidations)) + // WARNING: in.XMetadata requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchemaMetadata vs sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchemaMetadata) + if err := v1.Convert_bool_To_Pointer_bool(&in.XIntOrString, &out.XIntOrString, s); err != nil { + return err + } + if in.AllOf != nil { + in, out := &in.AllOf, &out.AllOf + *out = make([]v1beta2.JSONSchemaProps, len(*in)) + for i := range *in { + if err := Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.AllOf = nil + } + if in.OneOf != nil { + in, out := &in.OneOf, &out.OneOf + *out = make([]v1beta2.JSONSchemaProps, len(*in)) + for i := range *in { + if err := Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.OneOf = nil + } + if in.AnyOf != nil { + in, out := &in.AnyOf, &out.AnyOf + *out = make([]v1beta2.JSONSchemaProps, len(*in)) + for i := range *in { + if err := Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.AnyOf = nil + } + if in.Not != nil { + in, out := &in.Not, &out.Not + *out = new(v1beta2.JSONSchemaProps) + if err := Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(*in, *out, s); err != nil { + return err + } + } else { + out.Not = nil + } + return nil +} + +func autoConvert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *v1beta2.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error { + out.Description = in.Description + out.Example = (*apiextensionsv1.JSON)(unsafe.Pointer(in.Example)) + out.Type = in.Type + if in.Properties != nil { + in, out := &in.Properties, &out.Properties + *out = make(map[string]JSONSchemaProps, len(*in)) + for key, val := range *in { + newVal := new(JSONSchemaProps) + if err := Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&val, newVal, s); err != nil { + return err + } + (*out)[key] = *newVal + } + } else { + out.Properties = nil + } + if in.AdditionalProperties != nil { + in, out := &in.AdditionalProperties, &out.AdditionalProperties + *out = new(JSONSchemaProps) + if err := Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(*in, *out, s); err != nil { + return err + } + } else { + out.AdditionalProperties = nil + } + out.MaxProperties = (*int64)(unsafe.Pointer(in.MaxProperties)) + out.MinProperties = (*int64)(unsafe.Pointer(in.MinProperties)) + out.Required = *(*[]string)(unsafe.Pointer(&in.Required)) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = new(JSONSchemaProps) + if err := Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(*in, *out, s); err != nil { + return err + } + } else { + out.Items = nil + } + out.MaxItems = (*int64)(unsafe.Pointer(in.MaxItems)) + out.MinItems = (*int64)(unsafe.Pointer(in.MinItems)) + if err := v1.Convert_Pointer_bool_To_bool(&in.UniqueItems, &out.UniqueItems, s); err != nil { + return err + } + out.Format = in.Format + out.MaxLength = (*int64)(unsafe.Pointer(in.MaxLength)) + out.MinLength = (*int64)(unsafe.Pointer(in.MinLength)) + out.Pattern = in.Pattern + out.Maximum = (*int64)(unsafe.Pointer(in.Maximum)) + if err := v1.Convert_Pointer_bool_To_bool(&in.ExclusiveMaximum, &out.ExclusiveMaximum, s); err != nil { + return err + } + out.Minimum = (*int64)(unsafe.Pointer(in.Minimum)) + if err := v1.Convert_Pointer_bool_To_bool(&in.ExclusiveMinimum, &out.ExclusiveMinimum, s); err != nil { + return err + } + if err := v1.Convert_Pointer_bool_To_bool(&in.XPreserveUnknownFields, &out.XPreserveUnknownFields, s); err != nil { + return err + } + out.Enum = *(*[]apiextensionsv1.JSON)(unsafe.Pointer(&in.Enum)) + out.Default = (*apiextensionsv1.JSON)(unsafe.Pointer(in.Default)) + out.XValidations = *(*[]ValidationRule)(unsafe.Pointer(&in.XValidations)) + // WARNING: in.XMetadata requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchemaMetadata vs *sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchemaMetadata) + if err := v1.Convert_Pointer_bool_To_bool(&in.XIntOrString, &out.XIntOrString, s); err != nil { + return err + } + if in.AllOf != nil { + in, out := &in.AllOf, &out.AllOf + *out = make([]JSONSchemaProps, len(*in)) + for i := range *in { + if err := Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.AllOf = nil + } + if in.OneOf != nil { + in, out := &in.OneOf, &out.OneOf + *out = make([]JSONSchemaProps, len(*in)) + for i := range *in { + if err := Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.OneOf = nil + } + if in.AnyOf != nil { + in, out := &in.AnyOf, &out.AnyOf + *out = make([]JSONSchemaProps, len(*in)) + for i := range *in { + if err := Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.AnyOf = nil + } + if in.Not != nil { + in, out := &in.Not, &out.Not + *out = new(JSONSchemaProps) + if err := Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(*in, *out, s); err != nil { + return err + } + } else { + out.Not = nil + } + return nil +} + +func autoConvert_v1beta1_Machine_To_v1beta2_Machine(in *Machine, out *v1beta2.Machine, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_MachineSpec_To_v1beta2_MachineSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta1_MachineStatus_To_v1beta2_MachineStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_Machine_To_v1beta2_Machine is an autogenerated conversion function. +func Convert_v1beta1_Machine_To_v1beta2_Machine(in *Machine, out *v1beta2.Machine, s conversion.Scope) error { + return autoConvert_v1beta1_Machine_To_v1beta2_Machine(in, out, s) +} + +func autoConvert_v1beta2_Machine_To_v1beta1_Machine(in *v1beta2.Machine, out *Machine, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta2_MachineSpec_To_v1beta1_MachineSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta2_MachineStatus_To_v1beta1_MachineStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_Machine_To_v1beta1_Machine is an autogenerated conversion function. +func Convert_v1beta2_Machine_To_v1beta1_Machine(in *v1beta2.Machine, out *Machine, s conversion.Scope) error { + return autoConvert_v1beta2_Machine_To_v1beta1_Machine(in, out, s) +} + +func autoConvert_v1beta1_MachineAddress_To_v1beta2_MachineAddress(in *MachineAddress, out *v1beta2.MachineAddress, s conversion.Scope) error { + out.Type = v1beta2.MachineAddressType(in.Type) + out.Address = in.Address + return nil +} + +// Convert_v1beta1_MachineAddress_To_v1beta2_MachineAddress is an autogenerated conversion function. +func Convert_v1beta1_MachineAddress_To_v1beta2_MachineAddress(in *MachineAddress, out *v1beta2.MachineAddress, s conversion.Scope) error { + return autoConvert_v1beta1_MachineAddress_To_v1beta2_MachineAddress(in, out, s) +} + +func autoConvert_v1beta2_MachineAddress_To_v1beta1_MachineAddress(in *v1beta2.MachineAddress, out *MachineAddress, s conversion.Scope) error { + out.Type = MachineAddressType(in.Type) + out.Address = in.Address + return nil +} + +// Convert_v1beta2_MachineAddress_To_v1beta1_MachineAddress is an autogenerated conversion function. +func Convert_v1beta2_MachineAddress_To_v1beta1_MachineAddress(in *v1beta2.MachineAddress, out *MachineAddress, s conversion.Scope) error { + return autoConvert_v1beta2_MachineAddress_To_v1beta1_MachineAddress(in, out, s) +} + +func autoConvert_v1beta1_MachineDeletionStatus_To_v1beta2_MachineDeletionStatus(in *MachineDeletionStatus, out *v1beta2.MachineDeletionStatus, s conversion.Scope) error { + // WARNING: in.NodeDrainStartTime requires manual conversion: inconvertible types (*k8s.io/apimachinery/pkg/apis/meta/v1.Time vs k8s.io/apimachinery/pkg/apis/meta/v1.Time) + // WARNING: in.WaitForNodeVolumeDetachStartTime requires manual conversion: inconvertible types (*k8s.io/apimachinery/pkg/apis/meta/v1.Time vs k8s.io/apimachinery/pkg/apis/meta/v1.Time) + return nil +} + +func autoConvert_v1beta2_MachineDeletionStatus_To_v1beta1_MachineDeletionStatus(in *v1beta2.MachineDeletionStatus, out *MachineDeletionStatus, s conversion.Scope) error { + // WARNING: in.NodeDrainStartTime requires manual conversion: inconvertible types (k8s.io/apimachinery/pkg/apis/meta/v1.Time vs *k8s.io/apimachinery/pkg/apis/meta/v1.Time) + // WARNING: in.WaitForNodeVolumeDetachStartTime requires manual conversion: inconvertible types (k8s.io/apimachinery/pkg/apis/meta/v1.Time vs *k8s.io/apimachinery/pkg/apis/meta/v1.Time) + return nil +} + +func autoConvert_v1beta1_MachineDeployment_To_v1beta2_MachineDeployment(in *MachineDeployment, out *v1beta2.MachineDeployment, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_MachineDeploymentSpec_To_v1beta2_MachineDeploymentSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta1_MachineDeploymentStatus_To_v1beta2_MachineDeploymentStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_MachineDeployment_To_v1beta2_MachineDeployment is an autogenerated conversion function. +func Convert_v1beta1_MachineDeployment_To_v1beta2_MachineDeployment(in *MachineDeployment, out *v1beta2.MachineDeployment, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDeployment_To_v1beta2_MachineDeployment(in, out, s) +} + +func autoConvert_v1beta2_MachineDeployment_To_v1beta1_MachineDeployment(in *v1beta2.MachineDeployment, out *MachineDeployment, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta2_MachineDeploymentSpec_To_v1beta1_MachineDeploymentSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta2_MachineDeploymentStatus_To_v1beta1_MachineDeploymentStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_MachineDeployment_To_v1beta1_MachineDeployment is an autogenerated conversion function. +func Convert_v1beta2_MachineDeployment_To_v1beta1_MachineDeployment(in *v1beta2.MachineDeployment, out *MachineDeployment, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDeployment_To_v1beta1_MachineDeployment(in, out, s) +} + +func autoConvert_v1beta1_MachineDeploymentClass_To_v1beta2_MachineDeploymentClass(in *MachineDeploymentClass, out *v1beta2.MachineDeploymentClass, s conversion.Scope) error { + out.Class = in.Class + // WARNING: in.Template requires manual conversion: does not exist in peer-type + // WARNING: in.MachineHealthCheck requires manual conversion: does not exist in peer-type + if err := v1.Convert_Pointer_string_To_string(&in.FailureDomain, &out.FailureDomain, s); err != nil { + return err + } + // WARNING: in.NamingStrategy requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDrainTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeVolumeDetachTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDeletionTimeout requires manual conversion: does not exist in peer-type + out.MinReadySeconds = (*int32)(unsafe.Pointer(in.MinReadySeconds)) + out.ReadinessGates = *(*[]v1beta2.MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + // WARNING: in.Strategy requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineDeploymentClass_To_v1beta1_MachineDeploymentClass(in *v1beta2.MachineDeploymentClass, out *MachineDeploymentClass, s conversion.Scope) error { + // WARNING: in.Metadata requires manual conversion: does not exist in peer-type + out.Class = in.Class + // WARNING: in.Bootstrap requires manual conversion: does not exist in peer-type + // WARNING: in.Infrastructure requires manual conversion: does not exist in peer-type + // WARNING: in.HealthCheck requires manual conversion: does not exist in peer-type + if err := v1.Convert_string_To_Pointer_string(&in.FailureDomain, &out.FailureDomain, s); err != nil { + return err + } + // WARNING: in.Naming requires manual conversion: does not exist in peer-type + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + out.MinReadySeconds = (*int32)(unsafe.Pointer(in.MinReadySeconds)) + out.ReadinessGates = *(*[]MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + // WARNING: in.Rollout requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachineDeploymentList_To_v1beta2_MachineDeploymentList(in *MachineDeploymentList, out *v1beta2.MachineDeploymentList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]v1beta2.MachineDeployment, len(*in)) + for i := range *in { + if err := Convert_v1beta1_MachineDeployment_To_v1beta2_MachineDeployment(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta1_MachineDeploymentList_To_v1beta2_MachineDeploymentList is an autogenerated conversion function. +func Convert_v1beta1_MachineDeploymentList_To_v1beta2_MachineDeploymentList(in *MachineDeploymentList, out *v1beta2.MachineDeploymentList, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDeploymentList_To_v1beta2_MachineDeploymentList(in, out, s) +} + +func autoConvert_v1beta2_MachineDeploymentList_To_v1beta1_MachineDeploymentList(in *v1beta2.MachineDeploymentList, out *MachineDeploymentList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachineDeployment, len(*in)) + for i := range *in { + if err := Convert_v1beta2_MachineDeployment_To_v1beta1_MachineDeployment(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta2_MachineDeploymentList_To_v1beta1_MachineDeploymentList is an autogenerated conversion function. +func Convert_v1beta2_MachineDeploymentList_To_v1beta1_MachineDeploymentList(in *v1beta2.MachineDeploymentList, out *MachineDeploymentList, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDeploymentList_To_v1beta1_MachineDeploymentList(in, out, s) +} + +func autoConvert_v1beta1_MachineDeploymentSpec_To_v1beta2_MachineDeploymentSpec(in *MachineDeploymentSpec, out *v1beta2.MachineDeploymentSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.RolloutAfter requires manual conversion: does not exist in peer-type + out.Selector = in.Selector + if err := Convert_v1beta1_MachineTemplateSpec_To_v1beta2_MachineTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + // WARNING: in.Strategy requires manual conversion: does not exist in peer-type + // WARNING: in.MachineNamingStrategy requires manual conversion: does not exist in peer-type + // WARNING: in.MinReadySeconds requires manual conversion: does not exist in peer-type + // WARNING: in.RevisionHistoryLimit requires manual conversion: does not exist in peer-type + if err := v1.Convert_bool_To_Pointer_bool(&in.Paused, &out.Paused, s); err != nil { + return err + } + // WARNING: in.ProgressDeadlineSeconds requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineDeploymentSpec_To_v1beta1_MachineDeploymentSpec(in *v1beta2.MachineDeploymentSpec, out *MachineDeploymentSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.Rollout requires manual conversion: does not exist in peer-type + out.Selector = in.Selector + if err := Convert_v1beta2_MachineTemplateSpec_To_v1beta1_MachineTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + // WARNING: in.MachineNaming requires manual conversion: does not exist in peer-type + // WARNING: in.Remediation requires manual conversion: does not exist in peer-type + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + if err := v1.Convert_Pointer_bool_To_bool(&in.Paused, &out.Paused, s); err != nil { + return err + } + return nil +} + +func autoConvert_v1beta1_MachineDeploymentStatus_To_v1beta2_MachineDeploymentStatus(in *MachineDeploymentStatus, out *v1beta2.MachineDeploymentStatus, s conversion.Scope) error { + out.ObservedGeneration = in.ObservedGeneration + out.Selector = in.Selector + if err := v1.Convert_int32_To_Pointer_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + // WARNING: in.UpdatedReplicas requires manual conversion: does not exist in peer-type + if err := v1.Convert_int32_To_Pointer_int32(&in.ReadyReplicas, &out.ReadyReplicas, s); err != nil { + return err + } + if err := v1.Convert_int32_To_Pointer_int32(&in.AvailableReplicas, &out.AvailableReplicas, s); err != nil { + return err + } + // WARNING: in.UnavailableReplicas requires manual conversion: does not exist in peer-type + out.Phase = in.Phase + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Condition_To_v1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineDeploymentStatus_To_v1beta1_MachineDeploymentStatus(in *v1beta2.MachineDeploymentStatus, out *MachineDeploymentStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + if err := Convert_v1_Condition_To_v1beta1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + out.ObservedGeneration = in.ObservedGeneration + out.Selector = in.Selector + if err := v1.Convert_Pointer_int32_To_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + if err := v1.Convert_Pointer_int32_To_int32(&in.ReadyReplicas, &out.ReadyReplicas, s); err != nil { + return err + } + if err := v1.Convert_Pointer_int32_To_int32(&in.AvailableReplicas, &out.AvailableReplicas, s); err != nil { + return err + } + // WARNING: in.UpToDateReplicas requires manual conversion: does not exist in peer-type + out.Phase = in.Phase + // WARNING: in.Deprecated requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachineDeploymentTopology_To_v1beta2_MachineDeploymentTopology(in *MachineDeploymentTopology, out *v1beta2.MachineDeploymentTopology, s conversion.Scope) error { + if err := Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(&in.Metadata, &out.Metadata, s); err != nil { + return err + } + out.Class = in.Class + out.Name = in.Name + if err := v1.Convert_Pointer_string_To_string(&in.FailureDomain, &out.FailureDomain, s); err != nil { + return err + } + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.MachineHealthCheck requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDrainTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeVolumeDetachTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDeletionTimeout requires manual conversion: does not exist in peer-type + out.MinReadySeconds = (*int32)(unsafe.Pointer(in.MinReadySeconds)) + out.ReadinessGates = *(*[]v1beta2.MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + // WARNING: in.Strategy requires manual conversion: does not exist in peer-type + // WARNING: in.Variables requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentVariables vs sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentVariables) + return nil +} + +func autoConvert_v1beta2_MachineDeploymentTopology_To_v1beta1_MachineDeploymentTopology(in *v1beta2.MachineDeploymentTopology, out *MachineDeploymentTopology, s conversion.Scope) error { + if err := Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(&in.Metadata, &out.Metadata, s); err != nil { + return err + } + out.Class = in.Class + out.Name = in.Name + if err := v1.Convert_string_To_Pointer_string(&in.FailureDomain, &out.FailureDomain, s); err != nil { + return err + } + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.HealthCheck requires manual conversion: does not exist in peer-type + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + out.MinReadySeconds = (*int32)(unsafe.Pointer(in.MinReadySeconds)) + out.ReadinessGates = *(*[]MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + // WARNING: in.Rollout requires manual conversion: does not exist in peer-type + // WARNING: in.Variables requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentVariables vs *sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentVariables) + return nil +} + +func autoConvert_v1beta1_MachineDeploymentVariables_To_v1beta2_MachineDeploymentVariables(in *MachineDeploymentVariables, out *v1beta2.MachineDeploymentVariables, s conversion.Scope) error { + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]v1beta2.ClusterVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterVariable_To_v1beta2_ClusterVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Overrides = nil + } + return nil +} + +// Convert_v1beta1_MachineDeploymentVariables_To_v1beta2_MachineDeploymentVariables is an autogenerated conversion function. +func Convert_v1beta1_MachineDeploymentVariables_To_v1beta2_MachineDeploymentVariables(in *MachineDeploymentVariables, out *v1beta2.MachineDeploymentVariables, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDeploymentVariables_To_v1beta2_MachineDeploymentVariables(in, out, s) +} + +func autoConvert_v1beta2_MachineDeploymentVariables_To_v1beta1_MachineDeploymentVariables(in *v1beta2.MachineDeploymentVariables, out *MachineDeploymentVariables, s conversion.Scope) error { + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]ClusterVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Overrides = nil + } + return nil +} + +// Convert_v1beta2_MachineDeploymentVariables_To_v1beta1_MachineDeploymentVariables is an autogenerated conversion function. +func Convert_v1beta2_MachineDeploymentVariables_To_v1beta1_MachineDeploymentVariables(in *v1beta2.MachineDeploymentVariables, out *MachineDeploymentVariables, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDeploymentVariables_To_v1beta1_MachineDeploymentVariables(in, out, s) +} + +func autoConvert_v1beta1_MachineDrainRule_To_v1beta2_MachineDrainRule(in *MachineDrainRule, out *v1beta2.MachineDrainRule, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_MachineDrainRuleSpec_To_v1beta2_MachineDrainRuleSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_MachineDrainRule_To_v1beta2_MachineDrainRule is an autogenerated conversion function. +func Convert_v1beta1_MachineDrainRule_To_v1beta2_MachineDrainRule(in *MachineDrainRule, out *v1beta2.MachineDrainRule, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDrainRule_To_v1beta2_MachineDrainRule(in, out, s) +} + +func autoConvert_v1beta2_MachineDrainRule_To_v1beta1_MachineDrainRule(in *v1beta2.MachineDrainRule, out *MachineDrainRule, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta2_MachineDrainRuleSpec_To_v1beta1_MachineDrainRuleSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_MachineDrainRule_To_v1beta1_MachineDrainRule is an autogenerated conversion function. +func Convert_v1beta2_MachineDrainRule_To_v1beta1_MachineDrainRule(in *v1beta2.MachineDrainRule, out *MachineDrainRule, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDrainRule_To_v1beta1_MachineDrainRule(in, out, s) +} + +func autoConvert_v1beta1_MachineDrainRuleDrainConfig_To_v1beta2_MachineDrainRuleDrainConfig(in *MachineDrainRuleDrainConfig, out *v1beta2.MachineDrainRuleDrainConfig, s conversion.Scope) error { + out.Behavior = v1beta2.MachineDrainRuleDrainBehavior(in.Behavior) + out.Order = (*int32)(unsafe.Pointer(in.Order)) + return nil +} + +// Convert_v1beta1_MachineDrainRuleDrainConfig_To_v1beta2_MachineDrainRuleDrainConfig is an autogenerated conversion function. +func Convert_v1beta1_MachineDrainRuleDrainConfig_To_v1beta2_MachineDrainRuleDrainConfig(in *MachineDrainRuleDrainConfig, out *v1beta2.MachineDrainRuleDrainConfig, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDrainRuleDrainConfig_To_v1beta2_MachineDrainRuleDrainConfig(in, out, s) +} + +func autoConvert_v1beta2_MachineDrainRuleDrainConfig_To_v1beta1_MachineDrainRuleDrainConfig(in *v1beta2.MachineDrainRuleDrainConfig, out *MachineDrainRuleDrainConfig, s conversion.Scope) error { + out.Behavior = MachineDrainRuleDrainBehavior(in.Behavior) + out.Order = (*int32)(unsafe.Pointer(in.Order)) + return nil +} + +// Convert_v1beta2_MachineDrainRuleDrainConfig_To_v1beta1_MachineDrainRuleDrainConfig is an autogenerated conversion function. +func Convert_v1beta2_MachineDrainRuleDrainConfig_To_v1beta1_MachineDrainRuleDrainConfig(in *v1beta2.MachineDrainRuleDrainConfig, out *MachineDrainRuleDrainConfig, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDrainRuleDrainConfig_To_v1beta1_MachineDrainRuleDrainConfig(in, out, s) +} + +func autoConvert_v1beta1_MachineDrainRuleList_To_v1beta2_MachineDrainRuleList(in *MachineDrainRuleList, out *v1beta2.MachineDrainRuleList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]v1beta2.MachineDrainRule)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1beta1_MachineDrainRuleList_To_v1beta2_MachineDrainRuleList is an autogenerated conversion function. +func Convert_v1beta1_MachineDrainRuleList_To_v1beta2_MachineDrainRuleList(in *MachineDrainRuleList, out *v1beta2.MachineDrainRuleList, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDrainRuleList_To_v1beta2_MachineDrainRuleList(in, out, s) +} + +func autoConvert_v1beta2_MachineDrainRuleList_To_v1beta1_MachineDrainRuleList(in *v1beta2.MachineDrainRuleList, out *MachineDrainRuleList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + out.Items = *(*[]MachineDrainRule)(unsafe.Pointer(&in.Items)) + return nil +} + +// Convert_v1beta2_MachineDrainRuleList_To_v1beta1_MachineDrainRuleList is an autogenerated conversion function. +func Convert_v1beta2_MachineDrainRuleList_To_v1beta1_MachineDrainRuleList(in *v1beta2.MachineDrainRuleList, out *MachineDrainRuleList, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDrainRuleList_To_v1beta1_MachineDrainRuleList(in, out, s) +} + +func autoConvert_v1beta1_MachineDrainRuleMachineSelector_To_v1beta2_MachineDrainRuleMachineSelector(in *MachineDrainRuleMachineSelector, out *v1beta2.MachineDrainRuleMachineSelector, s conversion.Scope) error { + out.Selector = (*v1.LabelSelector)(unsafe.Pointer(in.Selector)) + out.ClusterSelector = (*v1.LabelSelector)(unsafe.Pointer(in.ClusterSelector)) + return nil +} + +// Convert_v1beta1_MachineDrainRuleMachineSelector_To_v1beta2_MachineDrainRuleMachineSelector is an autogenerated conversion function. +func Convert_v1beta1_MachineDrainRuleMachineSelector_To_v1beta2_MachineDrainRuleMachineSelector(in *MachineDrainRuleMachineSelector, out *v1beta2.MachineDrainRuleMachineSelector, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDrainRuleMachineSelector_To_v1beta2_MachineDrainRuleMachineSelector(in, out, s) +} + +func autoConvert_v1beta2_MachineDrainRuleMachineSelector_To_v1beta1_MachineDrainRuleMachineSelector(in *v1beta2.MachineDrainRuleMachineSelector, out *MachineDrainRuleMachineSelector, s conversion.Scope) error { + out.Selector = (*v1.LabelSelector)(unsafe.Pointer(in.Selector)) + out.ClusterSelector = (*v1.LabelSelector)(unsafe.Pointer(in.ClusterSelector)) + return nil +} + +// Convert_v1beta2_MachineDrainRuleMachineSelector_To_v1beta1_MachineDrainRuleMachineSelector is an autogenerated conversion function. +func Convert_v1beta2_MachineDrainRuleMachineSelector_To_v1beta1_MachineDrainRuleMachineSelector(in *v1beta2.MachineDrainRuleMachineSelector, out *MachineDrainRuleMachineSelector, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDrainRuleMachineSelector_To_v1beta1_MachineDrainRuleMachineSelector(in, out, s) +} + +func autoConvert_v1beta1_MachineDrainRulePodSelector_To_v1beta2_MachineDrainRulePodSelector(in *MachineDrainRulePodSelector, out *v1beta2.MachineDrainRulePodSelector, s conversion.Scope) error { + out.Selector = (*v1.LabelSelector)(unsafe.Pointer(in.Selector)) + out.NamespaceSelector = (*v1.LabelSelector)(unsafe.Pointer(in.NamespaceSelector)) + return nil +} + +// Convert_v1beta1_MachineDrainRulePodSelector_To_v1beta2_MachineDrainRulePodSelector is an autogenerated conversion function. +func Convert_v1beta1_MachineDrainRulePodSelector_To_v1beta2_MachineDrainRulePodSelector(in *MachineDrainRulePodSelector, out *v1beta2.MachineDrainRulePodSelector, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDrainRulePodSelector_To_v1beta2_MachineDrainRulePodSelector(in, out, s) +} + +func autoConvert_v1beta2_MachineDrainRulePodSelector_To_v1beta1_MachineDrainRulePodSelector(in *v1beta2.MachineDrainRulePodSelector, out *MachineDrainRulePodSelector, s conversion.Scope) error { + out.Selector = (*v1.LabelSelector)(unsafe.Pointer(in.Selector)) + out.NamespaceSelector = (*v1.LabelSelector)(unsafe.Pointer(in.NamespaceSelector)) + return nil +} + +// Convert_v1beta2_MachineDrainRulePodSelector_To_v1beta1_MachineDrainRulePodSelector is an autogenerated conversion function. +func Convert_v1beta2_MachineDrainRulePodSelector_To_v1beta1_MachineDrainRulePodSelector(in *v1beta2.MachineDrainRulePodSelector, out *MachineDrainRulePodSelector, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDrainRulePodSelector_To_v1beta1_MachineDrainRulePodSelector(in, out, s) +} + +func autoConvert_v1beta1_MachineDrainRuleSpec_To_v1beta2_MachineDrainRuleSpec(in *MachineDrainRuleSpec, out *v1beta2.MachineDrainRuleSpec, s conversion.Scope) error { + if err := Convert_v1beta1_MachineDrainRuleDrainConfig_To_v1beta2_MachineDrainRuleDrainConfig(&in.Drain, &out.Drain, s); err != nil { + return err + } + out.Machines = *(*[]v1beta2.MachineDrainRuleMachineSelector)(unsafe.Pointer(&in.Machines)) + out.Pods = *(*[]v1beta2.MachineDrainRulePodSelector)(unsafe.Pointer(&in.Pods)) + return nil +} + +// Convert_v1beta1_MachineDrainRuleSpec_To_v1beta2_MachineDrainRuleSpec is an autogenerated conversion function. +func Convert_v1beta1_MachineDrainRuleSpec_To_v1beta2_MachineDrainRuleSpec(in *MachineDrainRuleSpec, out *v1beta2.MachineDrainRuleSpec, s conversion.Scope) error { + return autoConvert_v1beta1_MachineDrainRuleSpec_To_v1beta2_MachineDrainRuleSpec(in, out, s) +} + +func autoConvert_v1beta2_MachineDrainRuleSpec_To_v1beta1_MachineDrainRuleSpec(in *v1beta2.MachineDrainRuleSpec, out *MachineDrainRuleSpec, s conversion.Scope) error { + if err := Convert_v1beta2_MachineDrainRuleDrainConfig_To_v1beta1_MachineDrainRuleDrainConfig(&in.Drain, &out.Drain, s); err != nil { + return err + } + out.Machines = *(*[]MachineDrainRuleMachineSelector)(unsafe.Pointer(&in.Machines)) + out.Pods = *(*[]MachineDrainRulePodSelector)(unsafe.Pointer(&in.Pods)) + return nil +} + +// Convert_v1beta2_MachineDrainRuleSpec_To_v1beta1_MachineDrainRuleSpec is an autogenerated conversion function. +func Convert_v1beta2_MachineDrainRuleSpec_To_v1beta1_MachineDrainRuleSpec(in *v1beta2.MachineDrainRuleSpec, out *MachineDrainRuleSpec, s conversion.Scope) error { + return autoConvert_v1beta2_MachineDrainRuleSpec_To_v1beta1_MachineDrainRuleSpec(in, out, s) +} + +func autoConvert_v1beta1_MachineHealthCheck_To_v1beta2_MachineHealthCheck(in *MachineHealthCheck, out *v1beta2.MachineHealthCheck, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_MachineHealthCheckSpec_To_v1beta2_MachineHealthCheckSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta1_MachineHealthCheckStatus_To_v1beta2_MachineHealthCheckStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_MachineHealthCheck_To_v1beta2_MachineHealthCheck is an autogenerated conversion function. +func Convert_v1beta1_MachineHealthCheck_To_v1beta2_MachineHealthCheck(in *MachineHealthCheck, out *v1beta2.MachineHealthCheck, s conversion.Scope) error { + return autoConvert_v1beta1_MachineHealthCheck_To_v1beta2_MachineHealthCheck(in, out, s) +} + +func autoConvert_v1beta2_MachineHealthCheck_To_v1beta1_MachineHealthCheck(in *v1beta2.MachineHealthCheck, out *MachineHealthCheck, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta2_MachineHealthCheckSpec_To_v1beta1_MachineHealthCheckSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta2_MachineHealthCheckStatus_To_v1beta1_MachineHealthCheckStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_MachineHealthCheck_To_v1beta1_MachineHealthCheck is an autogenerated conversion function. +func Convert_v1beta2_MachineHealthCheck_To_v1beta1_MachineHealthCheck(in *v1beta2.MachineHealthCheck, out *MachineHealthCheck, s conversion.Scope) error { + return autoConvert_v1beta2_MachineHealthCheck_To_v1beta1_MachineHealthCheck(in, out, s) +} + +func autoConvert_v1beta1_MachineHealthCheckList_To_v1beta2_MachineHealthCheckList(in *MachineHealthCheckList, out *v1beta2.MachineHealthCheckList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]v1beta2.MachineHealthCheck, len(*in)) + for i := range *in { + if err := Convert_v1beta1_MachineHealthCheck_To_v1beta2_MachineHealthCheck(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta1_MachineHealthCheckList_To_v1beta2_MachineHealthCheckList is an autogenerated conversion function. +func Convert_v1beta1_MachineHealthCheckList_To_v1beta2_MachineHealthCheckList(in *MachineHealthCheckList, out *v1beta2.MachineHealthCheckList, s conversion.Scope) error { + return autoConvert_v1beta1_MachineHealthCheckList_To_v1beta2_MachineHealthCheckList(in, out, s) +} + +func autoConvert_v1beta2_MachineHealthCheckList_To_v1beta1_MachineHealthCheckList(in *v1beta2.MachineHealthCheckList, out *MachineHealthCheckList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachineHealthCheck, len(*in)) + for i := range *in { + if err := Convert_v1beta2_MachineHealthCheck_To_v1beta1_MachineHealthCheck(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta2_MachineHealthCheckList_To_v1beta1_MachineHealthCheckList is an autogenerated conversion function. +func Convert_v1beta2_MachineHealthCheckList_To_v1beta1_MachineHealthCheckList(in *v1beta2.MachineHealthCheckList, out *MachineHealthCheckList, s conversion.Scope) error { + return autoConvert_v1beta2_MachineHealthCheckList_To_v1beta1_MachineHealthCheckList(in, out, s) +} + +func autoConvert_v1beta1_MachineHealthCheckSpec_To_v1beta2_MachineHealthCheckSpec(in *MachineHealthCheckSpec, out *v1beta2.MachineHealthCheckSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + out.Selector = in.Selector + // WARNING: in.UnhealthyConditions requires manual conversion: does not exist in peer-type + // WARNING: in.MaxUnhealthy requires manual conversion: does not exist in peer-type + // WARNING: in.UnhealthyRange requires manual conversion: does not exist in peer-type + // WARNING: in.NodeStartupTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.RemediationTemplate requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineHealthCheckSpec_To_v1beta1_MachineHealthCheckSpec(in *v1beta2.MachineHealthCheckSpec, out *MachineHealthCheckSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + out.Selector = in.Selector + // WARNING: in.Checks requires manual conversion: does not exist in peer-type + // WARNING: in.Remediation requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachineHealthCheckStatus_To_v1beta2_MachineHealthCheckStatus(in *MachineHealthCheckStatus, out *v1beta2.MachineHealthCheckStatus, s conversion.Scope) error { + if err := v1.Convert_int32_To_Pointer_int32(&in.ExpectedMachines, &out.ExpectedMachines, s); err != nil { + return err + } + if err := v1.Convert_int32_To_Pointer_int32(&in.CurrentHealthy, &out.CurrentHealthy, s); err != nil { + return err + } + if err := v1.Convert_int32_To_Pointer_int32(&in.RemediationsAllowed, &out.RemediationsAllowed, s); err != nil { + return err + } + out.ObservedGeneration = in.ObservedGeneration + out.Targets = *(*[]string)(unsafe.Pointer(&in.Targets)) + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Condition_To_v1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineHealthCheckStatus_To_v1beta1_MachineHealthCheckStatus(in *v1beta2.MachineHealthCheckStatus, out *MachineHealthCheckStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + if err := Convert_v1_Condition_To_v1beta1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if err := v1.Convert_Pointer_int32_To_int32(&in.ExpectedMachines, &out.ExpectedMachines, s); err != nil { + return err + } + if err := v1.Convert_Pointer_int32_To_int32(&in.CurrentHealthy, &out.CurrentHealthy, s); err != nil { + return err + } + if err := v1.Convert_Pointer_int32_To_int32(&in.RemediationsAllowed, &out.RemediationsAllowed, s); err != nil { + return err + } + out.ObservedGeneration = in.ObservedGeneration + out.Targets = *(*[]string)(unsafe.Pointer(&in.Targets)) + // WARNING: in.Deprecated requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachineList_To_v1beta2_MachineList(in *MachineList, out *v1beta2.MachineList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]v1beta2.Machine, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Machine_To_v1beta2_Machine(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta1_MachineList_To_v1beta2_MachineList is an autogenerated conversion function. +func Convert_v1beta1_MachineList_To_v1beta2_MachineList(in *MachineList, out *v1beta2.MachineList, s conversion.Scope) error { + return autoConvert_v1beta1_MachineList_To_v1beta2_MachineList(in, out, s) +} + +func autoConvert_v1beta2_MachineList_To_v1beta1_MachineList(in *v1beta2.MachineList, out *MachineList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Machine, len(*in)) + for i := range *in { + if err := Convert_v1beta2_Machine_To_v1beta1_Machine(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta2_MachineList_To_v1beta1_MachineList is an autogenerated conversion function. +func Convert_v1beta2_MachineList_To_v1beta1_MachineList(in *v1beta2.MachineList, out *MachineList, s conversion.Scope) error { + return autoConvert_v1beta2_MachineList_To_v1beta1_MachineList(in, out, s) +} + +func autoConvert_v1beta1_MachinePool_To_v1beta2_MachinePool(in *MachinePool, out *v1beta2.MachinePool, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_MachinePoolSpec_To_v1beta2_MachinePoolSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta1_MachinePoolStatus_To_v1beta2_MachinePoolStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_MachinePool_To_v1beta2_MachinePool is an autogenerated conversion function. +func Convert_v1beta1_MachinePool_To_v1beta2_MachinePool(in *MachinePool, out *v1beta2.MachinePool, s conversion.Scope) error { + return autoConvert_v1beta1_MachinePool_To_v1beta2_MachinePool(in, out, s) +} + +func autoConvert_v1beta2_MachinePool_To_v1beta1_MachinePool(in *v1beta2.MachinePool, out *MachinePool, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta2_MachinePoolSpec_To_v1beta1_MachinePoolSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta2_MachinePoolStatus_To_v1beta1_MachinePoolStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_MachinePool_To_v1beta1_MachinePool is an autogenerated conversion function. +func Convert_v1beta2_MachinePool_To_v1beta1_MachinePool(in *v1beta2.MachinePool, out *MachinePool, s conversion.Scope) error { + return autoConvert_v1beta2_MachinePool_To_v1beta1_MachinePool(in, out, s) +} + +func autoConvert_v1beta1_MachinePoolClass_To_v1beta2_MachinePoolClass(in *MachinePoolClass, out *v1beta2.MachinePoolClass, s conversion.Scope) error { + out.Class = in.Class + // WARNING: in.Template requires manual conversion: does not exist in peer-type + out.FailureDomains = *(*[]string)(unsafe.Pointer(&in.FailureDomains)) + // WARNING: in.NamingStrategy requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDrainTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeVolumeDetachTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDeletionTimeout requires manual conversion: does not exist in peer-type + out.MinReadySeconds = (*int32)(unsafe.Pointer(in.MinReadySeconds)) + return nil +} + +func autoConvert_v1beta2_MachinePoolClass_To_v1beta1_MachinePoolClass(in *v1beta2.MachinePoolClass, out *MachinePoolClass, s conversion.Scope) error { + // WARNING: in.Metadata requires manual conversion: does not exist in peer-type + out.Class = in.Class + // WARNING: in.Bootstrap requires manual conversion: does not exist in peer-type + // WARNING: in.Infrastructure requires manual conversion: does not exist in peer-type + out.FailureDomains = *(*[]string)(unsafe.Pointer(&in.FailureDomains)) + // WARNING: in.Naming requires manual conversion: does not exist in peer-type + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + out.MinReadySeconds = (*int32)(unsafe.Pointer(in.MinReadySeconds)) + return nil +} + +func autoConvert_v1beta1_MachinePoolList_To_v1beta2_MachinePoolList(in *MachinePoolList, out *v1beta2.MachinePoolList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]v1beta2.MachinePool, len(*in)) + for i := range *in { + if err := Convert_v1beta1_MachinePool_To_v1beta2_MachinePool(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta1_MachinePoolList_To_v1beta2_MachinePoolList is an autogenerated conversion function. +func Convert_v1beta1_MachinePoolList_To_v1beta2_MachinePoolList(in *MachinePoolList, out *v1beta2.MachinePoolList, s conversion.Scope) error { + return autoConvert_v1beta1_MachinePoolList_To_v1beta2_MachinePoolList(in, out, s) +} + +func autoConvert_v1beta2_MachinePoolList_To_v1beta1_MachinePoolList(in *v1beta2.MachinePoolList, out *MachinePoolList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachinePool, len(*in)) + for i := range *in { + if err := Convert_v1beta2_MachinePool_To_v1beta1_MachinePool(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta2_MachinePoolList_To_v1beta1_MachinePoolList is an autogenerated conversion function. +func Convert_v1beta2_MachinePoolList_To_v1beta1_MachinePoolList(in *v1beta2.MachinePoolList, out *MachinePoolList, s conversion.Scope) error { + return autoConvert_v1beta2_MachinePoolList_To_v1beta1_MachinePoolList(in, out, s) +} + +func autoConvert_v1beta1_MachinePoolSpec_To_v1beta2_MachinePoolSpec(in *MachinePoolSpec, out *v1beta2.MachinePoolSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + if err := Convert_v1beta1_MachineTemplateSpec_To_v1beta2_MachineTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + // WARNING: in.MinReadySeconds requires manual conversion: does not exist in peer-type + out.ProviderIDList = *(*[]string)(unsafe.Pointer(&in.ProviderIDList)) + out.FailureDomains = *(*[]string)(unsafe.Pointer(&in.FailureDomains)) + return nil +} + +func autoConvert_v1beta2_MachinePoolSpec_To_v1beta1_MachinePoolSpec(in *v1beta2.MachinePoolSpec, out *MachinePoolSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + if err := Convert_v1beta2_MachineTemplateSpec_To_v1beta1_MachineTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + out.ProviderIDList = *(*[]string)(unsafe.Pointer(&in.ProviderIDList)) + out.FailureDomains = *(*[]string)(unsafe.Pointer(&in.FailureDomains)) + return nil +} + +// Convert_v1beta2_MachinePoolSpec_To_v1beta1_MachinePoolSpec is an autogenerated conversion function. +func Convert_v1beta2_MachinePoolSpec_To_v1beta1_MachinePoolSpec(in *v1beta2.MachinePoolSpec, out *MachinePoolSpec, s conversion.Scope) error { + return autoConvert_v1beta2_MachinePoolSpec_To_v1beta1_MachinePoolSpec(in, out, s) +} + +func autoConvert_v1beta1_MachinePoolStatus_To_v1beta2_MachinePoolStatus(in *MachinePoolStatus, out *v1beta2.MachinePoolStatus, s conversion.Scope) error { + out.NodeRefs = *(*[]corev1.ObjectReference)(unsafe.Pointer(&in.NodeRefs)) + if err := v1.Convert_int32_To_Pointer_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + if err := v1.Convert_int32_To_Pointer_int32(&in.ReadyReplicas, &out.ReadyReplicas, s); err != nil { + return err + } + if err := v1.Convert_int32_To_Pointer_int32(&in.AvailableReplicas, &out.AvailableReplicas, s); err != nil { + return err + } + // WARNING: in.UnavailableReplicas requires manual conversion: does not exist in peer-type + // WARNING: in.FailureReason requires manual conversion: does not exist in peer-type + // WARNING: in.FailureMessage requires manual conversion: does not exist in peer-type + out.Phase = in.Phase + // WARNING: in.BootstrapReady requires manual conversion: does not exist in peer-type + // WARNING: in.InfrastructureReady requires manual conversion: does not exist in peer-type + out.ObservedGeneration = in.ObservedGeneration + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Condition_To_v1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachinePoolStatus_To_v1beta1_MachinePoolStatus(in *v1beta2.MachinePoolStatus, out *MachinePoolStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + if err := Convert_v1_Condition_To_v1beta1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // WARNING: in.Initialization requires manual conversion: does not exist in peer-type + out.NodeRefs = *(*[]corev1.ObjectReference)(unsafe.Pointer(&in.NodeRefs)) + if err := v1.Convert_Pointer_int32_To_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + if err := v1.Convert_Pointer_int32_To_int32(&in.ReadyReplicas, &out.ReadyReplicas, s); err != nil { + return err + } + if err := v1.Convert_Pointer_int32_To_int32(&in.AvailableReplicas, &out.AvailableReplicas, s); err != nil { + return err + } + // WARNING: in.UpToDateReplicas requires manual conversion: does not exist in peer-type + out.Phase = in.Phase + out.ObservedGeneration = in.ObservedGeneration + // WARNING: in.Deprecated requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachinePoolTopology_To_v1beta2_MachinePoolTopology(in *MachinePoolTopology, out *v1beta2.MachinePoolTopology, s conversion.Scope) error { + if err := Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(&in.Metadata, &out.Metadata, s); err != nil { + return err + } + out.Class = in.Class + out.Name = in.Name + out.FailureDomains = *(*[]string)(unsafe.Pointer(&in.FailureDomains)) + // WARNING: in.NodeDrainTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeVolumeDetachTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDeletionTimeout requires manual conversion: does not exist in peer-type + out.MinReadySeconds = (*int32)(unsafe.Pointer(in.MinReadySeconds)) + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.Variables requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolVariables vs sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolVariables) + return nil +} + +func autoConvert_v1beta2_MachinePoolTopology_To_v1beta1_MachinePoolTopology(in *v1beta2.MachinePoolTopology, out *MachinePoolTopology, s conversion.Scope) error { + if err := Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(&in.Metadata, &out.Metadata, s); err != nil { + return err + } + out.Class = in.Class + out.Name = in.Name + out.FailureDomains = *(*[]string)(unsafe.Pointer(&in.FailureDomains)) + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + out.MinReadySeconds = (*int32)(unsafe.Pointer(in.MinReadySeconds)) + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.Variables requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolVariables vs *sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolVariables) + return nil +} + +func autoConvert_v1beta1_MachinePoolVariables_To_v1beta2_MachinePoolVariables(in *MachinePoolVariables, out *v1beta2.MachinePoolVariables, s conversion.Scope) error { + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]v1beta2.ClusterVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterVariable_To_v1beta2_ClusterVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Overrides = nil + } + return nil +} + +// Convert_v1beta1_MachinePoolVariables_To_v1beta2_MachinePoolVariables is an autogenerated conversion function. +func Convert_v1beta1_MachinePoolVariables_To_v1beta2_MachinePoolVariables(in *MachinePoolVariables, out *v1beta2.MachinePoolVariables, s conversion.Scope) error { + return autoConvert_v1beta1_MachinePoolVariables_To_v1beta2_MachinePoolVariables(in, out, s) +} + +func autoConvert_v1beta2_MachinePoolVariables_To_v1beta1_MachinePoolVariables(in *v1beta2.MachinePoolVariables, out *MachinePoolVariables, s conversion.Scope) error { + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]ClusterVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Overrides = nil + } + return nil +} + +// Convert_v1beta2_MachinePoolVariables_To_v1beta1_MachinePoolVariables is an autogenerated conversion function. +func Convert_v1beta2_MachinePoolVariables_To_v1beta1_MachinePoolVariables(in *v1beta2.MachinePoolVariables, out *MachinePoolVariables, s conversion.Scope) error { + return autoConvert_v1beta2_MachinePoolVariables_To_v1beta1_MachinePoolVariables(in, out, s) +} + +func autoConvert_v1beta1_MachineReadinessGate_To_v1beta2_MachineReadinessGate(in *MachineReadinessGate, out *v1beta2.MachineReadinessGate, s conversion.Scope) error { + out.ConditionType = in.ConditionType + out.Polarity = v1beta2.ConditionPolarity(in.Polarity) + return nil +} + +// Convert_v1beta1_MachineReadinessGate_To_v1beta2_MachineReadinessGate is an autogenerated conversion function. +func Convert_v1beta1_MachineReadinessGate_To_v1beta2_MachineReadinessGate(in *MachineReadinessGate, out *v1beta2.MachineReadinessGate, s conversion.Scope) error { + return autoConvert_v1beta1_MachineReadinessGate_To_v1beta2_MachineReadinessGate(in, out, s) +} + +func autoConvert_v1beta2_MachineReadinessGate_To_v1beta1_MachineReadinessGate(in *v1beta2.MachineReadinessGate, out *MachineReadinessGate, s conversion.Scope) error { + out.ConditionType = in.ConditionType + out.Polarity = ConditionPolarity(in.Polarity) + return nil +} + +// Convert_v1beta2_MachineReadinessGate_To_v1beta1_MachineReadinessGate is an autogenerated conversion function. +func Convert_v1beta2_MachineReadinessGate_To_v1beta1_MachineReadinessGate(in *v1beta2.MachineReadinessGate, out *MachineReadinessGate, s conversion.Scope) error { + return autoConvert_v1beta2_MachineReadinessGate_To_v1beta1_MachineReadinessGate(in, out, s) +} + +func autoConvert_v1beta1_MachineSet_To_v1beta2_MachineSet(in *MachineSet, out *v1beta2.MachineSet, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta1_MachineSetSpec_To_v1beta2_MachineSetSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta1_MachineSetStatus_To_v1beta2_MachineSetStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_MachineSet_To_v1beta2_MachineSet is an autogenerated conversion function. +func Convert_v1beta1_MachineSet_To_v1beta2_MachineSet(in *MachineSet, out *v1beta2.MachineSet, s conversion.Scope) error { + return autoConvert_v1beta1_MachineSet_To_v1beta2_MachineSet(in, out, s) +} + +func autoConvert_v1beta2_MachineSet_To_v1beta1_MachineSet(in *v1beta2.MachineSet, out *MachineSet, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1beta2_MachineSetSpec_To_v1beta1_MachineSetSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1beta2_MachineSetStatus_To_v1beta1_MachineSetStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_MachineSet_To_v1beta1_MachineSet is an autogenerated conversion function. +func Convert_v1beta2_MachineSet_To_v1beta1_MachineSet(in *v1beta2.MachineSet, out *MachineSet, s conversion.Scope) error { + return autoConvert_v1beta2_MachineSet_To_v1beta1_MachineSet(in, out, s) +} + +func autoConvert_v1beta1_MachineSetList_To_v1beta2_MachineSetList(in *MachineSetList, out *v1beta2.MachineSetList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]v1beta2.MachineSet, len(*in)) + for i := range *in { + if err := Convert_v1beta1_MachineSet_To_v1beta2_MachineSet(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta1_MachineSetList_To_v1beta2_MachineSetList is an autogenerated conversion function. +func Convert_v1beta1_MachineSetList_To_v1beta2_MachineSetList(in *MachineSetList, out *v1beta2.MachineSetList, s conversion.Scope) error { + return autoConvert_v1beta1_MachineSetList_To_v1beta2_MachineSetList(in, out, s) +} + +func autoConvert_v1beta2_MachineSetList_To_v1beta1_MachineSetList(in *v1beta2.MachineSetList, out *MachineSetList, s conversion.Scope) error { + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachineSet, len(*in)) + for i := range *in { + if err := Convert_v1beta2_MachineSet_To_v1beta1_MachineSet(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +// Convert_v1beta2_MachineSetList_To_v1beta1_MachineSetList is an autogenerated conversion function. +func Convert_v1beta2_MachineSetList_To_v1beta1_MachineSetList(in *v1beta2.MachineSetList, out *MachineSetList, s conversion.Scope) error { + return autoConvert_v1beta2_MachineSetList_To_v1beta1_MachineSetList(in, out, s) +} + +func autoConvert_v1beta1_MachineSetSpec_To_v1beta2_MachineSetSpec(in *MachineSetSpec, out *v1beta2.MachineSetSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + // WARNING: in.MinReadySeconds requires manual conversion: does not exist in peer-type + // WARNING: in.DeletePolicy requires manual conversion: does not exist in peer-type + out.Selector = in.Selector + if err := Convert_v1beta1_MachineTemplateSpec_To_v1beta2_MachineTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + // WARNING: in.MachineNamingStrategy requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineSetSpec_To_v1beta1_MachineSetSpec(in *v1beta2.MachineSetSpec, out *MachineSetSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + out.Selector = in.Selector + if err := Convert_v1beta2_MachineTemplateSpec_To_v1beta1_MachineTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + // WARNING: in.MachineNaming requires manual conversion: does not exist in peer-type + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachineSetStatus_To_v1beta2_MachineSetStatus(in *MachineSetStatus, out *v1beta2.MachineSetStatus, s conversion.Scope) error { + out.Selector = in.Selector + if err := v1.Convert_int32_To_Pointer_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + // WARNING: in.FullyLabeledReplicas requires manual conversion: does not exist in peer-type + if err := v1.Convert_int32_To_Pointer_int32(&in.ReadyReplicas, &out.ReadyReplicas, s); err != nil { + return err + } + if err := v1.Convert_int32_To_Pointer_int32(&in.AvailableReplicas, &out.AvailableReplicas, s); err != nil { + return err + } + out.ObservedGeneration = in.ObservedGeneration + // WARNING: in.FailureReason requires manual conversion: does not exist in peer-type + // WARNING: in.FailureMessage requires manual conversion: does not exist in peer-type + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Condition_To_v1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineSetStatus_To_v1beta1_MachineSetStatus(in *v1beta2.MachineSetStatus, out *MachineSetStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + if err := Convert_v1_Condition_To_v1beta1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + out.Selector = in.Selector + if err := v1.Convert_Pointer_int32_To_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + if err := v1.Convert_Pointer_int32_To_int32(&in.ReadyReplicas, &out.ReadyReplicas, s); err != nil { + return err + } + if err := v1.Convert_Pointer_int32_To_int32(&in.AvailableReplicas, &out.AvailableReplicas, s); err != nil { + return err + } + // WARNING: in.UpToDateReplicas requires manual conversion: does not exist in peer-type + out.ObservedGeneration = in.ObservedGeneration + // WARNING: in.Deprecated requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachineSpec_To_v1beta2_MachineSpec(in *MachineSpec, out *v1beta2.MachineSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + if err := Convert_v1beta1_Bootstrap_To_v1beta2_Bootstrap(&in.Bootstrap, &out.Bootstrap, s); err != nil { + return err + } + if err := Convert_v1_ObjectReference_To_v1beta2_ContractVersionedObjectReference(&in.InfrastructureRef, &out.InfrastructureRef, s); err != nil { + return err + } + if err := v1.Convert_Pointer_string_To_string(&in.Version, &out.Version, s); err != nil { + return err + } + if err := v1.Convert_Pointer_string_To_string(&in.ProviderID, &out.ProviderID, s); err != nil { + return err + } + if err := v1.Convert_Pointer_string_To_string(&in.FailureDomain, &out.FailureDomain, s); err != nil { + return err + } + out.ReadinessGates = *(*[]v1beta2.MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + // WARNING: in.NodeDrainTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeVolumeDetachTimeout requires manual conversion: does not exist in peer-type + // WARNING: in.NodeDeletionTimeout requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineSpec_To_v1beta1_MachineSpec(in *v1beta2.MachineSpec, out *MachineSpec, s conversion.Scope) error { + out.ClusterName = in.ClusterName + if err := Convert_v1beta2_Bootstrap_To_v1beta1_Bootstrap(&in.Bootstrap, &out.Bootstrap, s); err != nil { + return err + } + if err := Convert_v1beta2_ContractVersionedObjectReference_To_v1_ObjectReference(&in.InfrastructureRef, &out.InfrastructureRef, s); err != nil { + return err + } + if err := v1.Convert_string_To_Pointer_string(&in.Version, &out.Version, s); err != nil { + return err + } + if err := v1.Convert_string_To_Pointer_string(&in.ProviderID, &out.ProviderID, s); err != nil { + return err + } + if err := v1.Convert_string_To_Pointer_string(&in.FailureDomain, &out.FailureDomain, s); err != nil { + return err + } + // WARNING: in.MinReadySeconds requires manual conversion: does not exist in peer-type + out.ReadinessGates = *(*[]MachineReadinessGate)(unsafe.Pointer(&in.ReadinessGates)) + // WARNING: in.Deletion requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachineStatus_To_v1beta2_MachineStatus(in *MachineStatus, out *v1beta2.MachineStatus, s conversion.Scope) error { + // WARNING: in.NodeRef requires manual conversion: inconvertible types (*k8s.io/api/core/v1.ObjectReference vs sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNodeReference) + out.NodeInfo = (*corev1.NodeSystemInfo)(unsafe.Pointer(in.NodeInfo)) + // WARNING: in.LastUpdated requires manual conversion: inconvertible types (*k8s.io/apimachinery/pkg/apis/meta/v1.Time vs k8s.io/apimachinery/pkg/apis/meta/v1.Time) + // WARNING: in.FailureReason requires manual conversion: does not exist in peer-type + // WARNING: in.FailureMessage requires manual conversion: does not exist in peer-type + out.Addresses = *(*v1beta2.MachineAddresses)(unsafe.Pointer(&in.Addresses)) + out.Phase = in.Phase + // WARNING: in.CertificatesExpiryDate requires manual conversion: inconvertible types (*k8s.io/apimachinery/pkg/apis/meta/v1.Time vs k8s.io/apimachinery/pkg/apis/meta/v1.Time) + // WARNING: in.BootstrapReady requires manual conversion: does not exist in peer-type + // WARNING: in.InfrastructureReady requires manual conversion: does not exist in peer-type + out.ObservedGeneration = in.ObservedGeneration + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + if err := Convert_v1beta1_Condition_To_v1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.Deletion != nil { + in, out := &in.Deletion, &out.Deletion + *out = new(v1beta2.MachineDeletionStatus) + if err := Convert_v1beta1_MachineDeletionStatus_To_v1beta2_MachineDeletionStatus(*in, *out, s); err != nil { + return err + } + } else { + out.Deletion = nil + } + // WARNING: in.V1Beta2 requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta2_MachineStatus_To_v1beta1_MachineStatus(in *v1beta2.MachineStatus, out *MachineStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + if err := Convert_v1_Condition_To_v1beta1_Condition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // WARNING: in.Initialization requires manual conversion: does not exist in peer-type + // WARNING: in.NodeRef requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNodeReference vs *k8s.io/api/core/v1.ObjectReference) + out.NodeInfo = (*corev1.NodeSystemInfo)(unsafe.Pointer(in.NodeInfo)) + // WARNING: in.LastUpdated requires manual conversion: inconvertible types (k8s.io/apimachinery/pkg/apis/meta/v1.Time vs *k8s.io/apimachinery/pkg/apis/meta/v1.Time) + out.Addresses = *(*MachineAddresses)(unsafe.Pointer(&in.Addresses)) + out.Phase = in.Phase + // WARNING: in.CertificatesExpiryDate requires manual conversion: inconvertible types (k8s.io/apimachinery/pkg/apis/meta/v1.Time vs *k8s.io/apimachinery/pkg/apis/meta/v1.Time) + out.ObservedGeneration = in.ObservedGeneration + if in.Deletion != nil { + in, out := &in.Deletion, &out.Deletion + *out = new(MachineDeletionStatus) + if err := Convert_v1beta2_MachineDeletionStatus_To_v1beta1_MachineDeletionStatus(*in, *out, s); err != nil { + return err + } + } else { + out.Deletion = nil + } + // WARNING: in.Deprecated requires manual conversion: does not exist in peer-type + return nil +} + +func autoConvert_v1beta1_MachineTemplateSpec_To_v1beta2_MachineTemplateSpec(in *MachineTemplateSpec, out *v1beta2.MachineTemplateSpec, s conversion.Scope) error { + if err := Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, s); err != nil { + return err + } + if err := Convert_v1beta1_MachineSpec_To_v1beta2_MachineSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_MachineTemplateSpec_To_v1beta2_MachineTemplateSpec is an autogenerated conversion function. +func Convert_v1beta1_MachineTemplateSpec_To_v1beta2_MachineTemplateSpec(in *MachineTemplateSpec, out *v1beta2.MachineTemplateSpec, s conversion.Scope) error { + return autoConvert_v1beta1_MachineTemplateSpec_To_v1beta2_MachineTemplateSpec(in, out, s) +} + +func autoConvert_v1beta2_MachineTemplateSpec_To_v1beta1_MachineTemplateSpec(in *v1beta2.MachineTemplateSpec, out *MachineTemplateSpec, s conversion.Scope) error { + if err := Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, s); err != nil { + return err + } + if err := Convert_v1beta2_MachineSpec_To_v1beta1_MachineSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_MachineTemplateSpec_To_v1beta1_MachineTemplateSpec is an autogenerated conversion function. +func Convert_v1beta2_MachineTemplateSpec_To_v1beta1_MachineTemplateSpec(in *v1beta2.MachineTemplateSpec, out *MachineTemplateSpec, s conversion.Scope) error { + return autoConvert_v1beta2_MachineTemplateSpec_To_v1beta1_MachineTemplateSpec(in, out, s) +} + +func autoConvert_v1beta1_NetworkRanges_To_v1beta2_NetworkRanges(in *NetworkRanges, out *v1beta2.NetworkRanges, s conversion.Scope) error { + out.CIDRBlocks = *(*[]string)(unsafe.Pointer(&in.CIDRBlocks)) + return nil +} + +// Convert_v1beta1_NetworkRanges_To_v1beta2_NetworkRanges is an autogenerated conversion function. +func Convert_v1beta1_NetworkRanges_To_v1beta2_NetworkRanges(in *NetworkRanges, out *v1beta2.NetworkRanges, s conversion.Scope) error { + return autoConvert_v1beta1_NetworkRanges_To_v1beta2_NetworkRanges(in, out, s) +} + +func autoConvert_v1beta2_NetworkRanges_To_v1beta1_NetworkRanges(in *v1beta2.NetworkRanges, out *NetworkRanges, s conversion.Scope) error { + out.CIDRBlocks = *(*[]string)(unsafe.Pointer(&in.CIDRBlocks)) + return nil +} + +// Convert_v1beta2_NetworkRanges_To_v1beta1_NetworkRanges is an autogenerated conversion function. +func Convert_v1beta2_NetworkRanges_To_v1beta1_NetworkRanges(in *v1beta2.NetworkRanges, out *NetworkRanges, s conversion.Scope) error { + return autoConvert_v1beta2_NetworkRanges_To_v1beta1_NetworkRanges(in, out, s) +} + +func autoConvert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(in *ObjectMeta, out *v1beta2.ObjectMeta, s conversion.Scope) error { + out.Labels = *(*map[string]string)(unsafe.Pointer(&in.Labels)) + out.Annotations = *(*map[string]string)(unsafe.Pointer(&in.Annotations)) + return nil +} + +// Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta is an autogenerated conversion function. +func Convert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(in *ObjectMeta, out *v1beta2.ObjectMeta, s conversion.Scope) error { + return autoConvert_v1beta1_ObjectMeta_To_v1beta2_ObjectMeta(in, out, s) +} + +func autoConvert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(in *v1beta2.ObjectMeta, out *ObjectMeta, s conversion.Scope) error { + out.Labels = *(*map[string]string)(unsafe.Pointer(&in.Labels)) + out.Annotations = *(*map[string]string)(unsafe.Pointer(&in.Annotations)) + return nil +} + +// Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta is an autogenerated conversion function. +func Convert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(in *v1beta2.ObjectMeta, out *ObjectMeta, s conversion.Scope) error { + return autoConvert_v1beta2_ObjectMeta_To_v1beta1_ObjectMeta(in, out, s) +} + +func autoConvert_v1beta1_PatchDefinition_To_v1beta2_PatchDefinition(in *PatchDefinition, out *v1beta2.PatchDefinition, s conversion.Scope) error { + if err := Convert_v1beta1_PatchSelector_To_v1beta2_PatchSelector(&in.Selector, &out.Selector, s); err != nil { + return err + } + if in.JSONPatches != nil { + in, out := &in.JSONPatches, &out.JSONPatches + *out = make([]v1beta2.JSONPatch, len(*in)) + for i := range *in { + if err := Convert_v1beta1_JSONPatch_To_v1beta2_JSONPatch(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.JSONPatches = nil + } + return nil +} + +// Convert_v1beta1_PatchDefinition_To_v1beta2_PatchDefinition is an autogenerated conversion function. +func Convert_v1beta1_PatchDefinition_To_v1beta2_PatchDefinition(in *PatchDefinition, out *v1beta2.PatchDefinition, s conversion.Scope) error { + return autoConvert_v1beta1_PatchDefinition_To_v1beta2_PatchDefinition(in, out, s) +} + +func autoConvert_v1beta2_PatchDefinition_To_v1beta1_PatchDefinition(in *v1beta2.PatchDefinition, out *PatchDefinition, s conversion.Scope) error { + if err := Convert_v1beta2_PatchSelector_To_v1beta1_PatchSelector(&in.Selector, &out.Selector, s); err != nil { + return err + } + if in.JSONPatches != nil { + in, out := &in.JSONPatches, &out.JSONPatches + *out = make([]JSONPatch, len(*in)) + for i := range *in { + if err := Convert_v1beta2_JSONPatch_To_v1beta1_JSONPatch(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.JSONPatches = nil + } + return nil +} + +// Convert_v1beta2_PatchDefinition_To_v1beta1_PatchDefinition is an autogenerated conversion function. +func Convert_v1beta2_PatchDefinition_To_v1beta1_PatchDefinition(in *v1beta2.PatchDefinition, out *PatchDefinition, s conversion.Scope) error { + return autoConvert_v1beta2_PatchDefinition_To_v1beta1_PatchDefinition(in, out, s) +} + +func autoConvert_v1beta1_PatchSelector_To_v1beta2_PatchSelector(in *PatchSelector, out *v1beta2.PatchSelector, s conversion.Scope) error { + out.APIVersion = in.APIVersion + out.Kind = in.Kind + if err := Convert_v1beta1_PatchSelectorMatch_To_v1beta2_PatchSelectorMatch(&in.MatchResources, &out.MatchResources, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_PatchSelector_To_v1beta2_PatchSelector is an autogenerated conversion function. +func Convert_v1beta1_PatchSelector_To_v1beta2_PatchSelector(in *PatchSelector, out *v1beta2.PatchSelector, s conversion.Scope) error { + return autoConvert_v1beta1_PatchSelector_To_v1beta2_PatchSelector(in, out, s) +} + +func autoConvert_v1beta2_PatchSelector_To_v1beta1_PatchSelector(in *v1beta2.PatchSelector, out *PatchSelector, s conversion.Scope) error { + out.APIVersion = in.APIVersion + out.Kind = in.Kind + if err := Convert_v1beta2_PatchSelectorMatch_To_v1beta1_PatchSelectorMatch(&in.MatchResources, &out.MatchResources, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_PatchSelector_To_v1beta1_PatchSelector is an autogenerated conversion function. +func Convert_v1beta2_PatchSelector_To_v1beta1_PatchSelector(in *v1beta2.PatchSelector, out *PatchSelector, s conversion.Scope) error { + return autoConvert_v1beta2_PatchSelector_To_v1beta1_PatchSelector(in, out, s) +} + +func autoConvert_v1beta1_PatchSelectorMatch_To_v1beta2_PatchSelectorMatch(in *PatchSelectorMatch, out *v1beta2.PatchSelectorMatch, s conversion.Scope) error { + if err := v1.Convert_bool_To_Pointer_bool(&in.ControlPlane, &out.ControlPlane, s); err != nil { + return err + } + if err := v1.Convert_bool_To_Pointer_bool(&in.InfrastructureCluster, &out.InfrastructureCluster, s); err != nil { + return err + } + out.MachineDeploymentClass = (*v1beta2.PatchSelectorMatchMachineDeploymentClass)(unsafe.Pointer(in.MachineDeploymentClass)) + out.MachinePoolClass = (*v1beta2.PatchSelectorMatchMachinePoolClass)(unsafe.Pointer(in.MachinePoolClass)) + return nil +} + +// Convert_v1beta1_PatchSelectorMatch_To_v1beta2_PatchSelectorMatch is an autogenerated conversion function. +func Convert_v1beta1_PatchSelectorMatch_To_v1beta2_PatchSelectorMatch(in *PatchSelectorMatch, out *v1beta2.PatchSelectorMatch, s conversion.Scope) error { + return autoConvert_v1beta1_PatchSelectorMatch_To_v1beta2_PatchSelectorMatch(in, out, s) +} + +func autoConvert_v1beta2_PatchSelectorMatch_To_v1beta1_PatchSelectorMatch(in *v1beta2.PatchSelectorMatch, out *PatchSelectorMatch, s conversion.Scope) error { + if err := v1.Convert_Pointer_bool_To_bool(&in.ControlPlane, &out.ControlPlane, s); err != nil { + return err + } + if err := v1.Convert_Pointer_bool_To_bool(&in.InfrastructureCluster, &out.InfrastructureCluster, s); err != nil { + return err + } + out.MachineDeploymentClass = (*PatchSelectorMatchMachineDeploymentClass)(unsafe.Pointer(in.MachineDeploymentClass)) + out.MachinePoolClass = (*PatchSelectorMatchMachinePoolClass)(unsafe.Pointer(in.MachinePoolClass)) + return nil +} + +// Convert_v1beta2_PatchSelectorMatch_To_v1beta1_PatchSelectorMatch is an autogenerated conversion function. +func Convert_v1beta2_PatchSelectorMatch_To_v1beta1_PatchSelectorMatch(in *v1beta2.PatchSelectorMatch, out *PatchSelectorMatch, s conversion.Scope) error { + return autoConvert_v1beta2_PatchSelectorMatch_To_v1beta1_PatchSelectorMatch(in, out, s) +} + +func autoConvert_v1beta1_PatchSelectorMatchMachineDeploymentClass_To_v1beta2_PatchSelectorMatchMachineDeploymentClass(in *PatchSelectorMatchMachineDeploymentClass, out *v1beta2.PatchSelectorMatchMachineDeploymentClass, s conversion.Scope) error { + out.Names = *(*[]string)(unsafe.Pointer(&in.Names)) + return nil +} + +// Convert_v1beta1_PatchSelectorMatchMachineDeploymentClass_To_v1beta2_PatchSelectorMatchMachineDeploymentClass is an autogenerated conversion function. +func Convert_v1beta1_PatchSelectorMatchMachineDeploymentClass_To_v1beta2_PatchSelectorMatchMachineDeploymentClass(in *PatchSelectorMatchMachineDeploymentClass, out *v1beta2.PatchSelectorMatchMachineDeploymentClass, s conversion.Scope) error { + return autoConvert_v1beta1_PatchSelectorMatchMachineDeploymentClass_To_v1beta2_PatchSelectorMatchMachineDeploymentClass(in, out, s) +} + +func autoConvert_v1beta2_PatchSelectorMatchMachineDeploymentClass_To_v1beta1_PatchSelectorMatchMachineDeploymentClass(in *v1beta2.PatchSelectorMatchMachineDeploymentClass, out *PatchSelectorMatchMachineDeploymentClass, s conversion.Scope) error { + out.Names = *(*[]string)(unsafe.Pointer(&in.Names)) + return nil +} + +// Convert_v1beta2_PatchSelectorMatchMachineDeploymentClass_To_v1beta1_PatchSelectorMatchMachineDeploymentClass is an autogenerated conversion function. +func Convert_v1beta2_PatchSelectorMatchMachineDeploymentClass_To_v1beta1_PatchSelectorMatchMachineDeploymentClass(in *v1beta2.PatchSelectorMatchMachineDeploymentClass, out *PatchSelectorMatchMachineDeploymentClass, s conversion.Scope) error { + return autoConvert_v1beta2_PatchSelectorMatchMachineDeploymentClass_To_v1beta1_PatchSelectorMatchMachineDeploymentClass(in, out, s) +} + +func autoConvert_v1beta1_PatchSelectorMatchMachinePoolClass_To_v1beta2_PatchSelectorMatchMachinePoolClass(in *PatchSelectorMatchMachinePoolClass, out *v1beta2.PatchSelectorMatchMachinePoolClass, s conversion.Scope) error { + out.Names = *(*[]string)(unsafe.Pointer(&in.Names)) + return nil +} + +// Convert_v1beta1_PatchSelectorMatchMachinePoolClass_To_v1beta2_PatchSelectorMatchMachinePoolClass is an autogenerated conversion function. +func Convert_v1beta1_PatchSelectorMatchMachinePoolClass_To_v1beta2_PatchSelectorMatchMachinePoolClass(in *PatchSelectorMatchMachinePoolClass, out *v1beta2.PatchSelectorMatchMachinePoolClass, s conversion.Scope) error { + return autoConvert_v1beta1_PatchSelectorMatchMachinePoolClass_To_v1beta2_PatchSelectorMatchMachinePoolClass(in, out, s) +} + +func autoConvert_v1beta2_PatchSelectorMatchMachinePoolClass_To_v1beta1_PatchSelectorMatchMachinePoolClass(in *v1beta2.PatchSelectorMatchMachinePoolClass, out *PatchSelectorMatchMachinePoolClass, s conversion.Scope) error { + out.Names = *(*[]string)(unsafe.Pointer(&in.Names)) + return nil +} + +// Convert_v1beta2_PatchSelectorMatchMachinePoolClass_To_v1beta1_PatchSelectorMatchMachinePoolClass is an autogenerated conversion function. +func Convert_v1beta2_PatchSelectorMatchMachinePoolClass_To_v1beta1_PatchSelectorMatchMachinePoolClass(in *v1beta2.PatchSelectorMatchMachinePoolClass, out *PatchSelectorMatchMachinePoolClass, s conversion.Scope) error { + return autoConvert_v1beta2_PatchSelectorMatchMachinePoolClass_To_v1beta1_PatchSelectorMatchMachinePoolClass(in, out, s) +} + +func autoConvert_v1beta1_Topology_To_v1beta2_Topology(in *Topology, out *v1beta2.Topology, s conversion.Scope) error { + // WARNING: in.Class requires manual conversion: does not exist in peer-type + // WARNING: in.ClassNamespace requires manual conversion: does not exist in peer-type + out.Version = in.Version + // WARNING: in.RolloutAfter requires manual conversion: does not exist in peer-type + if err := Convert_v1beta1_ControlPlaneTopology_To_v1beta2_ControlPlaneTopology(&in.ControlPlane, &out.ControlPlane, s); err != nil { + return err + } + // WARNING: in.Workers requires manual conversion: inconvertible types (*sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersTopology vs sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersTopology) + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]v1beta2.ClusterVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta1_ClusterVariable_To_v1beta2_ClusterVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Variables = nil + } + return nil +} + +func autoConvert_v1beta2_Topology_To_v1beta1_Topology(in *v1beta2.Topology, out *Topology, s conversion.Scope) error { + // WARNING: in.ClassRef requires manual conversion: does not exist in peer-type + out.Version = in.Version + if err := Convert_v1beta2_ControlPlaneTopology_To_v1beta1_ControlPlaneTopology(&in.ControlPlane, &out.ControlPlane, s); err != nil { + return err + } + // WARNING: in.Workers requires manual conversion: inconvertible types (sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersTopology vs *sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersTopology) + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]ClusterVariable, len(*in)) + for i := range *in { + if err := Convert_v1beta2_ClusterVariable_To_v1beta1_ClusterVariable(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Variables = nil + } + return nil +} + +func autoConvert_v1beta1_ValidationRule_To_v1beta2_ValidationRule(in *ValidationRule, out *v1beta2.ValidationRule, s conversion.Scope) error { + out.Rule = in.Rule + out.Message = in.Message + out.MessageExpression = in.MessageExpression + out.Reason = v1beta2.FieldValueErrorReason(in.Reason) + out.FieldPath = in.FieldPath + return nil +} + +// Convert_v1beta1_ValidationRule_To_v1beta2_ValidationRule is an autogenerated conversion function. +func Convert_v1beta1_ValidationRule_To_v1beta2_ValidationRule(in *ValidationRule, out *v1beta2.ValidationRule, s conversion.Scope) error { + return autoConvert_v1beta1_ValidationRule_To_v1beta2_ValidationRule(in, out, s) +} + +func autoConvert_v1beta2_ValidationRule_To_v1beta1_ValidationRule(in *v1beta2.ValidationRule, out *ValidationRule, s conversion.Scope) error { + out.Rule = in.Rule + out.Message = in.Message + out.MessageExpression = in.MessageExpression + out.Reason = FieldValueErrorReason(in.Reason) + out.FieldPath = in.FieldPath + return nil +} + +// Convert_v1beta2_ValidationRule_To_v1beta1_ValidationRule is an autogenerated conversion function. +func Convert_v1beta2_ValidationRule_To_v1beta1_ValidationRule(in *v1beta2.ValidationRule, out *ValidationRule, s conversion.Scope) error { + return autoConvert_v1beta2_ValidationRule_To_v1beta1_ValidationRule(in, out, s) +} + +func autoConvert_v1beta1_VariableSchema_To_v1beta2_VariableSchema(in *VariableSchema, out *v1beta2.VariableSchema, s conversion.Scope) error { + if err := Convert_v1beta1_JSONSchemaProps_To_v1beta2_JSONSchemaProps(&in.OpenAPIV3Schema, &out.OpenAPIV3Schema, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta1_VariableSchema_To_v1beta2_VariableSchema is an autogenerated conversion function. +func Convert_v1beta1_VariableSchema_To_v1beta2_VariableSchema(in *VariableSchema, out *v1beta2.VariableSchema, s conversion.Scope) error { + return autoConvert_v1beta1_VariableSchema_To_v1beta2_VariableSchema(in, out, s) +} + +func autoConvert_v1beta2_VariableSchema_To_v1beta1_VariableSchema(in *v1beta2.VariableSchema, out *VariableSchema, s conversion.Scope) error { + if err := Convert_v1beta2_JSONSchemaProps_To_v1beta1_JSONSchemaProps(&in.OpenAPIV3Schema, &out.OpenAPIV3Schema, s); err != nil { + return err + } + return nil +} + +// Convert_v1beta2_VariableSchema_To_v1beta1_VariableSchema is an autogenerated conversion function. +func Convert_v1beta2_VariableSchema_To_v1beta1_VariableSchema(in *v1beta2.VariableSchema, out *VariableSchema, s conversion.Scope) error { + return autoConvert_v1beta2_VariableSchema_To_v1beta1_VariableSchema(in, out, s) +} + +func autoConvert_v1beta1_VariableSchemaMetadata_To_v1beta2_VariableSchemaMetadata(in *VariableSchemaMetadata, out *v1beta2.VariableSchemaMetadata, s conversion.Scope) error { + out.Labels = *(*map[string]string)(unsafe.Pointer(&in.Labels)) + out.Annotations = *(*map[string]string)(unsafe.Pointer(&in.Annotations)) + return nil +} + +// Convert_v1beta1_VariableSchemaMetadata_To_v1beta2_VariableSchemaMetadata is an autogenerated conversion function. +func Convert_v1beta1_VariableSchemaMetadata_To_v1beta2_VariableSchemaMetadata(in *VariableSchemaMetadata, out *v1beta2.VariableSchemaMetadata, s conversion.Scope) error { + return autoConvert_v1beta1_VariableSchemaMetadata_To_v1beta2_VariableSchemaMetadata(in, out, s) +} + +func autoConvert_v1beta2_VariableSchemaMetadata_To_v1beta1_VariableSchemaMetadata(in *v1beta2.VariableSchemaMetadata, out *VariableSchemaMetadata, s conversion.Scope) error { + out.Labels = *(*map[string]string)(unsafe.Pointer(&in.Labels)) + out.Annotations = *(*map[string]string)(unsafe.Pointer(&in.Annotations)) + return nil +} + +// Convert_v1beta2_VariableSchemaMetadata_To_v1beta1_VariableSchemaMetadata is an autogenerated conversion function. +func Convert_v1beta2_VariableSchemaMetadata_To_v1beta1_VariableSchemaMetadata(in *v1beta2.VariableSchemaMetadata, out *VariableSchemaMetadata, s conversion.Scope) error { + return autoConvert_v1beta2_VariableSchemaMetadata_To_v1beta1_VariableSchemaMetadata(in, out, s) +} + +func autoConvert_v1beta1_WorkersClass_To_v1beta2_WorkersClass(in *WorkersClass, out *v1beta2.WorkersClass, s conversion.Scope) error { + if in.MachineDeployments != nil { + in, out := &in.MachineDeployments, &out.MachineDeployments + *out = make([]v1beta2.MachineDeploymentClass, len(*in)) + for i := range *in { + if err := Convert_v1beta1_MachineDeploymentClass_To_v1beta2_MachineDeploymentClass(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.MachineDeployments = nil + } + if in.MachinePools != nil { + in, out := &in.MachinePools, &out.MachinePools + *out = make([]v1beta2.MachinePoolClass, len(*in)) + for i := range *in { + if err := Convert_v1beta1_MachinePoolClass_To_v1beta2_MachinePoolClass(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.MachinePools = nil + } + return nil +} + +// Convert_v1beta1_WorkersClass_To_v1beta2_WorkersClass is an autogenerated conversion function. +func Convert_v1beta1_WorkersClass_To_v1beta2_WorkersClass(in *WorkersClass, out *v1beta2.WorkersClass, s conversion.Scope) error { + return autoConvert_v1beta1_WorkersClass_To_v1beta2_WorkersClass(in, out, s) +} + +func autoConvert_v1beta2_WorkersClass_To_v1beta1_WorkersClass(in *v1beta2.WorkersClass, out *WorkersClass, s conversion.Scope) error { + if in.MachineDeployments != nil { + in, out := &in.MachineDeployments, &out.MachineDeployments + *out = make([]MachineDeploymentClass, len(*in)) + for i := range *in { + if err := Convert_v1beta2_MachineDeploymentClass_To_v1beta1_MachineDeploymentClass(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.MachineDeployments = nil + } + if in.MachinePools != nil { + in, out := &in.MachinePools, &out.MachinePools + *out = make([]MachinePoolClass, len(*in)) + for i := range *in { + if err := Convert_v1beta2_MachinePoolClass_To_v1beta1_MachinePoolClass(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.MachinePools = nil + } + return nil +} + +// Convert_v1beta2_WorkersClass_To_v1beta1_WorkersClass is an autogenerated conversion function. +func Convert_v1beta2_WorkersClass_To_v1beta1_WorkersClass(in *v1beta2.WorkersClass, out *WorkersClass, s conversion.Scope) error { + return autoConvert_v1beta2_WorkersClass_To_v1beta1_WorkersClass(in, out, s) +} + +func autoConvert_v1beta1_WorkersStatus_To_v1beta2_WorkersStatus(in *WorkersStatus, out *v1beta2.WorkersStatus, s conversion.Scope) error { + out.DesiredReplicas = (*int32)(unsafe.Pointer(in.DesiredReplicas)) + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + out.UpToDateReplicas = (*int32)(unsafe.Pointer(in.UpToDateReplicas)) + out.ReadyReplicas = (*int32)(unsafe.Pointer(in.ReadyReplicas)) + out.AvailableReplicas = (*int32)(unsafe.Pointer(in.AvailableReplicas)) + return nil +} + +// Convert_v1beta1_WorkersStatus_To_v1beta2_WorkersStatus is an autogenerated conversion function. +func Convert_v1beta1_WorkersStatus_To_v1beta2_WorkersStatus(in *WorkersStatus, out *v1beta2.WorkersStatus, s conversion.Scope) error { + return autoConvert_v1beta1_WorkersStatus_To_v1beta2_WorkersStatus(in, out, s) +} + +func autoConvert_v1beta2_WorkersStatus_To_v1beta1_WorkersStatus(in *v1beta2.WorkersStatus, out *WorkersStatus, s conversion.Scope) error { + out.DesiredReplicas = (*int32)(unsafe.Pointer(in.DesiredReplicas)) + out.Replicas = (*int32)(unsafe.Pointer(in.Replicas)) + out.UpToDateReplicas = (*int32)(unsafe.Pointer(in.UpToDateReplicas)) + out.ReadyReplicas = (*int32)(unsafe.Pointer(in.ReadyReplicas)) + out.AvailableReplicas = (*int32)(unsafe.Pointer(in.AvailableReplicas)) + return nil +} + +// Convert_v1beta2_WorkersStatus_To_v1beta1_WorkersStatus is an autogenerated conversion function. +func Convert_v1beta2_WorkersStatus_To_v1beta1_WorkersStatus(in *v1beta2.WorkersStatus, out *WorkersStatus, s conversion.Scope) error { + return autoConvert_v1beta2_WorkersStatus_To_v1beta1_WorkersStatus(in, out, s) +} + +func autoConvert_v1beta1_WorkersTopology_To_v1beta2_WorkersTopology(in *WorkersTopology, out *v1beta2.WorkersTopology, s conversion.Scope) error { + if in.MachineDeployments != nil { + in, out := &in.MachineDeployments, &out.MachineDeployments + *out = make([]v1beta2.MachineDeploymentTopology, len(*in)) + for i := range *in { + if err := Convert_v1beta1_MachineDeploymentTopology_To_v1beta2_MachineDeploymentTopology(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.MachineDeployments = nil + } + if in.MachinePools != nil { + in, out := &in.MachinePools, &out.MachinePools + *out = make([]v1beta2.MachinePoolTopology, len(*in)) + for i := range *in { + if err := Convert_v1beta1_MachinePoolTopology_To_v1beta2_MachinePoolTopology(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.MachinePools = nil + } + return nil +} + +// Convert_v1beta1_WorkersTopology_To_v1beta2_WorkersTopology is an autogenerated conversion function. +func Convert_v1beta1_WorkersTopology_To_v1beta2_WorkersTopology(in *WorkersTopology, out *v1beta2.WorkersTopology, s conversion.Scope) error { + return autoConvert_v1beta1_WorkersTopology_To_v1beta2_WorkersTopology(in, out, s) +} + +func autoConvert_v1beta2_WorkersTopology_To_v1beta1_WorkersTopology(in *v1beta2.WorkersTopology, out *WorkersTopology, s conversion.Scope) error { + if in.MachineDeployments != nil { + in, out := &in.MachineDeployments, &out.MachineDeployments + *out = make([]MachineDeploymentTopology, len(*in)) + for i := range *in { + if err := Convert_v1beta2_MachineDeploymentTopology_To_v1beta1_MachineDeploymentTopology(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.MachineDeployments = nil + } + if in.MachinePools != nil { + in, out := &in.MachinePools, &out.MachinePools + *out = make([]MachinePoolTopology, len(*in)) + for i := range *in { + if err := Convert_v1beta2_MachinePoolTopology_To_v1beta1_MachinePoolTopology(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.MachinePools = nil + } + return nil +} + +// Convert_v1beta2_WorkersTopology_To_v1beta1_WorkersTopology is an autogenerated conversion function. +func Convert_v1beta2_WorkersTopology_To_v1beta1_WorkersTopology(in *v1beta2.WorkersTopology, out *WorkersTopology, s conversion.Scope) error { + return autoConvert_v1beta2_WorkersTopology_To_v1beta1_WorkersTopology(in, out, s) +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.deepcopy.go similarity index 94% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/zz_generated.deepcopy.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.deepcopy.go index ec25c1dfb000..a1b090669cb4 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.deepcopy.go @@ -1992,6 +1992,33 @@ func (in *MachineNamingStrategy) DeepCopy() *MachineNamingStrategy { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePool) DeepCopyInto(out *MachinePool) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePool. +func (in *MachinePool) DeepCopy() *MachinePool { + if in == nil { + return nil + } + out := new(MachinePool) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachinePool) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MachinePoolClass) DeepCopyInto(out *MachinePoolClass) { *out = *in @@ -2076,6 +2103,116 @@ func (in *MachinePoolClassTemplate) DeepCopy() *MachinePoolClassTemplate { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolList) DeepCopyInto(out *MachinePoolList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachinePool, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolList. +func (in *MachinePoolList) DeepCopy() *MachinePoolList { + if in == nil { + return nil + } + out := new(MachinePoolList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachinePoolList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolSpec) DeepCopyInto(out *MachinePoolSpec) { + *out = *in + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + in.Template.DeepCopyInto(&out.Template) + if in.MinReadySeconds != nil { + in, out := &in.MinReadySeconds, &out.MinReadySeconds + *out = new(int32) + **out = **in + } + if in.ProviderIDList != nil { + in, out := &in.ProviderIDList, &out.ProviderIDList + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.FailureDomains != nil { + in, out := &in.FailureDomains, &out.FailureDomains + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolSpec. +func (in *MachinePoolSpec) DeepCopy() *MachinePoolSpec { + if in == nil { + return nil + } + out := new(MachinePoolSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolStatus) DeepCopyInto(out *MachinePoolStatus) { + *out = *in + if in.NodeRefs != nil { + in, out := &in.NodeRefs, &out.NodeRefs + *out = make([]v1.ObjectReference, len(*in)) + copy(*out, *in) + } + if in.FailureReason != nil { + in, out := &in.FailureReason, &out.FailureReason + *out = new(errors.MachinePoolStatusFailure) + **out = **in + } + if in.FailureMessage != nil { + in, out := &in.FailureMessage, &out.FailureMessage + *out = new(string) + **out = **in + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.V1Beta2 != nil { + in, out := &in.V1Beta2, &out.V1Beta2 + *out = new(MachinePoolV1Beta2Status) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolStatus. +func (in *MachinePoolStatus) DeepCopy() *MachinePoolStatus { + if in == nil { + return nil + } + out := new(MachinePoolStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MachinePoolTopology) DeepCopyInto(out *MachinePoolTopology) { *out = *in @@ -2127,6 +2264,43 @@ func (in *MachinePoolTopology) DeepCopy() *MachinePoolTopology { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolV1Beta2Status) DeepCopyInto(out *MachinePoolV1Beta2Status) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]metav1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.ReadyReplicas != nil { + in, out := &in.ReadyReplicas, &out.ReadyReplicas + *out = new(int32) + **out = **in + } + if in.AvailableReplicas != nil { + in, out := &in.AvailableReplicas, &out.AvailableReplicas + *out = new(int32) + **out = **in + } + if in.UpToDateReplicas != nil { + in, out := &in.UpToDateReplicas, &out.UpToDateReplicas + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolV1Beta2Status. +func (in *MachinePoolV1Beta2Status) DeepCopy() *MachinePoolV1Beta2Status { + if in == nil { + return nil + } + out := new(MachinePoolV1Beta2Status) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MachinePoolVariables) DeepCopyInto(out *MachinePoolVariables) { *out = *in @@ -2417,7 +2591,7 @@ func (in *MachineStatus) DeepCopyInto(out *MachineStatus) { if in.NodeInfo != nil { in, out := &in.NodeInfo, &out.NodeInfo *out = new(v1.NodeSystemInfo) - **out = **in + (*in).DeepCopyInto(*out) } if in.LastUpdated != nil { in, out := &in.LastUpdated, &out.LastUpdated diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/zz_generated.openapi.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.openapi.go similarity index 79% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/zz_generated.openapi.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.openapi.go index a3f0529dc3ca..13a78b23719c 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/zz_generated.openapi.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta1/zz_generated.openapi.go @@ -28,104 +28,109 @@ import ( func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { return map[string]common.OpenAPIDefinition{ - "sigs.k8s.io/cluster-api/api/v1beta1.APIEndpoint": schema_sigsk8sio_cluster_api_api_v1beta1_APIEndpoint(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.Bootstrap": schema_sigsk8sio_cluster_api_api_v1beta1_Bootstrap(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.Cluster": schema_sigsk8sio_cluster_api_api_v1beta1_Cluster(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterAvailabilityGate": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterAvailabilityGate(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClass": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClass(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassList": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassList(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassPatch": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassPatch(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassSpec": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatus": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatusVariable": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatusVariable(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatusVariableDefinition": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatusVariableDefinition(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassV1Beta2Status": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassV1Beta2Status(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassVariable": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassVariable(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassVariableMetadata": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassVariableMetadata(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterControlPlaneStatus": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterControlPlaneStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterList": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterList(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterNetwork": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterNetwork(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterSpec": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterStatus": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterV1Beta2Status": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterV1Beta2Status(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable": schema_sigsk8sio_cluster_api_api_v1beta1_ClusterVariable(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.Condition": schema_sigsk8sio_cluster_api_api_v1beta1_Condition(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneClass": schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClass(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneClassNamingStrategy": schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClassNamingStrategy(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneTopology": schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneTopology(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneVariables": schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneVariables(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ExternalPatchDefinition": schema_sigsk8sio_cluster_api_api_v1beta1_ExternalPatchDefinition(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.FailureDomainSpec": schema_sigsk8sio_cluster_api_api_v1beta1_FailureDomainSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.InfrastructureNamingStrategy": schema_sigsk8sio_cluster_api_api_v1beta1_InfrastructureNamingStrategy(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.JSONPatch": schema_sigsk8sio_cluster_api_api_v1beta1_JSONPatch(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.JSONPatchValue": schema_sigsk8sio_cluster_api_api_v1beta1_JSONPatchValue(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps": schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate": schema_sigsk8sio_cluster_api_api_v1beta1_LocalObjectTemplate(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.Machine": schema_sigsk8sio_cluster_api_api_v1beta1_Machine(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineAddress": schema_sigsk8sio_cluster_api_api_v1beta1_MachineAddress(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeletionStatus": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeletionStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeployment": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeployment(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClass": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClass(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClassNamingStrategy": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClassNamingStrategy(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClassTemplate": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClassTemplate(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentList": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentList(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentSpec": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStatus": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStrategy": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentStrategy(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentTopology": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentTopology(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentV1Beta2Status": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentV1Beta2Status(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentVariables": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentVariables(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRule": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRule(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleDrainConfig": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleDrainConfig(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleList": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleList(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleMachineSelector": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleMachineSelector(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRulePodSelector": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRulePodSelector(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleSpec": schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheck": schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheck(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckClass": schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckClass(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckList": schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckList(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckSpec": schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckStatus": schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckTopology": schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckTopology(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckV1Beta2Status": schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckV1Beta2Status(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineList": schema_sigsk8sio_cluster_api_api_v1beta1_MachineList(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineNamingStrategy": schema_sigsk8sio_cluster_api_api_v1beta1_MachineNamingStrategy(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClass": schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClass(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClassNamingStrategy": schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClassNamingStrategy(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClassTemplate": schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClassTemplate(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolTopology": schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolTopology(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolVariables": schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolVariables(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate": schema_sigsk8sio_cluster_api_api_v1beta1_MachineReadinessGate(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineRollingUpdateDeployment": schema_sigsk8sio_cluster_api_api_v1beta1_MachineRollingUpdateDeployment(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineSet": schema_sigsk8sio_cluster_api_api_v1beta1_MachineSet(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineSetList": schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetList(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineSetSpec": schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineSetStatus": schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineSetV1Beta2Status": schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetV1Beta2Status(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineSpec": schema_sigsk8sio_cluster_api_api_v1beta1_MachineSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineStatus": schema_sigsk8sio_cluster_api_api_v1beta1_MachineStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineTemplateSpec": schema_sigsk8sio_cluster_api_api_v1beta1_MachineTemplateSpec(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.MachineV1Beta2Status": schema_sigsk8sio_cluster_api_api_v1beta1_MachineV1Beta2Status(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.NetworkRanges": schema_sigsk8sio_cluster_api_api_v1beta1_NetworkRanges(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta": schema_sigsk8sio_cluster_api_api_v1beta1_ObjectMeta(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.PatchDefinition": schema_sigsk8sio_cluster_api_api_v1beta1_PatchDefinition(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.PatchSelector": schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelector(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatch": schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatch(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatchMachineDeploymentClass": schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatchMachineDeploymentClass(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatchMachinePoolClass": schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatchMachinePoolClass(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.RemediationStrategy": schema_sigsk8sio_cluster_api_api_v1beta1_RemediationStrategy(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.Topology": schema_sigsk8sio_cluster_api_api_v1beta1_Topology(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.UnhealthyCondition": schema_sigsk8sio_cluster_api_api_v1beta1_UnhealthyCondition(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.ValidationRule": schema_sigsk8sio_cluster_api_api_v1beta1_ValidationRule(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.VariableSchema": schema_sigsk8sio_cluster_api_api_v1beta1_VariableSchema(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.VariableSchemaMetadata": schema_sigsk8sio_cluster_api_api_v1beta1_VariableSchemaMetadata(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.WorkersClass": schema_sigsk8sio_cluster_api_api_v1beta1_WorkersClass(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.WorkersStatus": schema_sigsk8sio_cluster_api_api_v1beta1_WorkersStatus(ref), - "sigs.k8s.io/cluster-api/api/v1beta1.WorkersTopology": schema_sigsk8sio_cluster_api_api_v1beta1_WorkersTopology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.APIEndpoint": schema_cluster_api_api_core_v1beta1_APIEndpoint(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.Bootstrap": schema_cluster_api_api_core_v1beta1_Bootstrap(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.Cluster": schema_cluster_api_api_core_v1beta1_Cluster(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterAvailabilityGate": schema_cluster_api_api_core_v1beta1_ClusterAvailabilityGate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClass": schema_cluster_api_api_core_v1beta1_ClusterClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassList": schema_cluster_api_api_core_v1beta1_ClusterClassList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassPatch": schema_cluster_api_api_core_v1beta1_ClusterClassPatch(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassSpec": schema_cluster_api_api_core_v1beta1_ClusterClassSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatus": schema_cluster_api_api_core_v1beta1_ClusterClassStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatusVariable": schema_cluster_api_api_core_v1beta1_ClusterClassStatusVariable(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatusVariableDefinition": schema_cluster_api_api_core_v1beta1_ClusterClassStatusVariableDefinition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassV1Beta2Status": schema_cluster_api_api_core_v1beta1_ClusterClassV1Beta2Status(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassVariable": schema_cluster_api_api_core_v1beta1_ClusterClassVariable(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassVariableMetadata": schema_cluster_api_api_core_v1beta1_ClusterClassVariableMetadata(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterControlPlaneStatus": schema_cluster_api_api_core_v1beta1_ClusterControlPlaneStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterList": schema_cluster_api_api_core_v1beta1_ClusterList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterNetwork": schema_cluster_api_api_core_v1beta1_ClusterNetwork(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterSpec": schema_cluster_api_api_core_v1beta1_ClusterSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterStatus": schema_cluster_api_api_core_v1beta1_ClusterStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterV1Beta2Status": schema_cluster_api_api_core_v1beta1_ClusterV1Beta2Status(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable": schema_cluster_api_api_core_v1beta1_ClusterVariable(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.Condition": schema_cluster_api_api_core_v1beta1_Condition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneClass": schema_cluster_api_api_core_v1beta1_ControlPlaneClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneClassNamingStrategy": schema_cluster_api_api_core_v1beta1_ControlPlaneClassNamingStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneTopology": schema_cluster_api_api_core_v1beta1_ControlPlaneTopology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneVariables": schema_cluster_api_api_core_v1beta1_ControlPlaneVariables(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ExternalPatchDefinition": schema_cluster_api_api_core_v1beta1_ExternalPatchDefinition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.FailureDomainSpec": schema_cluster_api_api_core_v1beta1_FailureDomainSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.InfrastructureNamingStrategy": schema_cluster_api_api_core_v1beta1_InfrastructureNamingStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.JSONPatch": schema_cluster_api_api_core_v1beta1_JSONPatch(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.JSONPatchValue": schema_cluster_api_api_core_v1beta1_JSONPatchValue(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps": schema_cluster_api_api_core_v1beta1_JSONSchemaProps(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate": schema_cluster_api_api_core_v1beta1_LocalObjectTemplate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.Machine": schema_cluster_api_api_core_v1beta1_Machine(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineAddress": schema_cluster_api_api_core_v1beta1_MachineAddress(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeletionStatus": schema_cluster_api_api_core_v1beta1_MachineDeletionStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeployment": schema_cluster_api_api_core_v1beta1_MachineDeployment(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClass": schema_cluster_api_api_core_v1beta1_MachineDeploymentClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClassNamingStrategy": schema_cluster_api_api_core_v1beta1_MachineDeploymentClassNamingStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClassTemplate": schema_cluster_api_api_core_v1beta1_MachineDeploymentClassTemplate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentList": schema_cluster_api_api_core_v1beta1_MachineDeploymentList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentSpec": schema_cluster_api_api_core_v1beta1_MachineDeploymentSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStatus": schema_cluster_api_api_core_v1beta1_MachineDeploymentStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStrategy": schema_cluster_api_api_core_v1beta1_MachineDeploymentStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentTopology": schema_cluster_api_api_core_v1beta1_MachineDeploymentTopology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentV1Beta2Status": schema_cluster_api_api_core_v1beta1_MachineDeploymentV1Beta2Status(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentVariables": schema_cluster_api_api_core_v1beta1_MachineDeploymentVariables(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRule": schema_cluster_api_api_core_v1beta1_MachineDrainRule(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleDrainConfig": schema_cluster_api_api_core_v1beta1_MachineDrainRuleDrainConfig(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleList": schema_cluster_api_api_core_v1beta1_MachineDrainRuleList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleMachineSelector": schema_cluster_api_api_core_v1beta1_MachineDrainRuleMachineSelector(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRulePodSelector": schema_cluster_api_api_core_v1beta1_MachineDrainRulePodSelector(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleSpec": schema_cluster_api_api_core_v1beta1_MachineDrainRuleSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheck": schema_cluster_api_api_core_v1beta1_MachineHealthCheck(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckClass": schema_cluster_api_api_core_v1beta1_MachineHealthCheckClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckList": schema_cluster_api_api_core_v1beta1_MachineHealthCheckList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckSpec": schema_cluster_api_api_core_v1beta1_MachineHealthCheckSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckStatus": schema_cluster_api_api_core_v1beta1_MachineHealthCheckStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckTopology": schema_cluster_api_api_core_v1beta1_MachineHealthCheckTopology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckV1Beta2Status": schema_cluster_api_api_core_v1beta1_MachineHealthCheckV1Beta2Status(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineList": schema_cluster_api_api_core_v1beta1_MachineList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineNamingStrategy": schema_cluster_api_api_core_v1beta1_MachineNamingStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePool": schema_cluster_api_api_core_v1beta1_MachinePool(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClass": schema_cluster_api_api_core_v1beta1_MachinePoolClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClassNamingStrategy": schema_cluster_api_api_core_v1beta1_MachinePoolClassNamingStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClassTemplate": schema_cluster_api_api_core_v1beta1_MachinePoolClassTemplate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolList": schema_cluster_api_api_core_v1beta1_MachinePoolList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolSpec": schema_cluster_api_api_core_v1beta1_MachinePoolSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolStatus": schema_cluster_api_api_core_v1beta1_MachinePoolStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolTopology": schema_cluster_api_api_core_v1beta1_MachinePoolTopology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolV1Beta2Status": schema_cluster_api_api_core_v1beta1_MachinePoolV1Beta2Status(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolVariables": schema_cluster_api_api_core_v1beta1_MachinePoolVariables(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate": schema_cluster_api_api_core_v1beta1_MachineReadinessGate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineRollingUpdateDeployment": schema_cluster_api_api_core_v1beta1_MachineRollingUpdateDeployment(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSet": schema_cluster_api_api_core_v1beta1_MachineSet(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetList": schema_cluster_api_api_core_v1beta1_MachineSetList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetSpec": schema_cluster_api_api_core_v1beta1_MachineSetSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetStatus": schema_cluster_api_api_core_v1beta1_MachineSetStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetV1Beta2Status": schema_cluster_api_api_core_v1beta1_MachineSetV1Beta2Status(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSpec": schema_cluster_api_api_core_v1beta1_MachineSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineStatus": schema_cluster_api_api_core_v1beta1_MachineStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineTemplateSpec": schema_cluster_api_api_core_v1beta1_MachineTemplateSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineV1Beta2Status": schema_cluster_api_api_core_v1beta1_MachineV1Beta2Status(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.NetworkRanges": schema_cluster_api_api_core_v1beta1_NetworkRanges(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta": schema_cluster_api_api_core_v1beta1_ObjectMeta(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchDefinition": schema_cluster_api_api_core_v1beta1_PatchDefinition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelector": schema_cluster_api_api_core_v1beta1_PatchSelector(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatch": schema_cluster_api_api_core_v1beta1_PatchSelectorMatch(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatchMachineDeploymentClass": schema_cluster_api_api_core_v1beta1_PatchSelectorMatchMachineDeploymentClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatchMachinePoolClass": schema_cluster_api_api_core_v1beta1_PatchSelectorMatchMachinePoolClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.RemediationStrategy": schema_cluster_api_api_core_v1beta1_RemediationStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.Topology": schema_cluster_api_api_core_v1beta1_Topology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.UnhealthyCondition": schema_cluster_api_api_core_v1beta1_UnhealthyCondition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.ValidationRule": schema_cluster_api_api_core_v1beta1_ValidationRule(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchema": schema_cluster_api_api_core_v1beta1_VariableSchema(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchemaMetadata": schema_cluster_api_api_core_v1beta1_VariableSchemaMetadata(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersClass": schema_cluster_api_api_core_v1beta1_WorkersClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersStatus": schema_cluster_api_api_core_v1beta1_WorkersStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersTopology": schema_cluster_api_api_core_v1beta1_WorkersTopology(ref), } } -func schema_sigsk8sio_cluster_api_api_v1beta1_APIEndpoint(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_APIEndpoint(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -155,7 +160,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_APIEndpoint(ref common.ReferenceCa } } -func schema_sigsk8sio_cluster_api_api_v1beta1_Bootstrap(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_Bootstrap(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -183,7 +188,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_Bootstrap(ref common.ReferenceCall } } -func schema_sigsk8sio_cluster_api_api_v1beta1_Cluster(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_Cluster(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -215,25 +220,25 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_Cluster(ref common.ReferenceCallba SchemaProps: spec.SchemaProps{ Description: "spec is the desired state of Cluster.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ Description: "status is the observed state of Cluster.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterStatus"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterSpec", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterStatus"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterSpec", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterStatus"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterAvailabilityGate(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterAvailabilityGate(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -262,7 +267,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterAvailabilityGate(ref common } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClass(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClass(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -294,25 +299,25 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClass(ref common.ReferenceC SchemaProps: spec.SchemaProps{ Description: "spec is the desired state of ClusterClass.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ Description: "status is the observed state of ClusterClass.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatus"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassSpec", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatus"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassSpec", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatus"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassList(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassList(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -348,7 +353,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassList(ref common.Refere Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClass"), }, }, }, @@ -359,11 +364,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassList(ref common.Refere }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClass"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClass"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassPatch(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassPatch(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -400,7 +405,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassPatch(ref common.Refer Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.PatchDefinition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.PatchDefinition"), }, }, }, @@ -409,7 +414,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassPatch(ref common.Refer "external": { SchemaProps: spec.SchemaProps{ Description: "external defines an external patch. Note: Exactly one of Definitions or External must be set.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ExternalPatchDefinition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ExternalPatchDefinition"), }, }, }, @@ -417,11 +422,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassPatch(ref common.Refer }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ExternalPatchDefinition", "sigs.k8s.io/cluster-api/api/v1beta1.PatchDefinition"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ExternalPatchDefinition", "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchDefinition"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -444,7 +449,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassSpec(ref common.Refere Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterAvailabilityGate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterAvailabilityGate"), }, }, }, @@ -454,27 +459,27 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassSpec(ref common.Refere SchemaProps: spec.SchemaProps{ Description: "infrastructure is a reference to a provider-specific template that holds the details for provisioning infrastructure specific cluster for the underlying provider. The underlying provider is responsible for the implementation of the template to an infrastructure cluster.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate"), }, }, "infrastructureNamingStrategy": { SchemaProps: spec.SchemaProps{ Description: "infrastructureNamingStrategy allows changing the naming pattern used when creating the infrastructure object.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.InfrastructureNamingStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.InfrastructureNamingStrategy"), }, }, "controlPlane": { SchemaProps: spec.SchemaProps{ Description: "controlPlane is a reference to a local struct that holds the details for provisioning the Control Plane for the Cluster.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneClass"), }, }, "workers": { SchemaProps: spec.SchemaProps{ Description: "workers describes the worker nodes for the cluster. It is a collection of node types which can be used to create the worker nodes of the cluster.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.WorkersClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersClass"), }, }, "variables": { @@ -485,7 +490,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassSpec(ref common.Refere Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassVariable"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassVariable"), }, }, }, @@ -499,7 +504,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassSpec(ref common.Refere Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassPatch"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassPatch"), }, }, }, @@ -509,11 +514,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassSpec(ref common.Refere }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterAvailabilityGate", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassPatch", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassVariable", "sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneClass", "sigs.k8s.io/cluster-api/api/v1beta1.InfrastructureNamingStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate", "sigs.k8s.io/cluster-api/api/v1beta1.WorkersClass"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterAvailabilityGate", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassPatch", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassVariable", "sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneClass", "sigs.k8s.io/cluster-api/api/core/v1beta1.InfrastructureNamingStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersClass"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -528,7 +533,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatus(ref common.Refe Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatusVariable"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatusVariable"), }, }, }, @@ -542,7 +547,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatus(ref common.Refe Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Condition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Condition"), }, }, }, @@ -558,18 +563,18 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatus(ref common.Refe "v1beta2": { SchemaProps: spec.SchemaProps{ Description: "v1beta2 groups all the fields that will be added or modified in ClusterClass's status with the V1Beta2 version.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassV1Beta2Status"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassV1Beta2Status"), }, }, }, }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatusVariable", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassV1Beta2Status", "sigs.k8s.io/cluster-api/api/v1beta1.Condition"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatusVariable", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassV1Beta2Status", "sigs.k8s.io/cluster-api/api/core/v1beta1.Condition"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatusVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassStatusVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -600,7 +605,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatusVariable(ref com Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatusVariableDefinition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatusVariableDefinition"), }, }, }, @@ -611,11 +616,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatusVariable(ref com }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassStatusVariableDefinition"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassStatusVariableDefinition"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatusVariableDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassStatusVariableDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -642,14 +647,14 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatusVariableDefiniti SchemaProps: spec.SchemaProps{ Description: "metadata is the metadata of a variable. It can be used to add additional data for higher level tools to a ClusterClassVariable.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassVariableMetadata"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassVariableMetadata"), }, }, "schema": { SchemaProps: spec.SchemaProps{ Description: "schema defines the schema of the variable.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.VariableSchema"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchema"), }, }, }, @@ -657,11 +662,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassStatusVariableDefiniti }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassVariableMetadata", "sigs.k8s.io/cluster-api/api/v1beta1.VariableSchema"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassVariableMetadata", "sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchema"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -698,7 +703,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassV1Beta2Status(ref comm } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -725,14 +730,14 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassVariable(ref common.Re SchemaProps: spec.SchemaProps{ Description: "metadata is the metadata of a variable. It can be used to add additional data for higher level tools to a ClusterClassVariable.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please use XMetadata in JSONSchemaProps instead.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassVariableMetadata"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassVariableMetadata"), }, }, "schema": { SchemaProps: spec.SchemaProps{ Description: "schema defines the schema of the variable.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.VariableSchema"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchema"), }, }, }, @@ -740,11 +745,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassVariable(ref common.Re }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterClassVariableMetadata", "sigs.k8s.io/cluster-api/api/v1beta1.VariableSchema"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterClassVariableMetadata", "sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchema"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassVariableMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterClassVariableMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -789,7 +794,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterClassVariableMetadata(ref c } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterControlPlaneStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterControlPlaneStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -837,7 +842,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterControlPlaneStatus(ref comm } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterList(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterList(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -873,7 +878,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterList(ref common.ReferenceCa Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Cluster"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Cluster"), }, }, }, @@ -884,11 +889,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterList(ref common.ReferenceCa }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/v1beta1.Cluster"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.Cluster"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterNetwork(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterNetwork(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -905,13 +910,13 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterNetwork(ref common.Referenc "services": { SchemaProps: spec.SchemaProps{ Description: "services is the network ranges from which service VIPs are allocated.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.NetworkRanges"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.NetworkRanges"), }, }, "pods": { SchemaProps: spec.SchemaProps{ Description: "pods is the network ranges from which Pod networks are allocated.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.NetworkRanges"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.NetworkRanges"), }, }, "serviceDomain": { @@ -925,11 +930,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterNetwork(ref common.Referenc }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.NetworkRanges"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.NetworkRanges"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -946,14 +951,14 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterSpec(ref common.ReferenceCa "clusterNetwork": { SchemaProps: spec.SchemaProps{ Description: "clusterNetwork represents the cluster network configuration.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterNetwork"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterNetwork"), }, }, "controlPlaneEndpoint": { SchemaProps: spec.SchemaProps{ Description: "controlPlaneEndpoint represents the endpoint used to communicate with the control plane.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.APIEndpoint"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.APIEndpoint"), }, }, "controlPlaneRef": { @@ -971,7 +976,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterSpec(ref common.ReferenceCa "topology": { SchemaProps: spec.SchemaProps{ Description: "topology encapsulates the topology for the cluster. NOTE: It is required to enable the ClusterTopology feature gate flag to activate managed topologies support; this feature is highly experimental, and parts of it might still be not implemented.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Topology"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Topology"), }, }, "availabilityGates": { @@ -990,7 +995,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterSpec(ref common.ReferenceCa Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterAvailabilityGate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterAvailabilityGate"), }, }, }, @@ -1000,11 +1005,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterSpec(ref common.ReferenceCa }, }, Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference", "sigs.k8s.io/cluster-api/api/v1beta1.APIEndpoint", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterAvailabilityGate", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterNetwork", "sigs.k8s.io/cluster-api/api/v1beta1.Topology"}, + "k8s.io/api/core/v1.ObjectReference", "sigs.k8s.io/cluster-api/api/core/v1beta1.APIEndpoint", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterAvailabilityGate", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterNetwork", "sigs.k8s.io/cluster-api/api/core/v1beta1.Topology"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1020,7 +1025,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterStatus(ref common.Reference Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.FailureDomainSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.FailureDomainSpec"), }, }, }, @@ -1028,14 +1033,14 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterStatus(ref common.Reference }, "failureReason": { SchemaProps: spec.SchemaProps{ - Description: "failureReason indicates that there is a fatal problem reconciling the state, and will be set to a token value suitable for programmatic interpretation.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Description: "failureReason indicates that there is a fatal problem reconciling the state, and will be set to a token value suitable for programmatic interpretation.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", Type: []string{"string"}, Format: "", }, }, "failureMessage": { SchemaProps: spec.SchemaProps{ - Description: "failureMessage indicates that there is a fatal problem reconciling the state, and will be set to a descriptive error message.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Description: "failureMessage indicates that there is a fatal problem reconciling the state, and will be set to a descriptive error message.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", Type: []string{"string"}, Format: "", }, @@ -1071,7 +1076,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterStatus(ref common.Reference Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Condition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Condition"), }, }, }, @@ -1087,18 +1092,18 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterStatus(ref common.Reference "v1beta2": { SchemaProps: spec.SchemaProps{ Description: "v1beta2 groups all the fields that will be added or modified in Cluster's status with the V1Beta2 version.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterV1Beta2Status"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterV1Beta2Status"), }, }, }, }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterV1Beta2Status", "sigs.k8s.io/cluster-api/api/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/v1beta1.FailureDomainSpec"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterV1Beta2Status", "sigs.k8s.io/cluster-api/api/core/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta1.FailureDomainSpec"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1130,24 +1135,24 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterV1Beta2Status(ref common.Re "controlPlane": { SchemaProps: spec.SchemaProps{ Description: "controlPlane groups all the observations about Cluster's ControlPlane current state.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterControlPlaneStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterControlPlaneStatus"), }, }, "workers": { SchemaProps: spec.SchemaProps{ Description: "workers groups all the observations about Cluster's Workers current state.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.WorkersStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersStatus"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterControlPlaneStatus", "sigs.k8s.io/cluster-api/api/v1beta1.WorkersStatus"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterControlPlaneStatus", "sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersStatus"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ClusterVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1184,7 +1189,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ClusterVariable(ref common.Referen } } -func schema_sigsk8sio_cluster_api_api_v1beta1_Condition(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_Condition(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1243,7 +1248,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_Condition(ref common.ReferenceCall } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClass(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ControlPlaneClass(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1254,7 +1259,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClass(ref common.Refer SchemaProps: spec.SchemaProps{ Description: "metadata is the metadata applied to the ControlPlane and the Machines of the ControlPlane if the ControlPlaneTemplate referenced is machine based. If not, it is applied only to the ControlPlane. At runtime this metadata is merged with the corresponding metadata from the topology.\n\nThis field is supported if and only if the control plane provider template referenced is Machine based.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"), }, }, "ref": { @@ -1266,19 +1271,19 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClass(ref common.Refer "machineInfrastructure": { SchemaProps: spec.SchemaProps{ Description: "machineInfrastructure defines the metadata and infrastructure information for control plane machines.\n\nThis field is supported if and only if the control plane provider template referenced above is Machine based and supports setting replicas.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate"), }, }, "machineHealthCheck": { SchemaProps: spec.SchemaProps{ Description: "machineHealthCheck defines a MachineHealthCheck for this ControlPlaneClass. This field is supported if and only if the ControlPlane provider template referenced above is Machine based and supports setting replicas.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckClass"), }, }, "namingStrategy": { SchemaProps: spec.SchemaProps{ Description: "namingStrategy allows changing the naming pattern used when creating the control plane provider object.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneClassNamingStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneClassNamingStrategy"), }, }, "nodeDrainTimeout": { @@ -1315,7 +1320,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClass(ref common.Refer Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate"), }, }, }, @@ -1326,11 +1331,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClass(ref common.Refer }, }, Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneClassNamingStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate", "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckClass", "sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"}, + "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneClassNamingStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckClass", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClassNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ControlPlaneClassNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1350,7 +1355,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneClassNamingStrategy(re } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ControlPlaneTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1361,7 +1366,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneTopology(ref common.Re SchemaProps: spec.SchemaProps{ Description: "metadata is the metadata applied to the ControlPlane and the Machines of the ControlPlane if the ControlPlaneTemplate referenced by the ClusterClass is machine based. If not, it is applied only to the ControlPlane. At runtime this metadata is merged with the corresponding metadata from the ClusterClass.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"), }, }, "replicas": { @@ -1374,7 +1379,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneTopology(ref common.Re "machineHealthCheck": { SchemaProps: spec.SchemaProps{ Description: "machineHealthCheck allows to enable, disable and override the MachineHealthCheck configuration in the ClusterClass for this control plane.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckTopology"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckTopology"), }, }, "nodeDrainTimeout": { @@ -1411,7 +1416,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneTopology(ref common.Re Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate"), }, }, }, @@ -1420,18 +1425,18 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneTopology(ref common.Re "variables": { SchemaProps: spec.SchemaProps{ Description: "variables can be used to customize the ControlPlane through patches.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneVariables"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneVariables"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneVariables", "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckTopology", "sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneVariables", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckTopology", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ControlPlaneVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1454,7 +1459,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneVariables(ref common.R Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable"), }, }, }, @@ -1464,11 +1469,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ControlPlaneVariables(ref common.R }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ExternalPatchDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ExternalPatchDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1518,7 +1523,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ExternalPatchDefinition(ref common } } -func schema_sigsk8sio_cluster_api_api_v1beta1_FailureDomainSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_FailureDomainSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1554,7 +1559,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_FailureDomainSpec(ref common.Refer } } -func schema_sigsk8sio_cluster_api_api_v1beta1_InfrastructureNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_InfrastructureNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1574,7 +1579,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_InfrastructureNamingStrategy(ref c } } -func schema_sigsk8sio_cluster_api_api_v1beta1_JSONPatch(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_JSONPatch(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1606,7 +1611,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONPatch(ref common.ReferenceCall "valueFrom": { SchemaProps: spec.SchemaProps{ Description: "valueFrom defines the value of the patch. Note: Either Value or ValueFrom is required for add and replace operations. Only one of them is allowed to be set at the same time.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONPatchValue"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONPatchValue"), }, }, }, @@ -1614,11 +1619,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONPatch(ref common.ReferenceCall }, }, Dependencies: []string{ - "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON", "sigs.k8s.io/cluster-api/api/v1beta1.JSONPatchValue"}, + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON", "sigs.k8s.io/cluster-api/api/core/v1beta1.JSONPatchValue"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_JSONPatchValue(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_JSONPatchValue(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1645,7 +1650,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONPatchValue(ref common.Referenc } } -func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_JSONSchemaProps(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1681,7 +1686,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"), }, }, }, @@ -1690,7 +1695,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen "additionalProperties": { SchemaProps: spec.SchemaProps{ Description: "additionalProperties specifies the schema of values in a map (keys are always strings). NOTE: Can only be set if type is object. NOTE: AdditionalProperties is mutually exclusive with Properties. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"), }, }, "maxProperties": { @@ -1725,7 +1730,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen "items": { SchemaProps: spec.SchemaProps{ Description: "items specifies fields of an array. NOTE: Can only be set if type is array. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"), }, }, "maxItems": { @@ -1847,7 +1852,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ValidationRule"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ValidationRule"), }, }, }, @@ -1856,7 +1861,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen "x-metadata": { SchemaProps: spec.SchemaProps{ Description: "x-metadata is the metadata of a variable or a nested field within a variable. It can be used to add additional data for higher level tools.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.VariableSchemaMetadata"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchemaMetadata"), }, }, "x-kubernetes-int-or-string": { @@ -1874,7 +1879,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"), }, }, }, @@ -1888,7 +1893,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"), }, }, }, @@ -1902,7 +1907,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"), }, }, }, @@ -1911,18 +1916,18 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_JSONSchemaProps(ref common.Referen "not": { SchemaProps: spec.SchemaProps{ Description: "not specifies that the variable must not validate against the subschema. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON", "sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps", "sigs.k8s.io/cluster-api/api/v1beta1.ValidationRule", "sigs.k8s.io/cluster-api/api/v1beta1.VariableSchemaMetadata"}, + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON", "sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps", "sigs.k8s.io/cluster-api/api/core/v1beta1.ValidationRule", "sigs.k8s.io/cluster-api/api/core/v1beta1.VariableSchemaMetadata"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_LocalObjectTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_LocalObjectTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1944,7 +1949,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_LocalObjectTemplate(ref common.Ref } } -func schema_sigsk8sio_cluster_api_api_v1beta1_Machine(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_Machine(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -1976,25 +1981,25 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_Machine(ref common.ReferenceCallba SchemaProps: spec.SchemaProps{ Description: "spec is the desired state of Machine.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ Description: "status is the observed state of Machine.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineStatus"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineSpec", "sigs.k8s.io/cluster-api/api/v1beta1.MachineStatus"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSpec", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineStatus"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineAddress(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineAddress(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2024,7 +2029,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineAddress(ref common.Referenc } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeletionStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeletionStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2051,7 +2056,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeletionStatus(ref common.R } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeployment(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeployment(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2083,25 +2088,25 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeployment(ref common.Refer SchemaProps: spec.SchemaProps{ Description: "spec is the desired state of MachineDeployment.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ Description: "status is the observed state of MachineDeployment.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStatus"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentSpec", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStatus"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentSpec", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStatus"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClass(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentClass(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2120,13 +2125,13 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClass(ref common. SchemaProps: spec.SchemaProps{ Description: "template is a local struct containing a collection of templates for creation of MachineDeployment objects representing a set of worker nodes.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClassTemplate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClassTemplate"), }, }, "machineHealthCheck": { SchemaProps: spec.SchemaProps{ Description: "machineHealthCheck defines a MachineHealthCheck for this MachineDeploymentClass.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckClass"), }, }, "failureDomain": { @@ -2139,7 +2144,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClass(ref common. "namingStrategy": { SchemaProps: spec.SchemaProps{ Description: "namingStrategy allows changing the naming pattern used when creating the MachineDeployment.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClassNamingStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClassNamingStrategy"), }, }, "nodeDrainTimeout": { @@ -2183,7 +2188,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClass(ref common. Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate"), }, }, }, @@ -2192,7 +2197,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClass(ref common. "strategy": { SchemaProps: spec.SchemaProps{ Description: "strategy is the deployment strategy to use to replace existing machines with new ones. NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStrategy"), }, }, }, @@ -2200,11 +2205,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClass(ref common. }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClassNamingStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClassTemplate", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckClass", "sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClassNamingStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClassTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckClass", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClassNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentClassNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2224,7 +2229,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClassNamingStrate } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClassTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentClassTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2235,21 +2240,21 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClassTemplate(ref SchemaProps: spec.SchemaProps{ Description: "metadata is the metadata applied to the MachineDeployment and the machines of the MachineDeployment. At runtime this metadata is merged with the corresponding metadata from the topology.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"), }, }, "bootstrap": { SchemaProps: spec.SchemaProps{ Description: "bootstrap contains the bootstrap template reference to be used for the creation of worker Machines.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate"), }, }, "infrastructure": { SchemaProps: spec.SchemaProps{ Description: "infrastructure contains the infrastructure template reference to be used for the creation of worker Machines.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate"), }, }, }, @@ -2257,11 +2262,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentClassTemplate(ref }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate", "sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentList(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentList(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2297,7 +2302,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentList(ref common.R Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeployment"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeployment"), }, }, }, @@ -2308,11 +2313,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentList(ref common.R }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeployment"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeployment"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2351,19 +2356,19 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentSpec(ref common.R SchemaProps: spec.SchemaProps{ Description: "template describes the machines that will be created.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineTemplateSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineTemplateSpec"), }, }, "strategy": { SchemaProps: spec.SchemaProps{ Description: "strategy is the deployment strategy to use to replace existing machines with new ones.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStrategy"), }, }, "machineNamingStrategy": { SchemaProps: spec.SchemaProps{ Description: "machineNamingStrategy allows changing the naming pattern used when creating Machines. Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineNamingStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineNamingStrategy"), }, }, "minReadySeconds": { @@ -2399,11 +2404,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentSpec(ref common.R }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "k8s.io/apimachinery/pkg/apis/meta/v1.Time", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.MachineNamingStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.MachineTemplateSpec"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "k8s.io/apimachinery/pkg/apis/meta/v1.Time", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineNamingStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineTemplateSpec"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2458,7 +2463,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentStatus(ref common }, "unavailableReplicas": { SchemaProps: spec.SchemaProps{ - Description: "unavailableReplicas is the total number of unavailable machines targeted by this deployment. This is the total number of machines that are still required for the deployment to have 100% available capacity. They may either be machines that are running but not yet available or machines that still have not been created.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Description: "unavailableReplicas is the total number of unavailable machines targeted by this deployment. This is the total number of machines that are still required for the deployment to have 100% available capacity. They may either be machines that are running but not yet available or machines that still have not been created.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", Default: 0, Type: []string{"integer"}, Format: "int32", @@ -2479,7 +2484,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentStatus(ref common Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Condition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Condition"), }, }, }, @@ -2488,18 +2493,18 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentStatus(ref common "v1beta2": { SchemaProps: spec.SchemaProps{ Description: "v1beta2 groups all the fields that will be added or modified in MachineDeployment's status with the V1Beta2 version.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentV1Beta2Status"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentV1Beta2Status"), }, }, }, }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentV1Beta2Status"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentV1Beta2Status"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2516,24 +2521,24 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentStrategy(ref comm "rollingUpdate": { SchemaProps: spec.SchemaProps{ Description: "rollingUpdate is the rolling update config params. Present only if MachineDeploymentStrategyType = RollingUpdate.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineRollingUpdateDeployment"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineRollingUpdateDeployment"), }, }, "remediation": { SchemaProps: spec.SchemaProps{ Description: "remediation controls the strategy of remediating unhealthy machines and how remediating operations should occur during the lifecycle of the dependant MachineSets.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.RemediationStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.RemediationStrategy"), }, }, }, }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.MachineRollingUpdateDeployment", "sigs.k8s.io/cluster-api/api/v1beta1.RemediationStrategy"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineRollingUpdateDeployment", "sigs.k8s.io/cluster-api/api/core/v1beta1.RemediationStrategy"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2544,7 +2549,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentTopology(ref comm SchemaProps: spec.SchemaProps{ Description: "metadata is the metadata applied to the MachineDeployment and the machines of the MachineDeployment. At runtime this metadata is merged with the corresponding metadata from the ClusterClass.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"), }, }, "class": { @@ -2580,7 +2585,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentTopology(ref comm "machineHealthCheck": { SchemaProps: spec.SchemaProps{ Description: "machineHealthCheck allows to enable, disable and override the MachineHealthCheck configuration in the ClusterClass for this MachineDeployment.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckTopology"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckTopology"), }, }, "nodeDrainTimeout": { @@ -2624,7 +2629,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentTopology(ref comm Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate"), }, }, }, @@ -2633,13 +2638,13 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentTopology(ref comm "strategy": { SchemaProps: spec.SchemaProps{ Description: "strategy is the deployment strategy to use to replace existing machines with new ones.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStrategy"), }, }, "variables": { SchemaProps: spec.SchemaProps{ Description: "variables can be used to customize the MachineDeployment through patches.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentVariables"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentVariables"), }, }, }, @@ -2647,11 +2652,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentTopology(ref comm }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentVariables", "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckTopology", "sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentVariables", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckTopology", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2709,7 +2714,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentV1Beta2Status(ref } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDeploymentVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2732,7 +2737,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentVariables(ref com Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable"), }, }, }, @@ -2742,11 +2747,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDeploymentVariables(ref com }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRule(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDrainRule(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2778,7 +2783,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRule(ref common.Refere SchemaProps: spec.SchemaProps{ Description: "spec defines the spec of a MachineDrainRule.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleSpec"), }, }, }, @@ -2786,11 +2791,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRule(ref common.Refere }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleSpec"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleSpec"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleDrainConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDrainRuleDrainConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2819,7 +2824,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleDrainConfig(ref co } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleList(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDrainRuleList(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2855,7 +2860,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleList(ref common.Re Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRule"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRule"), }, }, }, @@ -2866,11 +2871,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleList(ref common.Re }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRule"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRule"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleMachineSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDrainRuleMachineSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2897,7 +2902,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleMachineSelector(re } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRulePodSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDrainRulePodSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2924,7 +2929,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRulePodSelector(ref co } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineDrainRuleSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -2935,7 +2940,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleSpec(ref common.Re SchemaProps: spec.SchemaProps{ Description: "drain configures if and how Pods are drained.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleDrainConfig"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleDrainConfig"), }, }, "machines": { @@ -2951,7 +2956,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleSpec(ref common.Re Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleMachineSelector"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleMachineSelector"), }, }, }, @@ -2970,7 +2975,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleSpec(ref common.Re Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRulePodSelector"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRulePodSelector"), }, }, }, @@ -2981,11 +2986,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineDrainRuleSpec(ref common.Re }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleDrainConfig", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRuleMachineSelector", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDrainRulePodSelector"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleDrainConfig", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRuleMachineSelector", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDrainRulePodSelector"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheck(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineHealthCheck(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3017,25 +3022,25 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheck(ref common.Refe SchemaProps: spec.SchemaProps{ Description: "spec is the specification of machine health check policy", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ Description: "status is the most recently observed status of MachineHealthCheck resource", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckStatus"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckSpec", "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckStatus"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckSpec", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckStatus"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckClass(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineHealthCheckClass(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3050,7 +3055,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckClass(ref common Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.UnhealthyCondition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.UnhealthyCondition"), }, }, }, @@ -3085,11 +3090,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckClass(ref common }, }, Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "k8s.io/apimachinery/pkg/util/intstr.IntOrString", "sigs.k8s.io/cluster-api/api/v1beta1.UnhealthyCondition"}, + "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "k8s.io/apimachinery/pkg/util/intstr.IntOrString", "sigs.k8s.io/cluster-api/api/core/v1beta1.UnhealthyCondition"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckList(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineHealthCheckList(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3125,7 +3130,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckList(ref common. Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheck"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheck"), }, }, }, @@ -3136,11 +3141,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckList(ref common. }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheck"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheck"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineHealthCheckSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3170,7 +3175,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckSpec(ref common. Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.UnhealthyCondition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.UnhealthyCondition"), }, }, }, @@ -3206,11 +3211,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckSpec(ref common. }, }, Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "k8s.io/apimachinery/pkg/util/intstr.IntOrString", "sigs.k8s.io/cluster-api/api/v1beta1.UnhealthyCondition"}, + "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "k8s.io/apimachinery/pkg/util/intstr.IntOrString", "sigs.k8s.io/cluster-api/api/core/v1beta1.UnhealthyCondition"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineHealthCheckStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3271,7 +3276,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckStatus(ref commo Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Condition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Condition"), }, }, }, @@ -3280,18 +3285,18 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckStatus(ref commo "v1beta2": { SchemaProps: spec.SchemaProps{ Description: "v1beta2 groups all the fields that will be added or modified in MachineHealthCheck's status with the V1Beta2 version.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckV1Beta2Status"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckV1Beta2Status"), }, }, }, }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/v1beta1.MachineHealthCheckV1Beta2Status"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineHealthCheckV1Beta2Status"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineHealthCheckTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3313,7 +3318,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckTopology(ref com Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.UnhealthyCondition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.UnhealthyCondition"), }, }, }, @@ -3348,11 +3353,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckTopology(ref com }, }, Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "k8s.io/apimachinery/pkg/util/intstr.IntOrString", "sigs.k8s.io/cluster-api/api/v1beta1.UnhealthyCondition"}, + "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "k8s.io/apimachinery/pkg/util/intstr.IntOrString", "sigs.k8s.io/cluster-api/api/core/v1beta1.UnhealthyCondition"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineHealthCheckV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3389,7 +3394,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineHealthCheckV1Beta2Status(re } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineList(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineList(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3425,7 +3430,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineList(ref common.ReferenceCa Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Machine"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Machine"), }, }, }, @@ -3436,11 +3441,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineList(ref common.ReferenceCa }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/v1beta1.Machine"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.Machine"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3460,7 +3465,57 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineNamingStrategy(ref common.R } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClass(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachinePool(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePool is the Schema for the machinepools API.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the desired state of MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status is the observed state of MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolSpec", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta1_MachinePoolClass(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3479,7 +3534,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClass(ref common.Refere SchemaProps: spec.SchemaProps{ Description: "template is a local struct containing a collection of templates for creation of MachinePools objects representing a pool of worker nodes.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClassTemplate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClassTemplate"), }, }, "failureDomains": { @@ -3500,7 +3555,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClass(ref common.Refere "namingStrategy": { SchemaProps: spec.SchemaProps{ Description: "namingStrategy allows changing the naming pattern used when creating the MachinePool.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClassNamingStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClassNamingStrategy"), }, }, "nodeDrainTimeout": { @@ -3533,11 +3588,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClass(ref common.Refere }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClassNamingStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClassTemplate"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClassNamingStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClassTemplate"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClassNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachinePoolClassNamingStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3557,7 +3612,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClassNamingStrategy(ref } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClassTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachinePoolClassTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3568,21 +3623,21 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClassTemplate(ref commo SchemaProps: spec.SchemaProps{ Description: "metadata is the metadata applied to the MachinePool. At runtime this metadata is merged with the corresponding metadata from the topology.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"), }, }, "bootstrap": { SchemaProps: spec.SchemaProps{ Description: "bootstrap contains the bootstrap template reference to be used for the creation of the Machines in the MachinePool.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate"), }, }, "infrastructure": { SchemaProps: spec.SchemaProps{ Description: "infrastructure contains the infrastructure template reference to be used for the creation of the MachinePool.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate"), }, }, }, @@ -3590,11 +3645,259 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolClassTemplate(ref commo }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.LocalObjectTemplate", "sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.LocalObjectTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachinePoolList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolList contains a list of MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items is the list of MachinePools.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePool"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePool"}, + } +} + +func schema_cluster_api_api_core_v1beta1_MachinePoolSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolSpec defines the desired state of MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "clusterName": { + SchemaProps: spec.SchemaProps{ + Description: "clusterName is the name of the Cluster this object belongs to.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the number of desired machines. Defaults to 1. This is a pointer to distinguish between explicit zero and not specified.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template describes the machines that will be created.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineTemplateSpec"), + }, + }, + "minReadySeconds": { + SchemaProps: spec.SchemaProps{ + Description: "minReadySeconds is the minimum number of seconds for which a newly created machine instances should be ready. Defaults to 0 (machine instance will be considered available as soon as it is ready)", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "providerIDList": { + SchemaProps: spec.SchemaProps{ + Description: "providerIDList are the identification IDs of machine instances provided by the provider. This field must match the provider IDs as seen on the node objects corresponding to a machine pool's machine instances.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "failureDomains": { + SchemaProps: spec.SchemaProps{ + Description: "failureDomains is the list of failure domains this MachinePool should be attached to.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + Required: []string{"clusterName", "template"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineTemplateSpec"}, + } +} + +func schema_cluster_api_api_core_v1beta1_MachinePoolStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolStatus defines the observed state of MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeRefs": { + SchemaProps: spec.SchemaProps{ + Description: "nodeRefs will point to the corresponding Nodes if it they exist.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/api/core/v1.ObjectReference"), + }, + }, + }, + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the most recently observed number of replicas.", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the number of ready replicas for this MachinePool. A machine is considered ready when the node has been created and is \"Ready\".", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the number of available replicas (ready for at least minReadySeconds) for this MachinePool.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "unavailableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "unavailableReplicas is the total number of unavailable machine instances targeted by this machine pool. This is the total number of machine instances that are still required for the machine pool to have 100% available capacity. They may either be machine instances that are running but not yet available or machine instances that still have not been created.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "failureReason": { + SchemaProps: spec.SchemaProps{ + Description: "failureReason indicates that there is a problem reconciling the state, and will be set to a token value suitable for programmatic interpretation.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + "failureMessage": { + SchemaProps: spec.SchemaProps{ + Description: "failureMessage indicates that there is a problem reconciling the state, and will be set to a descriptive error message.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + "phase": { + SchemaProps: spec.SchemaProps{ + Description: "phase represents the current phase of cluster actuation.", + Type: []string{"string"}, + Format: "", + }, + }, + "bootstrapReady": { + SchemaProps: spec.SchemaProps{ + Description: "bootstrapReady is the state of the bootstrap provider.", + Default: false, + Type: []string{"boolean"}, + Format: "", + }, + }, + "infrastructureReady": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructureReady is the state of the infrastructure provider.", + Default: false, + Type: []string{"boolean"}, + Format: "", + }, + }, + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "observedGeneration is the latest generation observed by the controller.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "conditions": { + SchemaProps: spec.SchemaProps{ + Description: "conditions define the current service state of the MachinePool.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Condition"), + }, + }, + }, + }, + }, + "v1beta2": { + SchemaProps: spec.SchemaProps{ + Description: "v1beta2 groups all the fields that will be added or modified in MachinePool's status with the V1Beta2 version.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolV1Beta2Status"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/api/core/v1.ObjectReference", "sigs.k8s.io/cluster-api/api/core/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolV1Beta2Status"}, + } +} + +func schema_cluster_api_api_core_v1beta1_MachinePoolTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3605,7 +3908,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolTopology(ref common.Ref SchemaProps: spec.SchemaProps{ Description: "metadata is the metadata applied to the MachinePool. At runtime this metadata is merged with the corresponding metadata from the ClusterClass.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"), }, }, "class": { @@ -3674,7 +3977,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolTopology(ref common.Ref "variables": { SchemaProps: spec.SchemaProps{ Description: "variables can be used to customize the MachinePool through patches.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolVariables"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolVariables"), }, }, }, @@ -3682,11 +3985,69 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolTopology(ref common.Ref }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolVariables", "sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolVariables", "sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"}, + } +} + +func schema_cluster_api_api_core_v1beta1_MachinePoolV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolV1Beta2Status groups all the fields that will be added or modified in MachinePoolStatus with the V1Beta2 version. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observations of a MachinePool's current state. Known condition types are Available, BootstrapConfigReady, InfrastructureReady, MachinesReady, MachinesUpToDate, ScalingUp, ScalingDown, Remediating, Deleting, Paused.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the number of ready replicas for this MachinePool. A machine is considered ready when Machine's Ready condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the number of available replicas for this MachinePool. A machine is considered available when Machine's Available condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "upToDateReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "upToDateReplicas is the number of up-to-date replicas targeted by this MachinePool. A machine is considered up-to-date when Machine's UpToDate condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Condition"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachinePoolVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3709,7 +4070,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolVariables(ref common.Re Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable"), }, }, }, @@ -3719,11 +4080,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachinePoolVariables(ref common.Re }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineReadinessGate(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineReadinessGate(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3752,7 +4113,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineReadinessGate(ref common.Re } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineRollingUpdateDeployment(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineRollingUpdateDeployment(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3786,7 +4147,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineRollingUpdateDeployment(ref } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSet(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineSet(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3818,25 +4179,25 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSet(ref common.ReferenceCal SchemaProps: spec.SchemaProps{ Description: "spec is the desired state of MachineSet.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineSetSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetSpec"), }, }, "status": { SchemaProps: spec.SchemaProps{ Description: "status is the observed state of MachineSet.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineSetStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetStatus"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineSetSpec", "sigs.k8s.io/cluster-api/api/v1beta1.MachineSetStatus"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetSpec", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetStatus"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetList(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineSetList(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3872,7 +4233,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetList(ref common.Referenc Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineSet"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSet"), }, }, }, @@ -3883,11 +4244,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetList(ref common.Referenc }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/v1beta1.MachineSet"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSet"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineSetSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3934,13 +4295,13 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetSpec(ref common.Referenc SchemaProps: spec.SchemaProps{ Description: "template is the object that describes the machine that will be created if insufficient replicas are detected. Object references to custom resources are treated as templates.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineTemplateSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineTemplateSpec"), }, }, "machineNamingStrategy": { SchemaProps: spec.SchemaProps{ Description: "machineNamingStrategy allows changing the naming pattern used when creating Machines. Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineNamingStrategy"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineNamingStrategy"), }, }, }, @@ -3948,11 +4309,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetSpec(ref common.Referenc }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "sigs.k8s.io/cluster-api/api/v1beta1.MachineNamingStrategy", "sigs.k8s.io/cluster-api/api/v1beta1.MachineTemplateSpec"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineNamingStrategy", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineTemplateSpec"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineSetStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -3976,7 +4337,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetStatus(ref common.Refere }, "fullyLabeledReplicas": { SchemaProps: spec.SchemaProps{ - Description: "fullyLabeledReplicas is the number of replicas that have labels matching the labels of the machine template of the MachineSet.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Description: "fullyLabeledReplicas is the number of replicas that have labels matching the labels of the machine template of the MachineSet.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", Default: 0, Type: []string{"integer"}, Format: "int32", @@ -4007,14 +4368,14 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetStatus(ref common.Refere }, "failureReason": { SchemaProps: spec.SchemaProps{ - Description: "failureReason will be set in the event that there is a terminal problem reconciling the Machine and will contain a succinct value suitable for machine interpretation.\n\nIn the event that there is a terminal problem reconciling the replicas, both FailureReason and FailureMessage will be set. FailureReason will be populated with a succinct value suitable for machine interpretation, while FailureMessage will contain a more verbose string suitable for logging and human consumption.\n\nThese fields should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the MachineTemplate's spec or the configuration of the machine controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the machine controller, or the responsible machine controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the MachineSet object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Description: "failureReason will be set in the event that there is a terminal problem reconciling the Machine and will contain a succinct value suitable for machine interpretation.\n\nIn the event that there is a terminal problem reconciling the replicas, both FailureReason and FailureMessage will be set. FailureReason will be populated with a succinct value suitable for machine interpretation, while FailureMessage will contain a more verbose string suitable for logging and human consumption.\n\nThese fields should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the MachineTemplate's spec or the configuration of the machine controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the machine controller, or the responsible machine controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the MachineSet object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", Type: []string{"string"}, Format: "", }, }, "failureMessage": { SchemaProps: spec.SchemaProps{ - Description: "failureMessage will be set in the event that there is a terminal problem reconciling the Machine and will contain a more verbose string suitable for logging and human consumption.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Description: "failureMessage will be set in the event that there is a terminal problem reconciling the Machine and will contain a more verbose string suitable for logging and human consumption.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", Type: []string{"string"}, Format: "", }, @@ -4027,7 +4388,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetStatus(ref common.Refere Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Condition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Condition"), }, }, }, @@ -4036,18 +4397,18 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetStatus(ref common.Refere "v1beta2": { SchemaProps: spec.SchemaProps{ Description: "v1beta2 groups all the fields that will be added or modified in MachineSet's status with the V1Beta2 version.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineSetV1Beta2Status"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetV1Beta2Status"), }, }, }, }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/v1beta1.MachineSetV1Beta2Status"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSetV1Beta2Status"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineSetV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4105,7 +4466,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSetV1Beta2Status(ref common } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4124,7 +4485,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSpec(ref common.ReferenceCa SchemaProps: spec.SchemaProps{ Description: "bootstrap is a reference to a local struct which encapsulates fields to configure the Machine’s bootstrapping mechanism.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Bootstrap"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Bootstrap"), }, }, "infrastructureRef": { @@ -4171,7 +4532,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSpec(ref common.ReferenceCa Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate"), }, }, }, @@ -4200,11 +4561,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineSpec(ref common.ReferenceCa }, }, Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/v1beta1.Bootstrap", "sigs.k8s.io/cluster-api/api/v1beta1.MachineReadinessGate"}, + "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "sigs.k8s.io/cluster-api/api/core/v1beta1.Bootstrap", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineReadinessGate"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4231,14 +4592,14 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineStatus(ref common.Reference }, "failureReason": { SchemaProps: spec.SchemaProps{ - Description: "failureReason will be set in the event that there is a terminal problem reconciling the Machine and will contain a succinct value suitable for machine interpretation.\n\nThis field should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the Machine's spec or the configuration of the controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the controller, or the responsible controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the Machine object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Description: "failureReason will be set in the event that there is a terminal problem reconciling the Machine and will contain a succinct value suitable for machine interpretation.\n\nThis field should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the Machine's spec or the configuration of the controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the controller, or the responsible controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the Machine object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", Type: []string{"string"}, Format: "", }, }, "failureMessage": { SchemaProps: spec.SchemaProps{ - Description: "failureMessage will be set in the event that there is a terminal problem reconciling the Machine and will contain a more verbose string suitable for logging and human consumption.\n\nThis field should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the Machine's spec or the configuration of the controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the controller, or the responsible controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the Machine object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed in the next apiVersion. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Description: "failureMessage will be set in the event that there is a terminal problem reconciling the Machine and will contain a more verbose string suitable for logging and human consumption.\n\nThis field should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the Machine's spec or the configuration of the controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the controller, or the responsible controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the Machine object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", Type: []string{"string"}, Format: "", }, @@ -4251,7 +4612,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineStatus(ref common.Reference Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineAddress"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineAddress"), }, }, }, @@ -4301,7 +4662,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineStatus(ref common.Reference Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.Condition"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.Condition"), }, }, }, @@ -4310,24 +4671,24 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineStatus(ref common.Reference "deletion": { SchemaProps: spec.SchemaProps{ Description: "deletion contains information relating to removal of the Machine. Only present when the Machine has a deletionTimestamp and drain or wait for volume detach started.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeletionStatus"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeletionStatus"), }, }, "v1beta2": { SchemaProps: spec.SchemaProps{ Description: "v1beta2 groups all the fields that will be added or modified in Machine's status with the V1Beta2 version.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineV1Beta2Status"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineV1Beta2Status"), }, }, }, }, }, Dependencies: []string{ - "k8s.io/api/core/v1.NodeSystemInfo", "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Time", "sigs.k8s.io/cluster-api/api/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/v1beta1.MachineAddress", "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeletionStatus", "sigs.k8s.io/cluster-api/api/v1beta1.MachineV1Beta2Status"}, + "k8s.io/api/core/v1.NodeSystemInfo", "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Time", "sigs.k8s.io/cluster-api/api/core/v1beta1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineAddress", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeletionStatus", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineV1Beta2Status"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineTemplateSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineTemplateSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4338,25 +4699,25 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineTemplateSpec(ref common.Ref SchemaProps: spec.SchemaProps{ Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"), }, }, "spec": { SchemaProps: spec.SchemaProps{ Description: "spec is the specification of the desired behavior of the machine. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineSpec"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSpec"), }, }, }, }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.MachineSpec", "sigs.k8s.io/cluster-api/api/v1beta1.ObjectMeta"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineSpec", "sigs.k8s.io/cluster-api/api/core/v1beta1.ObjectMeta"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_MachineV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_MachineV1Beta2Status(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4393,7 +4754,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_MachineV1Beta2Status(ref common.Re } } -func schema_sigsk8sio_cluster_api_api_v1beta1_NetworkRanges(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_NetworkRanges(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4422,7 +4783,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_NetworkRanges(ref common.Reference } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ObjectMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ObjectMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4467,7 +4828,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ObjectMeta(ref common.ReferenceCal } } -func schema_sigsk8sio_cluster_api_api_v1beta1_PatchDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_PatchDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4478,7 +4839,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_PatchDefinition(ref common.Referen SchemaProps: spec.SchemaProps{ Description: "selector defines on which templates the patch should be applied.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.PatchSelector"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelector"), }, }, "jsonPatches": { @@ -4489,7 +4850,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_PatchDefinition(ref common.Referen Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONPatch"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONPatch"), }, }, }, @@ -4500,11 +4861,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_PatchDefinition(ref common.Referen }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.JSONPatch", "sigs.k8s.io/cluster-api/api/v1beta1.PatchSelector"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.JSONPatch", "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelector"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_PatchSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4531,7 +4892,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelector(ref common.Reference SchemaProps: spec.SchemaProps{ Description: "matchResources selects templates based on where they are referenced.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatch"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatch"), }, }, }, @@ -4539,11 +4900,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelector(ref common.Reference }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatch"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatch"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatch(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_PatchSelectorMatch(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4567,24 +4928,24 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatch(ref common.Refe "machineDeploymentClass": { SchemaProps: spec.SchemaProps{ Description: "machineDeploymentClass selects templates referenced in specific MachineDeploymentClasses in .spec.workers.machineDeployments.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatchMachineDeploymentClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatchMachineDeploymentClass"), }, }, "machinePoolClass": { SchemaProps: spec.SchemaProps{ Description: "machinePoolClass selects templates referenced in specific MachinePoolClasses in .spec.workers.machinePools.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatchMachinePoolClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatchMachinePoolClass"), }, }, }, }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatchMachineDeploymentClass", "sigs.k8s.io/cluster-api/api/v1beta1.PatchSelectorMatchMachinePoolClass"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatchMachineDeploymentClass", "sigs.k8s.io/cluster-api/api/core/v1beta1.PatchSelectorMatchMachinePoolClass"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatchMachineDeploymentClass(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_PatchSelectorMatchMachineDeploymentClass(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4612,7 +4973,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatchMachineDeploymen } } -func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatchMachinePoolClass(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_PatchSelectorMatchMachinePoolClass(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4640,7 +5001,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_PatchSelectorMatchMachinePoolClass } } -func schema_sigsk8sio_cluster_api_api_v1beta1_RemediationStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_RemediationStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4661,7 +5022,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_RemediationStrategy(ref common.Ref } } -func schema_sigsk8sio_cluster_api_api_v1beta1_Topology(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_Topology(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4701,13 +5062,13 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_Topology(ref common.ReferenceCallb SchemaProps: spec.SchemaProps{ Description: "controlPlane describes the cluster control plane.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneTopology"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneTopology"), }, }, "workers": { SchemaProps: spec.SchemaProps{ Description: "workers encapsulates the different constructs that form the worker nodes for the cluster.", - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.WorkersTopology"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersTopology"), }, }, "variables": { @@ -4726,7 +5087,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_Topology(ref common.ReferenceCallb Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable"), }, }, }, @@ -4737,11 +5098,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_Topology(ref common.ReferenceCallb }, }, Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time", "sigs.k8s.io/cluster-api/api/v1beta1.ClusterVariable", "sigs.k8s.io/cluster-api/api/v1beta1.ControlPlaneTopology", "sigs.k8s.io/cluster-api/api/v1beta1.WorkersTopology"}, + "k8s.io/apimachinery/pkg/apis/meta/v1.Time", "sigs.k8s.io/cluster-api/api/core/v1beta1.ClusterVariable", "sigs.k8s.io/cluster-api/api/core/v1beta1.ControlPlaneTopology", "sigs.k8s.io/cluster-api/api/core/v1beta1.WorkersTopology"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_UnhealthyCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_UnhealthyCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4779,7 +5140,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_UnhealthyCondition(ref common.Refe } } -func schema_sigsk8sio_cluster_api_api_v1beta1_ValidationRule(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_ValidationRule(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4830,7 +5191,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_ValidationRule(ref common.Referenc } } -func schema_sigsk8sio_cluster_api_api_v1beta1_VariableSchema(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_VariableSchema(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4841,7 +5202,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_VariableSchema(ref common.Referenc SchemaProps: spec.SchemaProps{ Description: "openAPIV3Schema defines the schema of a variable via OpenAPI v3 schema. The schema is a subset of the schema used in Kubernetes CRDs.", Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"), }, }, }, @@ -4849,11 +5210,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_VariableSchema(ref common.Referenc }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.JSONSchemaProps"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.JSONSchemaProps"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_VariableSchemaMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_VariableSchemaMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4898,7 +5259,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_VariableSchemaMetadata(ref common. } } -func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersClass(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_WorkersClass(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -4921,7 +5282,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersClass(ref common.ReferenceC Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClass"), }, }, }, @@ -4943,7 +5304,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersClass(ref common.ReferenceC Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClass"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClass"), }, }, }, @@ -4953,11 +5314,11 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersClass(ref common.ReferenceC }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentClass", "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolClass"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentClass", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolClass"}, } } -func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_WorkersStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -5005,7 +5366,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersStatus(ref common.Reference } } -func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { +func schema_cluster_api_api_core_v1beta1_WorkersTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ @@ -5028,7 +5389,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersTopology(ref common.Referen Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentTopology"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentTopology"), }, }, }, @@ -5050,7 +5411,7 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersTopology(ref common.Referen Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Default: map[string]interface{}{}, - Ref: ref("sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolTopology"), + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolTopology"), }, }, }, @@ -5060,6 +5421,6 @@ func schema_sigsk8sio_cluster_api_api_v1beta1_WorkersTopology(ref common.Referen }, }, Dependencies: []string{ - "sigs.k8s.io/cluster-api/api/v1beta1.MachineDeploymentTopology", "sigs.k8s.io/cluster-api/api/v1beta1.MachinePoolTopology"}, + "sigs.k8s.io/cluster-api/api/core/v1beta1.MachineDeploymentTopology", "sigs.k8s.io/cluster-api/api/core/v1beta1.MachinePoolTopology"}, } } diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/cluster_phase_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/cluster_phase_types.go new file mode 100644 index 000000000000..0706e18e80f2 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/cluster_phase_types.go @@ -0,0 +1,61 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +// ClusterPhase is a string representation of a Cluster Phase. +// +// This type is a high-level indicator of the status of the Cluster as it is provisioned, +// from the API user’s perspective. +// +// The value should not be interpreted by any software components as a reliable indication +// of the actual state of the Cluster, and controllers should not use the Cluster Phase field +// value when making decisions about what action to take. +// +// Controllers should always look at the actual state of the Cluster’s fields to make those decisions. +type ClusterPhase string + +const ( + // ClusterPhasePending is the first state a Cluster is assigned by + // Cluster API Cluster controller after being created. + ClusterPhasePending = ClusterPhase("Pending") + + // ClusterPhaseProvisioning is the state when the Cluster has a infrastructure + // object or a control plane object that can start provisioning the control plane endpoint. + ClusterPhaseProvisioning = ClusterPhase("Provisioning") + + // ClusterPhaseProvisioned is the state when its control plane endpoint has been created and configured + // and the infrastructure object is ready (if defined). + // Note: When a cluster reaches this phase parts of the control plane or worker machines might be still provisioning. + ClusterPhaseProvisioned = ClusterPhase("Provisioned") + + // ClusterPhaseDeleting is the Cluster state when a delete + // request has been sent to the API Server, + // but its infrastructure has not yet been fully deleted. + ClusterPhaseDeleting = ClusterPhase("Deleting") + + // ClusterPhaseFailed is the Cluster state when the system + // might require user intervention. + // + // Deprecated: This enum value is deprecated; the Failed phase won't be set anymore by controllers, and it is preserved only + // for conversion from v1beta1 objects; the Failed phase is going to be removed when support for v1beta1 will be dropped. + // Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + ClusterPhaseFailed = ClusterPhase("Failed") + + // ClusterPhaseUnknown is returned if the Cluster state cannot be determined. + ClusterPhaseUnknown = ClusterPhase("Unknown") +) diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/cluster_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/cluster_types.go new file mode 100644 index 000000000000..af0969853155 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/cluster_types.go @@ -0,0 +1,1628 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "cmp" + "fmt" + "net" + "reflect" + "strings" + + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/intstr" + + capierrors "sigs.k8s.io/cluster-api/errors" +) + +const ( + // ClusterFinalizer is the finalizer used by the cluster controller to + // cleanup the cluster resources when a Cluster is being deleted. + ClusterFinalizer = "cluster.cluster.x-k8s.io" + + // ClusterKind represents the Kind of Cluster. + ClusterKind = "Cluster" +) + +// Cluster's Available condition and corresponding reasons. +const ( + // ClusterAvailableCondition is true if the Cluster is not deleted, and RemoteConnectionProbe, InfrastructureReady, + // ControlPlaneAvailable, WorkersAvailable, TopologyReconciled (if present) conditions are true. + // If conditions are defined in spec.availabilityGates, those conditions must be true as well. + // Note: + // - When summarizing TopologyReconciled, all reasons except TopologyReconcileFailed and ClusterClassNotReconciled will + // be treated as info. This is because even if topology is not fully reconciled, this is an expected temporary state + // and it doesn't impact availability. + // - When summarizing InfrastructureReady, ControlPlaneAvailable, in case the Cluster is deleting, the absence of the + // referenced object won't be considered as an issue. + ClusterAvailableCondition = AvailableCondition + + // ClusterAvailableReason surfaces when the cluster availability criteria is met. + ClusterAvailableReason = AvailableReason + + // ClusterNotAvailableReason surfaces when the cluster availability criteria is not met (and thus the machine is not available). + ClusterNotAvailableReason = NotAvailableReason + + // ClusterAvailableUnknownReason surfaces when at least one cluster availability criteria is unknown + // and no availability criteria is not met. + ClusterAvailableUnknownReason = AvailableUnknownReason + + // ClusterAvailableInternalErrorReason surfaces unexpected error when computing the Available condition. + ClusterAvailableInternalErrorReason = InternalErrorReason +) + +// Cluster's TopologyReconciled condition and corresponding reasons. +const ( + // ClusterTopologyReconciledCondition is true if the topology controller is working properly. + // Note: This condition is added only if the Cluster is referencing a ClusterClass / defining a managed Topology. + ClusterTopologyReconciledCondition = "TopologyReconciled" + + // ClusterTopologyReconcileSucceededReason documents the reconciliation of a Cluster topology succeeded. + ClusterTopologyReconcileSucceededReason = "ReconcileSucceeded" + + // ClusterTopologyReconciledFailedReason documents the reconciliation of a Cluster topology + // failing due to an error. + ClusterTopologyReconciledFailedReason = "ReconcileFailed" + + // ClusterTopologyReconciledControlPlaneUpgradePendingReason documents reconciliation of a Cluster topology + // not yet completed because Control Plane is not yet updated to match the desired topology spec. + ClusterTopologyReconciledControlPlaneUpgradePendingReason = "ControlPlaneUpgradePending" + + // ClusterTopologyReconciledMachineDeploymentsCreatePendingReason documents reconciliation of a Cluster topology + // not yet completed because at least one of the MachineDeployments is yet to be created. + // This generally happens because new MachineDeployment creations are held off while the ControlPlane is not stable. + ClusterTopologyReconciledMachineDeploymentsCreatePendingReason = "MachineDeploymentsCreatePending" + + // ClusterTopologyReconciledMachineDeploymentsUpgradePendingReason documents reconciliation of a Cluster topology + // not yet completed because at least one of the MachineDeployments is not yet updated to match the desired topology spec. + ClusterTopologyReconciledMachineDeploymentsUpgradePendingReason = "MachineDeploymentsUpgradePending" + + // ClusterTopologyReconciledMachineDeploymentsUpgradeDeferredReason documents reconciliation of a Cluster topology + // not yet completed because the upgrade for at least one of the MachineDeployments has been deferred. + ClusterTopologyReconciledMachineDeploymentsUpgradeDeferredReason = "MachineDeploymentsUpgradeDeferred" + + // ClusterTopologyReconciledMachinePoolsUpgradePendingReason documents reconciliation of a Cluster topology + // not yet completed because at least one of the MachinePools is not yet updated to match the desired topology spec. + ClusterTopologyReconciledMachinePoolsUpgradePendingReason = "MachinePoolsUpgradePending" + + // ClusterTopologyReconciledMachinePoolsCreatePendingReason documents reconciliation of a Cluster topology + // not yet completed because at least one of the MachinePools is yet to be created. + // This generally happens because new MachinePool creations are held off while the ControlPlane is not stable. + ClusterTopologyReconciledMachinePoolsCreatePendingReason = "MachinePoolsCreatePending" + + // ClusterTopologyReconciledMachinePoolsUpgradeDeferredReason documents reconciliation of a Cluster topology + // not yet completed because the upgrade for at least one of the MachinePools has been deferred. + ClusterTopologyReconciledMachinePoolsUpgradeDeferredReason = "MachinePoolsUpgradeDeferred" + + // ClusterTopologyReconciledHookBlockingReason documents reconciliation of a Cluster topology + // not yet completed because at least one of the lifecycle hooks is blocking. + ClusterTopologyReconciledHookBlockingReason = "LifecycleHookBlocking" + + // ClusterTopologyReconciledClusterClassNotReconciledReason documents reconciliation of a Cluster topology not + // yet completed because the ClusterClass has not reconciled yet. If this condition persists there may be an issue + // with the ClusterClass surfaced in the ClusterClass status or controller logs. + ClusterTopologyReconciledClusterClassNotReconciledReason = "ClusterClassNotReconciled" + + // ClusterTopologyReconciledDeletingReason surfaces when the Cluster is deleting because the + // DeletionTimestamp is set. + ClusterTopologyReconciledDeletingReason = DeletingReason + + // ClusterTopologyReconcilePausedReason surfaces when the Cluster is paused. + ClusterTopologyReconcilePausedReason = PausedReason +) + +// Cluster's InfrastructureReady condition and corresponding reasons. +const ( + // ClusterInfrastructureReadyCondition mirrors Cluster's infrastructure Ready condition. + ClusterInfrastructureReadyCondition = InfrastructureReadyCondition + + // ClusterInfrastructureReadyReason surfaces when the cluster infrastructure is ready. + ClusterInfrastructureReadyReason = ReadyReason + + // ClusterInfrastructureNotReadyReason surfaces when the cluster infrastructure is not ready. + ClusterInfrastructureNotReadyReason = NotReadyReason + + // ClusterInfrastructureInvalidConditionReportedReason surfaces a infrastructure Ready condition (read from an infra cluster object) which is invalid + // (e.g. its status is missing). + ClusterInfrastructureInvalidConditionReportedReason = InvalidConditionReportedReason + + // ClusterInfrastructureInternalErrorReason surfaces unexpected failures when reading an infra cluster object. + ClusterInfrastructureInternalErrorReason = InternalErrorReason + + // ClusterInfrastructureDoesNotExistReason surfaces when a referenced infrastructure object does not exist. + // Note: this could happen when creating the Cluster. However, this state should be treated as an error if it lasts indefinitely. + ClusterInfrastructureDoesNotExistReason = ObjectDoesNotExistReason + + // ClusterInfrastructureDeletedReason surfaces when a referenced infrastructure object has been deleted. + // Note: controllers can't identify if the infrastructure object was deleted by the controller itself, e.g. + // during the deletion workflow, or by a users. + ClusterInfrastructureDeletedReason = ObjectDeletedReason +) + +// Cluster's ControlPlaneInitialized condition and corresponding reasons. +const ( + // ClusterControlPlaneInitializedCondition is true when the Cluster's control plane is functional enough + // to accept requests. This information is usually used as a signal for starting all the provisioning operations + // that depends on a functional API server, but do not require a full HA control plane to exists. + // Note: Once set to true, this condition will never change. + ClusterControlPlaneInitializedCondition = "ControlPlaneInitialized" + + // ClusterControlPlaneInitializedReason surfaces when the cluster control plane is initialized. + ClusterControlPlaneInitializedReason = "Initialized" + + // ClusterControlPlaneNotInitializedReason surfaces when the cluster control plane is not yet initialized. + ClusterControlPlaneNotInitializedReason = "NotInitialized" + + // ClusterControlPlaneInitializedInternalErrorReason surfaces unexpected failures when computing the + // ControlPlaneInitialized condition. + ClusterControlPlaneInitializedInternalErrorReason = InternalErrorReason +) + +// Cluster's ControlPlaneAvailable condition and corresponding reasons. +const ( + // ClusterControlPlaneAvailableCondition is a mirror of Cluster's control plane Available condition. + ClusterControlPlaneAvailableCondition = "ControlPlaneAvailable" + + // ClusterControlPlaneAvailableReason surfaces when the cluster control plane is available. + ClusterControlPlaneAvailableReason = AvailableReason + + // ClusterControlPlaneNotAvailableReason surfaces when the cluster control plane is not available. + ClusterControlPlaneNotAvailableReason = NotAvailableReason + + // ClusterControlPlaneInvalidConditionReportedReason surfaces a control plane Available condition (read from a control plane object) which is invalid. + // (e.g. its status is missing). + ClusterControlPlaneInvalidConditionReportedReason = InvalidConditionReportedReason + + // ClusterControlPlaneInternalErrorReason surfaces unexpected failures when reading a control plane object. + ClusterControlPlaneInternalErrorReason = InternalErrorReason + + // ClusterControlPlaneDoesNotExistReason surfaces when a referenced control plane object does not exist. + // Note: this could happen when creating the Cluster. However, this state should be treated as an error if it lasts indefinitely. + ClusterControlPlaneDoesNotExistReason = ObjectDoesNotExistReason + + // ClusterControlPlaneDeletedReason surfaces when a referenced control plane object has been deleted. + // Note: controllers can't identify if the control plane object was deleted by the controller itself, e.g. + // during the deletion workflow, or by a users. + ClusterControlPlaneDeletedReason = ObjectDeletedReason +) + +// Cluster's WorkersAvailable condition and corresponding reasons. +const ( + // ClusterWorkersAvailableCondition is the summary of MachineDeployment and MachinePool's Available conditions. + // Note: Stand-alone MachineSets and stand-alone Machines are not included in this condition. + ClusterWorkersAvailableCondition = "WorkersAvailable" + + // ClusterWorkersAvailableReason surfaces when all MachineDeployment and MachinePool's Available conditions are true. + ClusterWorkersAvailableReason = AvailableReason + + // ClusterWorkersNotAvailableReason surfaces when at least one of the MachineDeployment and MachinePool's Available + // conditions is false. + ClusterWorkersNotAvailableReason = NotAvailableReason + + // ClusterWorkersAvailableUnknownReason surfaces when at least one of the MachineDeployment and MachinePool's Available + // conditions is unknown and none of those Available conditions is false. + ClusterWorkersAvailableUnknownReason = AvailableUnknownReason + + // ClusterWorkersAvailableNoWorkersReason surfaces when no MachineDeployment and MachinePool exist for the Cluster. + ClusterWorkersAvailableNoWorkersReason = "NoWorkers" + + // ClusterWorkersAvailableInternalErrorReason surfaces unexpected failures when listing MachineDeployment and MachinePool + // or aggregating conditions from those objects. + ClusterWorkersAvailableInternalErrorReason = InternalErrorReason +) + +// Cluster's ControlPlaneMachinesReady condition and corresponding reasons. +const ( + // ClusterControlPlaneMachinesReadyCondition surfaces detail of issues on control plane machines, if any. + ClusterControlPlaneMachinesReadyCondition = "ControlPlaneMachinesReady" + + // ClusterControlPlaneMachinesReadyReason surfaces when all control plane machine's Ready conditions are true. + ClusterControlPlaneMachinesReadyReason = ReadyReason + + // ClusterControlPlaneMachinesNotReadyReason surfaces when at least one of control plane machine's Ready conditions is false. + ClusterControlPlaneMachinesNotReadyReason = NotReadyReason + + // ClusterControlPlaneMachinesReadyUnknownReason surfaces when at least one of control plane machine's Ready conditions is unknown + // and none of control plane machine's Ready conditions is false. + ClusterControlPlaneMachinesReadyUnknownReason = ReadyUnknownReason + + // ClusterControlPlaneMachinesReadyNoReplicasReason surfaces when no control plane machines exist for the Cluster. + ClusterControlPlaneMachinesReadyNoReplicasReason = NoReplicasReason + + // ClusterControlPlaneMachinesReadyInternalErrorReason surfaces unexpected failures when listing control plane machines + // or aggregating control plane machine's conditions. + ClusterControlPlaneMachinesReadyInternalErrorReason = InternalErrorReason +) + +// Cluster's WorkerMachinesReady condition and corresponding reasons. +const ( + // ClusterWorkerMachinesReadyCondition surfaces detail of issues on the worker machines, if any. + ClusterWorkerMachinesReadyCondition = "WorkerMachinesReady" + + // ClusterWorkerMachinesReadyReason surfaces when all the worker machine's Ready conditions are true. + ClusterWorkerMachinesReadyReason = ReadyReason + + // ClusterWorkerMachinesNotReadyReason surfaces when at least one of the worker machine's Ready conditions is false. + ClusterWorkerMachinesNotReadyReason = NotReadyReason + + // ClusterWorkerMachinesReadyUnknownReason surfaces when at least one of the worker machine's Ready conditions is unknown + // and none of the worker machine's Ready conditions is false. + ClusterWorkerMachinesReadyUnknownReason = ReadyUnknownReason + + // ClusterWorkerMachinesReadyNoReplicasReason surfaces when no worker machines exist for the Cluster. + ClusterWorkerMachinesReadyNoReplicasReason = NoReplicasReason + + // ClusterWorkerMachinesReadyInternalErrorReason surfaces unexpected failures when listing worker machines + // or aggregating worker machine's conditions. + ClusterWorkerMachinesReadyInternalErrorReason = InternalErrorReason +) + +// Cluster's ControlPlaneMachinesUpToDate condition and corresponding reasons. +const ( + // ClusterControlPlaneMachinesUpToDateCondition surfaces details of control plane machines not up to date, if any. + // Note: New machines are considered 10s after machine creation. This gives time to the machine's owner controller to recognize the new machine and add the UpToDate condition. + ClusterControlPlaneMachinesUpToDateCondition = "ControlPlaneMachinesUpToDate" + + // ClusterControlPlaneMachinesUpToDateReason surfaces when all the control plane machine's UpToDate conditions are true. + ClusterControlPlaneMachinesUpToDateReason = UpToDateReason + + // ClusterControlPlaneMachinesNotUpToDateReason surfaces when at least one of the control plane machine's UpToDate conditions is false. + ClusterControlPlaneMachinesNotUpToDateReason = NotUpToDateReason + + // ClusterControlPlaneMachinesUpToDateUnknownReason surfaces when at least one of the control plane machine's UpToDate conditions is unknown + // and none of the control plane machine's UpToDate conditions is false. + ClusterControlPlaneMachinesUpToDateUnknownReason = UpToDateUnknownReason + + // ClusterControlPlaneMachinesUpToDateNoReplicasReason surfaces when no control plane machines exist for the Cluster. + ClusterControlPlaneMachinesUpToDateNoReplicasReason = NoReplicasReason + + // ClusterControlPlaneMachinesUpToDateInternalErrorReason surfaces unexpected failures when listing control plane machines + // or aggregating status. + ClusterControlPlaneMachinesUpToDateInternalErrorReason = InternalErrorReason +) + +// Cluster's WorkerMachinesUpToDate condition and corresponding reasons. +const ( + // ClusterWorkerMachinesUpToDateCondition surfaces details of worker machines not up to date, if any. + // Note: New machines are considered 10s after machine creation. This gives time to the machine's owner controller to recognize the new machine and add the UpToDate condition. + ClusterWorkerMachinesUpToDateCondition = "WorkerMachinesUpToDate" + + // ClusterWorkerMachinesUpToDateReason surfaces when all the worker machine's UpToDate conditions are true. + ClusterWorkerMachinesUpToDateReason = UpToDateReason + + // ClusterWorkerMachinesNotUpToDateReason surfaces when at least one of the worker machine's UpToDate conditions is false. + ClusterWorkerMachinesNotUpToDateReason = NotUpToDateReason + + // ClusterWorkerMachinesUpToDateUnknownReason surfaces when at least one of the worker machine's UpToDate conditions is unknown + // and none of the worker machine's UpToDate conditions is false. + ClusterWorkerMachinesUpToDateUnknownReason = UpToDateUnknownReason + + // ClusterWorkerMachinesUpToDateNoReplicasReason surfaces when no worker machines exist for the Cluster. + ClusterWorkerMachinesUpToDateNoReplicasReason = NoReplicasReason + + // ClusterWorkerMachinesUpToDateInternalErrorReason surfaces unexpected failures when listing worker machines + // or aggregating status. + ClusterWorkerMachinesUpToDateInternalErrorReason = InternalErrorReason +) + +// Cluster's RemoteConnectionProbe condition and corresponding reasons. +const ( + // ClusterRemoteConnectionProbeCondition is true when control plane can be reached; in case of connection problems. + // The condition turns to false only if the cluster cannot be reached for 50s after the first connection problem + // is detected (or whatever period is defined in the --remote-connection-grace-period flag). + ClusterRemoteConnectionProbeCondition = "RemoteConnectionProbe" + + // ClusterRemoteConnectionProbeFailedReason surfaces issues with the connection to the workload cluster. + ClusterRemoteConnectionProbeFailedReason = "ProbeFailed" + + // ClusterRemoteConnectionProbeSucceededReason is used to report a working connection with the workload cluster. + ClusterRemoteConnectionProbeSucceededReason = "ProbeSucceeded" +) + +// Cluster's RollingOut condition and corresponding reasons. +const ( + // ClusterRollingOutCondition is the summary of `RollingOut` conditions from ControlPlane, MachineDeployments + // and MachinePools. + ClusterRollingOutCondition = RollingOutCondition + + // ClusterRollingOutReason surfaces when at least one of the Cluster's control plane, MachineDeployments, + // or MachinePools are rolling out. + ClusterRollingOutReason = RollingOutReason + + // ClusterNotRollingOutReason surfaces when none of the Cluster's control plane, MachineDeployments, + // or MachinePools are rolling out. + ClusterNotRollingOutReason = NotRollingOutReason + + // ClusterRollingOutUnknownReason surfaces when one of the Cluster's control plane, MachineDeployments, + // or MachinePools rolling out condition is unknown, and none true. + ClusterRollingOutUnknownReason = "RollingOutUnknown" + + // ClusterRollingOutInternalErrorReason surfaces unexpected failures when listing machines + // or computing the RollingOut condition. + ClusterRollingOutInternalErrorReason = InternalErrorReason +) + +// Cluster's ScalingUp condition and corresponding reasons. +const ( + // ClusterScalingUpCondition is the summary of `ScalingUp` conditions from ControlPlane, MachineDeployments, + // MachinePools and stand-alone MachineSets. + ClusterScalingUpCondition = ScalingUpCondition + + // ClusterScalingUpReason surfaces when at least one of the Cluster's control plane, MachineDeployments, + // MachinePools and stand-alone MachineSets are scaling up. + ClusterScalingUpReason = ScalingUpReason + + // ClusterNotScalingUpReason surfaces when none of the Cluster's control plane, MachineDeployments, + // MachinePools and stand-alone MachineSets are scaling up. + ClusterNotScalingUpReason = NotScalingUpReason + + // ClusterScalingUpUnknownReason surfaces when one of the Cluster's control plane, MachineDeployments, + // MachinePools and stand-alone MachineSets scaling up condition is unknown, and none true. + ClusterScalingUpUnknownReason = "ScalingUpUnknown" + + // ClusterScalingUpInternalErrorReason surfaces unexpected failures when listing machines + // or computing the ScalingUp condition. + ClusterScalingUpInternalErrorReason = InternalErrorReason +) + +// Cluster's ScalingDown condition and corresponding reasons. +const ( + // ClusterScalingDownCondition is the summary of `ScalingDown` conditions from ControlPlane, MachineDeployments, + // MachinePools and stand-alone MachineSets. + ClusterScalingDownCondition = ScalingDownCondition + + // ClusterScalingDownReason surfaces when at least one of the Cluster's control plane, MachineDeployments, + // MachinePools and stand-alone MachineSets are scaling down. + ClusterScalingDownReason = ScalingDownReason + + // ClusterNotScalingDownReason surfaces when none of the Cluster's control plane, MachineDeployments, + // MachinePools and stand-alone MachineSets are scaling down. + ClusterNotScalingDownReason = NotScalingDownReason + + // ClusterScalingDownUnknownReason surfaces when one of the Cluster's control plane, MachineDeployments, + // MachinePools and stand-alone MachineSets scaling down condition is unknown, and none true. + ClusterScalingDownUnknownReason = "ScalingDownUnknown" + + // ClusterScalingDownInternalErrorReason surfaces unexpected failures when listing machines + // or computing the ScalingDown condition. + ClusterScalingDownInternalErrorReason = InternalErrorReason +) + +// Cluster's Remediating condition and corresponding reasons. +const ( + // ClusterRemediatingCondition surfaces details about ongoing remediation of the controlled machines, if any. + ClusterRemediatingCondition = RemediatingCondition + + // ClusterRemediatingReason surfaces when the Cluster has at least one machine with HealthCheckSucceeded set to false + // and with the OwnerRemediated condition set to false. + ClusterRemediatingReason = RemediatingReason + + // ClusterNotRemediatingReason surfaces when the Cluster does not have any machine with HealthCheckSucceeded set to false + // and with the OwnerRemediated condition set to false. + ClusterNotRemediatingReason = NotRemediatingReason + + // ClusterRemediatingInternalErrorReason surfaces unexpected failures when computing the Remediating condition. + ClusterRemediatingInternalErrorReason = InternalErrorReason +) + +// Cluster's Deleting condition and corresponding reasons. +const ( + // ClusterDeletingCondition surfaces details about ongoing deletion of the cluster. + ClusterDeletingCondition = DeletingCondition + + // ClusterNotDeletingReason surfaces when the Cluster is not deleting because the + // DeletionTimestamp is not set. + ClusterNotDeletingReason = NotDeletingReason + + // ClusterDeletingWaitingForBeforeDeleteHookReason surfaces when the Cluster deletion + // waits for the ClusterDelete hooks to allow deletion to complete. + ClusterDeletingWaitingForBeforeDeleteHookReason = "WaitingForBeforeDeleteHook" + + // ClusterDeletingWaitingForWorkersDeletionReason surfaces when the Cluster deletion + // waits for the workers Machines and the object controlling those machines (MachinePools, MachineDeployments, MachineSets) + // to be deleted. + ClusterDeletingWaitingForWorkersDeletionReason = "WaitingForWorkersDeletion" + + // ClusterDeletingWaitingForControlPlaneDeletionReason surfaces when the Cluster deletion + // waits for the ControlPlane to be deleted. + ClusterDeletingWaitingForControlPlaneDeletionReason = "WaitingForControlPlaneDeletion" + + // ClusterDeletingWaitingForInfrastructureDeletionReason surfaces when the Cluster deletion + // waits for the InfraCluster to be deleted. + ClusterDeletingWaitingForInfrastructureDeletionReason = "WaitingForInfrastructureDeletion" + + // ClusterDeletingDeletionCompletedReason surfaces when the Cluster deletion has been completed. + // This reason is set right after the `cluster.cluster.x-k8s.io` finalizer is removed. + // This means that the object will go away (i.e. be removed from etcd), except if there are other + // finalizers on the Cluster object. + ClusterDeletingDeletionCompletedReason = DeletionCompletedReason + + // ClusterDeletingInternalErrorReason surfaces unexpected failures when deleting a cluster. + ClusterDeletingInternalErrorReason = InternalErrorReason +) + +// ClusterSpec defines the desired state of Cluster. +// +kubebuilder:validation:MinProperties=1 +type ClusterSpec struct { + // paused can be used to prevent controllers from processing the Cluster and all its associated objects. + // +optional + Paused *bool `json:"paused,omitempty"` + + // clusterNetwork represents the cluster network configuration. + // +optional + ClusterNetwork ClusterNetwork `json:"clusterNetwork,omitempty,omitzero"` + + // controlPlaneEndpoint represents the endpoint used to communicate with the control plane. + // +optional + ControlPlaneEndpoint APIEndpoint `json:"controlPlaneEndpoint,omitempty,omitzero"` + + // controlPlaneRef is an optional reference to a provider-specific resource that holds + // the details for provisioning the Control Plane for a Cluster. + // +optional + ControlPlaneRef ContractVersionedObjectReference `json:"controlPlaneRef,omitempty,omitzero"` + + // infrastructureRef is a reference to a provider-specific resource that holds the details + // for provisioning infrastructure for a cluster in said provider. + // +optional + InfrastructureRef ContractVersionedObjectReference `json:"infrastructureRef,omitempty,omitzero"` + + // topology encapsulates the topology for the cluster. + // NOTE: It is required to enable the ClusterTopology + // feature gate flag to activate managed topologies support; + // this feature is highly experimental, and parts of it might still be not implemented. + // +optional + Topology Topology `json:"topology,omitempty,omitzero"` + + // availabilityGates specifies additional conditions to include when evaluating Cluster Available condition. + // + // If this field is not defined and the Cluster implements a managed topology, availabilityGates + // from the corresponding ClusterClass will be used, if any. + // + // +optional + // +listType=map + // +listMapKey=conditionType + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + AvailabilityGates []ClusterAvailabilityGate `json:"availabilityGates,omitempty"` +} + +// ConditionPolarity defines the polarity for a metav1.Condition. +// +kubebuilder:validation:Enum=Positive;Negative +type ConditionPolarity string + +const ( + // PositivePolarityCondition describe a condition with positive polarity, a condition + // where the normal state is True. e.g. NetworkReady. + PositivePolarityCondition ConditionPolarity = "Positive" + + // NegativePolarityCondition describe a condition with negative polarity, a condition + // where the normal state is False. e.g. MemoryPressure. + NegativePolarityCondition ConditionPolarity = "Negative" +) + +// ClusterAvailabilityGate contains the type of a Cluster condition to be used as availability gate. +type ClusterAvailabilityGate struct { + // conditionType refers to a condition with matching type in the Cluster's condition list. + // If the conditions doesn't exist, it will be treated as unknown. + // Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as availability gates. + // +required + // +kubebuilder:validation:Pattern=`^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$` + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=316 + ConditionType string `json:"conditionType,omitempty"` + + // polarity of the conditionType specified in this availabilityGate. + // Valid values are Positive, Negative and omitted. + // When omitted, the default behaviour will be Positive. + // A positive polarity means that the condition should report a true status under normal conditions. + // A negative polarity means that the condition should report a false status under normal conditions. + // +optional + Polarity ConditionPolarity `json:"polarity,omitempty"` +} + +// Topology encapsulates the information of the managed resources. +type Topology struct { + // classRef is the ref to the ClusterClass that should be used for the topology. + // +required + ClassRef ClusterClassRef `json:"classRef,omitempty,omitzero"` + + // version is the Kubernetes version of the cluster. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Version string `json:"version,omitempty"` + + // controlPlane describes the cluster control plane. + // +optional + ControlPlane ControlPlaneTopology `json:"controlPlane,omitempty,omitzero"` + + // workers encapsulates the different constructs that form the worker nodes + // for the cluster. + // +optional + Workers WorkersTopology `json:"workers,omitempty,omitzero"` + + // variables can be used to customize the Cluster through + // patches. They must comply to the corresponding + // VariableClasses defined in the ClusterClass. + // +optional + // +listType=map + // +listMapKey=name + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=1000 + Variables []ClusterVariable `json:"variables,omitempty"` +} + +// IsDefined returns true if the Topology is defined. +func (r *Topology) IsDefined() bool { + return !reflect.DeepEqual(r, &Topology{}) +} + +// ClusterClassRef is the ref to the ClusterClass that should be used for the topology. +type ClusterClassRef struct { + // name is the name of the ClusterClass that should be used for the topology. + // name must be a valid ClusterClass name and because of that be at most 253 characters in length + // and it must consist only of lower case alphanumeric characters, hyphens (-) and periods (.), and must start + // and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` + + // namespace is the namespace of the ClusterClass that should be used for the topology. + // If namespace is empty or not set, it is defaulted to the namespace of the Cluster object. + // namespace must be a valid namespace name and because of that be at most 63 characters in length + // and it must consist only of lower case alphanumeric characters or hyphens (-), and must start + // and end with an alphanumeric character. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$` + Namespace string `json:"namespace,omitempty"` +} + +// ControlPlaneTopology specifies the parameters for the control plane nodes in the cluster. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneTopology struct { + // metadata is the metadata applied to the ControlPlane and the Machines of the ControlPlane + // if the ControlPlaneTemplate referenced by the ClusterClass is machine based. If not, it + // is applied only to the ControlPlane. + // At runtime this metadata is merged with the corresponding metadata from the ClusterClass. + // +optional + Metadata ObjectMeta `json:"metadata,omitempty,omitzero"` + + // replicas is the number of control plane nodes. + // If the value is not set, the ControlPlane object is created without the number of Replicas + // and it's assumed that the control plane controller does not implement support for this field. + // When specified against a control plane provider that lacks support for this field, this value will be ignored. + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // healthCheck allows to enable, disable and override control plane health check + // configuration from the ClusterClass for this control plane. + // +optional + HealthCheck ControlPlaneTopologyHealthCheck `json:"healthCheck,omitempty,omitzero"` + + // deletion contains configuration options for Machine deletion. + // +optional + Deletion ControlPlaneTopologyMachineDeletionSpec `json:"deletion,omitempty,omitzero"` + + // readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + // + // This field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready + // computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine. + // + // If this field is not defined, readinessGates from the corresponding ControlPlaneClass will be used, if any. + // + // NOTE: Specific control plane provider implementations might automatically extend the list of readinessGates; + // e.g. the kubeadm control provider adds ReadinessGates for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + // +optional + // +listType=map + // +listMapKey=conditionType + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + ReadinessGates []MachineReadinessGate `json:"readinessGates,omitempty"` + + // variables can be used to customize the ControlPlane through patches. + // +optional + Variables ControlPlaneVariables `json:"variables,omitempty,omitzero"` +} + +// ControlPlaneTopologyHealthCheck defines a MachineHealthCheck for control plane machines. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneTopologyHealthCheck struct { + // enabled controls if a MachineHealthCheck should be created for the target machines. + // + // If false: No MachineHealthCheck will be created. + // + // If not set(default): A MachineHealthCheck will be created if it is defined here or + // in the associated ClusterClass. If no MachineHealthCheck is defined then none will be created. + // + // If true: A MachineHealthCheck is guaranteed to be created. Cluster validation will + // block if `enable` is true and no MachineHealthCheck definition is available. + // +optional + Enabled *bool `json:"enabled,omitempty"` + + // checks are the checks that are used to evaluate if a Machine is healthy. + // + // If one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, + // and as a consequence the checks and remediation fields from Cluster will be used instead of the + // corresponding fields in ClusterClass. + // + // Independent of this configuration the MachineHealthCheck controller will always + // flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + // Machines with deleted Nodes as unhealthy. + // + // Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + // is defaulted to 10 minutes and evaluated accordingly. + // + // +optional + Checks ControlPlaneTopologyHealthCheckChecks `json:"checks,omitempty,omitzero"` + + // remediation configures if and how remediations are triggered if a Machine is unhealthy. + // + // If one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, + // and as a consequence the checks and remediation fields from cluster will be used instead of the + // corresponding fields in ClusterClass. + // + // If an health check override is defined and remediation or remediation.triggerIf is not set, + // remediation will always be triggered for unhealthy Machines. + // + // If an health check override is defined and remediation or remediation.templateRef is not set, + // the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + // the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + // + // +optional + Remediation ControlPlaneTopologyHealthCheckRemediation `json:"remediation,omitempty,omitzero"` +} + +// IsDefined returns true if one of checks and remediation are not zero. +func (m *ControlPlaneTopologyHealthCheck) IsDefined() bool { + return !reflect.ValueOf(m.Checks).IsZero() || !reflect.ValueOf(m.Remediation).IsZero() +} + +// ControlPlaneTopologyHealthCheckChecks are the checks that are used to evaluate if a control plane Machine is healthy. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneTopologyHealthCheckChecks struct { + // nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + // to consider a Machine unhealthy if a corresponding Node isn't associated + // through a `Spec.ProviderID` field. + // + // The duration set in this field is compared to the greatest of: + // - Cluster's infrastructure ready condition timestamp (if and when available) + // - Control Plane's initialized condition timestamp (if and when available) + // - Machine's infrastructure ready condition timestamp (if and when available) + // - Machine's metadata creation timestamp + // + // Defaults to 10 minutes. + // If you wish to disable this feature, set the value explicitly to 0. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeStartupTimeoutSeconds *int32 `json:"nodeStartupTimeoutSeconds,omitempty"` + + // unhealthyNodeConditions contains a list of conditions that determine + // whether a node is considered unhealthy. The conditions are combined in a + // logical OR, i.e. if any of the conditions is met, the node is unhealthy. + // + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + UnhealthyNodeConditions []UnhealthyNodeCondition `json:"unhealthyNodeConditions,omitempty"` +} + +// ControlPlaneTopologyHealthCheckRemediation configures if and how remediations are triggered if a control plane Machine is unhealthy. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneTopologyHealthCheckRemediation struct { + // triggerIf configures if remediations are triggered. + // If this field is not set, remediations are always triggered. + // +optional + TriggerIf ControlPlaneTopologyHealthCheckRemediationTriggerIf `json:"triggerIf,omitempty,omitzero"` + + // templateRef is a reference to a remediation template + // provided by an infrastructure provider. + // + // This field is completely optional, when filled, the MachineHealthCheck controller + // creates a new object from the template referenced and hands off remediation of the machine to + // a controller that lives outside of Cluster API. + // +optional + TemplateRef MachineHealthCheckRemediationTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// ControlPlaneTopologyHealthCheckRemediationTriggerIf configures if remediations are triggered. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneTopologyHealthCheckRemediationTriggerIf struct { + // unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + // unhealthy Machines is less than or equal to the configured value. + // unhealthyInRange takes precedence if set. + // + // +optional + UnhealthyLessThanOrEqualTo *intstr.IntOrString `json:"unhealthyLessThanOrEqualTo,omitempty"` + + // unhealthyInRange specifies that remediations are only triggered if the number of + // unhealthy Machines is in the configured range. + // Takes precedence over unhealthyLessThanOrEqualTo. + // Eg. "[3-5]" - This means that remediation will be allowed only when: + // (a) there are at least 3 unhealthy Machines (and) + // (b) there are at most 5 unhealthy Machines + // + // +optional + // +kubebuilder:validation:Pattern=^\[[0-9]+-[0-9]+\]$ + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=32 + UnhealthyInRange string `json:"unhealthyInRange,omitempty"` +} + +// ControlPlaneTopologyMachineDeletionSpec contains configuration options for Machine deletion. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneTopologyMachineDeletionSpec struct { + // nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + // The default value is 0, meaning that the node can be drained without any time limitations. + // NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDrainTimeoutSeconds *int32 `json:"nodeDrainTimeoutSeconds,omitempty"` + + // nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + // to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeVolumeDetachTimeoutSeconds *int32 `json:"nodeVolumeDetachTimeoutSeconds,omitempty"` + + // nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + // hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + // Defaults to 10 seconds. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDeletionTimeoutSeconds *int32 `json:"nodeDeletionTimeoutSeconds,omitempty"` +} + +// WorkersTopology represents the different sets of worker nodes in the cluster. +// +kubebuilder:validation:MinProperties=1 +type WorkersTopology struct { + // machineDeployments is a list of machine deployments in the cluster. + // +optional + // +listType=map + // +listMapKey=name + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=2000 + MachineDeployments []MachineDeploymentTopology `json:"machineDeployments,omitempty"` + + // machinePools is a list of machine pools in the cluster. + // +optional + // +listType=map + // +listMapKey=name + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=2000 + MachinePools []MachinePoolTopology `json:"machinePools,omitempty"` +} + +// MachineDeploymentTopology specifies the different parameters for a set of worker nodes in the topology. +// This set of nodes is managed by a MachineDeployment object whose lifecycle is managed by the Cluster controller. +type MachineDeploymentTopology struct { + // metadata is the metadata applied to the MachineDeployment and the machines of the MachineDeployment. + // At runtime this metadata is merged with the corresponding metadata from the ClusterClass. + // +optional + Metadata ObjectMeta `json:"metadata,omitempty,omitzero"` + + // class is the name of the MachineDeploymentClass used to create the set of worker nodes. + // This should match one of the deployment classes defined in the ClusterClass object + // mentioned in the `Cluster.Spec.Class` field. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Class string `json:"class,omitempty"` + + // name is the unique identifier for this MachineDeploymentTopology. + // The value is used with other unique identifiers to create a MachineDeployment's Name + // (e.g. cluster's name, etc). In case the name is greater than the allowed maximum length, + // the values are hashed together. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` + + // failureDomain is the failure domain the machines will be created in. + // Must match a key in the FailureDomains map stored on the cluster object. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + FailureDomain string `json:"failureDomain,omitempty"` + + // replicas is the number of worker nodes belonging to this set. + // If the value is nil, the MachineDeployment is created without the number of Replicas (defaulting to 1) + // and it's assumed that an external entity (like cluster autoscaler) is responsible for the management + // of this value. + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // healthCheck allows to enable, disable and override MachineDeployment health check + // configuration from the ClusterClass for this MachineDeployment. + // +optional + HealthCheck MachineDeploymentTopologyHealthCheck `json:"healthCheck,omitempty,omitzero"` + + // deletion contains configuration options for Machine deletion. + // +optional + Deletion MachineDeploymentTopologyMachineDeletionSpec `json:"deletion,omitempty,omitzero"` + + // minReadySeconds is the minimum number of seconds for which a newly created machine should + // be ready. + // Defaults to 0 (machine will be considered available as soon as it + // is ready) + // +optional + // +kubebuilder:validation:Minimum=0 + MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` + + // readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + // + // This field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready + // computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine. + // + // If this field is not defined, readinessGates from the corresponding MachineDeploymentClass will be used, if any. + // + // +optional + // +listType=map + // +listMapKey=conditionType + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + ReadinessGates []MachineReadinessGate `json:"readinessGates,omitempty"` + + // rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. + // It allows you to define the strategy used during rolling replacements. + // +optional + Rollout MachineDeploymentTopologyRolloutSpec `json:"rollout,omitempty,omitzero"` + + // variables can be used to customize the MachineDeployment through patches. + // +optional + Variables MachineDeploymentVariables `json:"variables,omitempty,omitzero"` +} + +// MachineDeploymentTopologyHealthCheck defines a MachineHealthCheck for MachineDeployment machines. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentTopologyHealthCheck struct { + // enabled controls if a MachineHealthCheck should be created for the target machines. + // + // If false: No MachineHealthCheck will be created. + // + // If not set(default): A MachineHealthCheck will be created if it is defined here or + // in the associated ClusterClass. If no MachineHealthCheck is defined then none will be created. + // + // If true: A MachineHealthCheck is guaranteed to be created. Cluster validation will + // block if `enable` is true and no MachineHealthCheck definition is available. + // +optional + Enabled *bool `json:"enabled,omitempty"` + + // checks are the checks that are used to evaluate if a Machine is healthy. + // + // If one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, + // and as a consequence the checks and remediation fields from Cluster will be used instead of the + // corresponding fields in ClusterClass. + // + // Independent of this configuration the MachineHealthCheck controller will always + // flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + // Machines with deleted Nodes as unhealthy. + // + // Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + // is defaulted to 10 minutes and evaluated accordingly. + // + // +optional + Checks MachineDeploymentTopologyHealthCheckChecks `json:"checks,omitempty,omitzero"` + + // remediation configures if and how remediations are triggered if a Machine is unhealthy. + // + // If one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, + // and as a consequence the checks and remediation fields from cluster will be used instead of the + // corresponding fields in ClusterClass. + // + // If an health check override is defined and remediation or remediation.triggerIf is not set, + // remediation will always be triggered for unhealthy Machines. + // + // If an health check override is defined and remediation or remediation.templateRef is not set, + // the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + // the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + // + // +optional + Remediation MachineDeploymentTopologyHealthCheckRemediation `json:"remediation,omitempty,omitzero"` +} + +// IsDefined returns true if one of checks and remediation are not zero. +func (m *MachineDeploymentTopologyHealthCheck) IsDefined() bool { + return !reflect.ValueOf(m.Checks).IsZero() || !reflect.ValueOf(m.Remediation).IsZero() +} + +// MachineDeploymentTopologyHealthCheckChecks are the checks that are used to evaluate if a MachineDeployment Machine is healthy. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentTopologyHealthCheckChecks struct { + // nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + // to consider a Machine unhealthy if a corresponding Node isn't associated + // through a `Spec.ProviderID` field. + // + // The duration set in this field is compared to the greatest of: + // - Cluster's infrastructure ready condition timestamp (if and when available) + // - Control Plane's initialized condition timestamp (if and when available) + // - Machine's infrastructure ready condition timestamp (if and when available) + // - Machine's metadata creation timestamp + // + // Defaults to 10 minutes. + // If you wish to disable this feature, set the value explicitly to 0. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeStartupTimeoutSeconds *int32 `json:"nodeStartupTimeoutSeconds,omitempty"` + + // unhealthyNodeConditions contains a list of conditions that determine + // whether a node is considered unhealthy. The conditions are combined in a + // logical OR, i.e. if any of the conditions is met, the node is unhealthy. + // + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + UnhealthyNodeConditions []UnhealthyNodeCondition `json:"unhealthyNodeConditions,omitempty"` +} + +// MachineDeploymentTopologyHealthCheckRemediation configures if and how remediations are triggered if a MachineDeployment Machine is unhealthy. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentTopologyHealthCheckRemediation struct { + // maxInFlight determines how many in flight remediations should happen at the same time. + // + // Remediation only happens on the MachineSet with the most current revision, while + // older MachineSets (usually present during rollout operations) aren't allowed to remediate. + // + // Note: In general (independent of remediations), unhealthy machines are always + // prioritized during scale down operations over healthy ones. + // + // MaxInFlight can be set to a fixed number or a percentage. + // Example: when this is set to 20%, the MachineSet controller deletes at most 20% of + // the desired replicas. + // + // If not set, remediation is limited to all machines (bounded by replicas) + // under the active MachineSet's management. + // + // +optional + MaxInFlight *intstr.IntOrString `json:"maxInFlight,omitempty"` + + // triggerIf configures if remediations are triggered. + // If this field is not set, remediations are always triggered. + // +optional + TriggerIf MachineDeploymentTopologyHealthCheckRemediationTriggerIf `json:"triggerIf,omitempty,omitzero"` + + // templateRef is a reference to a remediation template + // provided by an infrastructure provider. + // + // This field is completely optional, when filled, the MachineHealthCheck controller + // creates a new object from the template referenced and hands off remediation of the machine to + // a controller that lives outside of Cluster API. + // +optional + TemplateRef MachineHealthCheckRemediationTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// MachineDeploymentTopologyHealthCheckRemediationTriggerIf configures if remediations are triggered. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentTopologyHealthCheckRemediationTriggerIf struct { + // unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + // unhealthy Machines is less than or equal to the configured value. + // unhealthyInRange takes precedence if set. + // + // +optional + UnhealthyLessThanOrEqualTo *intstr.IntOrString `json:"unhealthyLessThanOrEqualTo,omitempty"` + + // unhealthyInRange specifies that remediations are only triggered if the number of + // unhealthy Machines is in the configured range. + // Takes precedence over unhealthyLessThanOrEqualTo. + // Eg. "[3-5]" - This means that remediation will be allowed only when: + // (a) there are at least 3 unhealthy Machines (and) + // (b) there are at most 5 unhealthy Machines + // + // +optional + // +kubebuilder:validation:Pattern=^\[[0-9]+-[0-9]+\]$ + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=32 + UnhealthyInRange string `json:"unhealthyInRange,omitempty"` +} + +// MachineDeploymentTopologyMachineDeletionSpec contains configuration options for Machine deletion. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentTopologyMachineDeletionSpec struct { + // order defines the order in which Machines are deleted when downscaling. + // Defaults to "Random". Valid values are "Random, "Newest", "Oldest" + // +optional + Order MachineSetDeletionOrder `json:"order,omitempty"` + + // nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + // The default value is 0, meaning that the node can be drained without any time limitations. + // NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDrainTimeoutSeconds *int32 `json:"nodeDrainTimeoutSeconds,omitempty"` + + // nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + // to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeVolumeDetachTimeoutSeconds *int32 `json:"nodeVolumeDetachTimeoutSeconds,omitempty"` + + // nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + // hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + // Defaults to 10 seconds. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDeletionTimeoutSeconds *int32 `json:"nodeDeletionTimeoutSeconds,omitempty"` +} + +// MachineDeploymentTopologyRolloutSpec defines the rollout behavior. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentTopologyRolloutSpec struct { + // strategy specifies how to roll out control plane Machines. + // +optional + Strategy MachineDeploymentTopologyRolloutStrategy `json:"strategy,omitempty,omitzero"` +} + +// MachineDeploymentTopologyRolloutStrategy describes how to replace existing machines +// with new ones. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentTopologyRolloutStrategy struct { + // type of rollout. Allowed values are RollingUpdate and OnDelete. + // Default is RollingUpdate. + // +required + Type MachineDeploymentRolloutStrategyType `json:"type,omitempty"` + + // rollingUpdate is the rolling update config params. Present only if + // type = RollingUpdate. + // +optional + RollingUpdate MachineDeploymentTopologyRolloutStrategyRollingUpdate `json:"rollingUpdate,omitempty,omitzero"` +} + +// MachineDeploymentTopologyRolloutStrategyRollingUpdate is used to control the desired behavior of rolling update. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentTopologyRolloutStrategyRollingUpdate struct { + // maxUnavailable is the maximum number of machines that can be unavailable during the update. + // Value can be an absolute number (ex: 5) or a percentage of desired + // machines (ex: 10%). + // Absolute number is calculated from percentage by rounding down. + // This can not be 0 if MaxSurge is 0. + // Defaults to 0. + // Example: when this is set to 30%, the old MachineSet can be scaled + // down to 70% of desired machines immediately when the rolling update + // starts. Once new machines are ready, old MachineSet can be scaled + // down further, followed by scaling up the new MachineSet, ensuring + // that the total number of machines available at all times + // during the update is at least 70% of desired machines. + // +optional + MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty"` + + // maxSurge is the maximum number of machines that can be scheduled above the + // desired number of machines. + // Value can be an absolute number (ex: 5) or a percentage of + // desired machines (ex: 10%). + // This can not be 0 if MaxUnavailable is 0. + // Absolute number is calculated from percentage by rounding up. + // Defaults to 1. + // Example: when this is set to 30%, the new MachineSet can be scaled + // up immediately when the rolling update starts, such that the total + // number of old and new machines do not exceed 130% of desired + // machines. Once old machines have been killed, new MachineSet can + // be scaled up further, ensuring that total number of machines running + // at any time during the update is at most 130% of desired machines. + // +optional + MaxSurge *intstr.IntOrString `json:"maxSurge,omitempty"` +} + +// MachinePoolTopology specifies the different parameters for a pool of worker nodes in the topology. +// This pool of nodes is managed by a MachinePool object whose lifecycle is managed by the Cluster controller. +type MachinePoolTopology struct { + // metadata is the metadata applied to the MachinePool. + // At runtime this metadata is merged with the corresponding metadata from the ClusterClass. + // +optional + Metadata ObjectMeta `json:"metadata,omitempty,omitzero"` + + // class is the name of the MachinePoolClass used to create the pool of worker nodes. + // This should match one of the deployment classes defined in the ClusterClass object + // mentioned in the `Cluster.Spec.Class` field. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Class string `json:"class,omitempty"` + + // name is the unique identifier for this MachinePoolTopology. + // The value is used with other unique identifiers to create a MachinePool's Name + // (e.g. cluster's name, etc). In case the name is greater than the allowed maximum length, + // the values are hashed together. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` + + // failureDomains is the list of failure domains the machine pool will be created in. + // Must match a key in the FailureDomains map stored on the cluster object. + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=256 + FailureDomains []string `json:"failureDomains,omitempty"` + + // deletion contains configuration options for Machine deletion. + // +optional + Deletion MachinePoolTopologyMachineDeletionSpec `json:"deletion,omitempty,omitzero"` + + // minReadySeconds is the minimum number of seconds for which a newly created machine pool should + // be ready. + // Defaults to 0 (machine will be considered available as soon as it + // is ready) + // +optional + // +kubebuilder:validation:Minimum=0 + MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` + + // replicas is the number of nodes belonging to this pool. + // If the value is nil, the MachinePool is created without the number of Replicas (defaulting to 1) + // and it's assumed that an external entity (like cluster autoscaler) is responsible for the management + // of this value. + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // variables can be used to customize the MachinePool through patches. + // +optional + Variables MachinePoolVariables `json:"variables,omitempty,omitzero"` +} + +// MachinePoolTopologyMachineDeletionSpec contains configuration options for Machine deletion. +// +kubebuilder:validation:MinProperties=1 +type MachinePoolTopologyMachineDeletionSpec struct { + // nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + // The default value is 0, meaning that the node can be drained without any time limitations. + // NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDrainTimeoutSeconds *int32 `json:"nodeDrainTimeoutSeconds,omitempty"` + + // nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + // to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeVolumeDetachTimeoutSeconds *int32 `json:"nodeVolumeDetachTimeoutSeconds,omitempty"` + + // nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the MachinePool + // hosts after the MachinePool is marked for deletion. A duration of 0 will retry deletion indefinitely. + // Defaults to 10 seconds. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDeletionTimeoutSeconds *int32 `json:"nodeDeletionTimeoutSeconds,omitempty"` +} + +// ClusterVariable can be used to customize the Cluster through patches. Each ClusterVariable is associated with a +// Variable definition in the ClusterClass `status` variables. +type ClusterVariable struct { + // name of the variable. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Name string `json:"name,omitempty"` + + // value of the variable. + // Note: the value will be validated against the schema of the corresponding ClusterClassVariable + // from the ClusterClass. + // Note: We have to use apiextensionsv1.JSON instead of a custom JSON type, because controller-tools has a + // hard-coded schema for apiextensionsv1.JSON which cannot be produced by another type via controller-tools, + // i.e. it is not possible to have no type field. + // Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111 + // +required + Value apiextensionsv1.JSON `json:"value,omitempty,omitzero"` +} + +// ControlPlaneVariables can be used to provide variables for the ControlPlane. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneVariables struct { + // overrides can be used to override Cluster level variables. + // +optional + // +listType=map + // +listMapKey=name + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=1000 + Overrides []ClusterVariable `json:"overrides,omitempty"` +} + +// MachineDeploymentVariables can be used to provide variables for a specific MachineDeployment. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentVariables struct { + // overrides can be used to override Cluster level variables. + // +optional + // +listType=map + // +listMapKey=name + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=1000 + Overrides []ClusterVariable `json:"overrides,omitempty"` +} + +// MachinePoolVariables can be used to provide variables for a specific MachinePool. +// +kubebuilder:validation:MinProperties=1 +type MachinePoolVariables struct { + // overrides can be used to override Cluster level variables. + // +optional + // +listType=map + // +listMapKey=name + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=1000 + Overrides []ClusterVariable `json:"overrides,omitempty"` +} + +// ClusterNetwork specifies the different networking +// parameters for a cluster. +// +kubebuilder:validation:MinProperties=1 +type ClusterNetwork struct { + // apiServerPort specifies the port the API Server should bind to. + // Defaults to 6443. + // +optional + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + APIServerPort int32 `json:"apiServerPort,omitempty"` + + // services is the network ranges from which service VIPs are allocated. + // +optional + Services NetworkRanges `json:"services,omitempty,omitzero"` + + // pods is the network ranges from which Pod networks are allocated. + // +optional + Pods NetworkRanges `json:"pods,omitempty,omitzero"` + + // serviceDomain is the domain name for services. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + ServiceDomain string `json:"serviceDomain,omitempty"` +} + +// NetworkRanges represents ranges of network addresses. +type NetworkRanges struct { + // cidrBlocks is a list of CIDR blocks. + // +required + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=43 + CIDRBlocks []string `json:"cidrBlocks,omitempty"` +} + +func (n NetworkRanges) String() string { + if len(n.CIDRBlocks) == 0 { + return "" + } + return strings.Join(n.CIDRBlocks, ",") +} + +// ClusterStatus defines the observed state of Cluster. +// +kubebuilder:validation:MinProperties=1 +type ClusterStatus struct { + // conditions represents the observations of a Cluster's current state. + // Known condition types are Available, InfrastructureReady, ControlPlaneInitialized, ControlPlaneAvailable, WorkersAvailable, MachinesReady + // MachinesUpToDate, RemoteConnectionProbe, ScalingUp, ScalingDown, Remediating, Deleting, Paused. + // Additionally, a TopologyReconciled condition will be added in case the Cluster is referencing a ClusterClass / defining a managed Topology. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // initialization provides observations of the Cluster initialization process. + // NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Cluster provisioning. + // +optional + Initialization ClusterInitializationStatus `json:"initialization,omitempty,omitzero"` + + // controlPlane groups all the observations about Cluster's ControlPlane current state. + // +optional + ControlPlane *ClusterControlPlaneStatus `json:"controlPlane,omitempty"` + + // workers groups all the observations about Cluster's Workers current state. + // +optional + Workers *WorkersStatus `json:"workers,omitempty"` + + // failureDomains is a slice of failure domain objects synced from the infrastructure provider. + // +optional + // +listType=map + // +listMapKey=name + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + FailureDomains []FailureDomain `json:"failureDomains,omitempty"` + + // phase represents the current phase of cluster actuation. + // +optional + // +kubebuilder:validation:Enum=Pending;Provisioning;Provisioned;Deleting;Failed;Unknown + Phase string `json:"phase,omitempty"` + + // observedGeneration is the latest generation observed by the controller. + // +optional + // +kubebuilder:validation:Minimum=1 + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. + // +optional + Deprecated *ClusterDeprecatedStatus `json:"deprecated,omitempty"` +} + +// ClusterInitializationStatus provides observations of the Cluster initialization process. +// NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Cluster provisioning. +// +kubebuilder:validation:MinProperties=1 +type ClusterInitializationStatus struct { + // infrastructureProvisioned is true when the infrastructure provider reports that Cluster's infrastructure is fully provisioned. + // NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + // The value of this field is never updated after provisioning is completed. + // +optional + InfrastructureProvisioned *bool `json:"infrastructureProvisioned,omitempty"` + + // controlPlaneInitialized denotes when the control plane is functional enough to accept requests. + // This information is usually used as a signal for starting all the provisioning operations that depends on + // a functional API server, but do not require a full HA control plane to exists, like e.g. join worker Machines, + // install core addons like CNI, CPI, CSI etc. + // NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + // The value of this field is never updated after initialization is completed. + // +optional + ControlPlaneInitialized *bool `json:"controlPlaneInitialized,omitempty"` +} + +// ClusterDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type ClusterDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + // +optional + V1Beta1 *ClusterV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` +} + +// ClusterV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type ClusterV1Beta1DeprecatedStatus struct { + // conditions defines current service state of the cluster. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + Conditions Conditions `json:"conditions,omitempty"` + + // failureReason indicates that there is a fatal problem reconciling the + // state, and will be set to a token value suitable for + // programmatic interpretation. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + FailureReason *capierrors.ClusterStatusError `json:"failureReason,omitempty"` + + // failureMessage indicates that there is a fatal problem reconciling the + // state, and will be set to a descriptive error message. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=10240 + FailureMessage *string `json:"failureMessage,omitempty"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed +} + +// ClusterControlPlaneStatus groups all the observations about control plane current state. +type ClusterControlPlaneStatus struct { + // desiredReplicas is the total number of desired control plane machines in this cluster. + // +optional + DesiredReplicas *int32 `json:"desiredReplicas,omitempty"` + + // replicas is the total number of control plane machines in this cluster. + // NOTE: replicas also includes machines still being provisioned or being deleted. + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // upToDateReplicas is the number of up-to-date control plane machines in this cluster. A machine is considered up-to-date when Machine's UpToDate condition is true. + // +optional + UpToDateReplicas *int32 `json:"upToDateReplicas,omitempty"` + + // readyReplicas is the total number of ready control plane machines in this cluster. A machine is considered ready when Machine's Ready condition is true. + // +optional + ReadyReplicas *int32 `json:"readyReplicas,omitempty"` + + // availableReplicas is the total number of available control plane machines in this cluster. A machine is considered available when Machine's Available condition is true. + // +optional + AvailableReplicas *int32 `json:"availableReplicas,omitempty"` +} + +// WorkersStatus groups all the observations about workers current state. +type WorkersStatus struct { + // desiredReplicas is the total number of desired worker machines in this cluster. + // +optional + DesiredReplicas *int32 `json:"desiredReplicas,omitempty"` + + // replicas is the total number of worker machines in this cluster. + // NOTE: replicas also includes machines still being provisioned or being deleted. + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // upToDateReplicas is the number of up-to-date worker machines in this cluster. A machine is considered up-to-date when Machine's UpToDate condition is true. + // +optional + UpToDateReplicas *int32 `json:"upToDateReplicas,omitempty"` + + // readyReplicas is the total number of ready worker machines in this cluster. A machine is considered ready when Machine's Ready condition is true. + // +optional + ReadyReplicas *int32 `json:"readyReplicas,omitempty"` + + // availableReplicas is the total number of available worker machines in this cluster. A machine is considered available when Machine's Available condition is true. + // +optional + AvailableReplicas *int32 `json:"availableReplicas,omitempty"` +} + +// SetTypedPhase sets the Phase field to the string representation of ClusterPhase. +func (c *ClusterStatus) SetTypedPhase(p ClusterPhase) { + c.Phase = string(p) +} + +// GetTypedPhase attempts to parse the Phase field and return +// the typed ClusterPhase representation as described in `machine_phase_types.go`. +func (c *ClusterStatus) GetTypedPhase() ClusterPhase { + switch phase := ClusterPhase(c.Phase); phase { + case + ClusterPhasePending, + ClusterPhaseProvisioning, + ClusterPhaseProvisioned, + ClusterPhaseDeleting, + ClusterPhaseFailed: + return phase + default: + return ClusterPhaseUnknown + } +} + +// APIEndpoint represents a reachable Kubernetes API endpoint. +// +kubebuilder:validation:MinProperties=1 +type APIEndpoint struct { + // host is the hostname on which the API server is serving. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + Host string `json:"host,omitempty"` + + // port is the port on which the API server is serving. + // +optional + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + Port int32 `json:"port,omitempty"` +} + +// IsZero returns true if both host and port are zero values. +func (v APIEndpoint) IsZero() bool { + return v.Host == "" && v.Port == 0 +} + +// IsValid returns true if both host and port are non-zero values. +func (v APIEndpoint) IsValid() bool { + return v.Host != "" && v.Port != 0 +} + +// String returns a formatted version HOST:PORT of this APIEndpoint. +func (v APIEndpoint) String() string { + return net.JoinHostPort(v.Host, fmt.Sprintf("%d", v.Port)) +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=clusters,shortName=cl,scope=Namespaced,categories=cluster-api +// +kubebuilder:storageversion +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="ClusterClass",type="string",JSONPath=".spec.topology.classRef.name",description="ClusterClass of this Cluster, empty if the Cluster is not using a ClusterClass" +// +kubebuilder:printcolumn:name="Available",type="string",JSONPath=`.status.conditions[?(@.type=="Available")].status`,description="Cluster pass all availability checks" +// +kubebuilder:printcolumn:name="CP Desired",type=integer,JSONPath=".status.controlPlane.desiredReplicas",description="The desired number of control plane machines" +// +kubebuilder:printcolumn:name="CP Current",type="integer",JSONPath=".status.controlPlane.replicas",description="The number of control plane machines",priority=10 +// +kubebuilder:printcolumn:name="CP Ready",type="integer",JSONPath=".status.controlPlane.readyReplicas",description="The number of control plane machines with Ready condition true",priority=10 +// +kubebuilder:printcolumn:name="CP Available",type=integer,JSONPath=".status.controlPlane.availableReplicas",description="The number of control plane machines with Available condition true" +// +kubebuilder:printcolumn:name="CP Up-to-date",type=integer,JSONPath=".status.controlPlane.upToDateReplicas",description="The number of control plane machines with UpToDate condition true" +// +kubebuilder:printcolumn:name="W Desired",type=integer,JSONPath=".status.workers.desiredReplicas",description="The desired number of worker machines" +// +kubebuilder:printcolumn:name="W Current",type="integer",JSONPath=".status.workers.replicas",description="The number of worker machines",priority=10 +// +kubebuilder:printcolumn:name="W Ready",type="integer",JSONPath=".status.workers.readyReplicas",description="The number of worker machines with Ready condition true",priority=10 +// +kubebuilder:printcolumn:name="W Available",type=integer,JSONPath=".status.workers.availableReplicas",description="The number of worker machines with Available condition true" +// +kubebuilder:printcolumn:name="W Up-to-date",type=integer,JSONPath=".status.workers.upToDateReplicas",description="The number of worker machines with UpToDate condition true" +// +kubebuilder:printcolumn:name="Paused",type="string",JSONPath=`.status.conditions[?(@.type=="Paused")].status`,description="Reconciliation paused",priority=10 +// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase",description="Cluster status such as Pending/Provisioning/Provisioned/Deleting/Failed" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of Cluster" +// +kubebuilder:printcolumn:name="Version",type="string",JSONPath=".spec.topology.version",description="Kubernetes version associated with this Cluster" + +// Cluster is the Schema for the clusters API. +type Cluster struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is the desired state of Cluster. + // +required + Spec ClusterSpec `json:"spec,omitempty,omitzero"` + // status is the observed state of Cluster. + // +optional + Status ClusterStatus `json:"status,omitempty,omitzero"` +} + +// GetClassKey returns the namespaced name for the class associated with this object. +func (c *Cluster) GetClassKey() types.NamespacedName { + if !c.Spec.Topology.IsDefined() { + return types.NamespacedName{} + } + + namespace := cmp.Or(c.Spec.Topology.ClassRef.Namespace, c.Namespace) + return types.NamespacedName{Namespace: namespace, Name: c.Spec.Topology.ClassRef.Name} +} + +// GetV1Beta1Conditions returns the set of conditions for this object. +func (c *Cluster) GetV1Beta1Conditions() Conditions { + if c.Status.Deprecated == nil || c.Status.Deprecated.V1Beta1 == nil { + return nil + } + return c.Status.Deprecated.V1Beta1.Conditions +} + +// SetV1Beta1Conditions sets the conditions on this object. +func (c *Cluster) SetV1Beta1Conditions(conditions Conditions) { + if c.Status.Deprecated == nil { + c.Status.Deprecated = &ClusterDeprecatedStatus{} + } + if c.Status.Deprecated.V1Beta1 == nil { + c.Status.Deprecated.V1Beta1 = &ClusterV1Beta1DeprecatedStatus{} + } + c.Status.Deprecated.V1Beta1.Conditions = conditions +} + +// GetConditions returns the set of conditions for this object. +func (c *Cluster) GetConditions() []metav1.Condition { + return c.Status.Conditions +} + +// SetConditions sets conditions for an API object. +func (c *Cluster) SetConditions(conditions []metav1.Condition) { + c.Status.Conditions = conditions +} + +// +kubebuilder:object:root=true + +// ClusterList contains a list of Cluster. +type ClusterList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + // items is the list of Clusters. + Items []Cluster `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &Cluster{}, &ClusterList{}) +} + +// FailureDomain is the Schema for Cluster API failure domains. +// It allows controllers to understand how many failure domains a cluster can optionally span across. +type FailureDomain struct { + // name is the name of the failure domain. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Name string `json:"name,omitempty"` + + // controlPlane determines if this failure domain is suitable for use by control plane machines. + // +optional + ControlPlane *bool `json:"controlPlane,omitempty"` + + // attributes is a free form map of attributes an infrastructure provider might use or require. + // +optional + Attributes map[string]string `json:"attributes,omitempty"` +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/clusterclass_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/clusterclass_types.go new file mode 100644 index 000000000000..80d78f358553 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/clusterclass_types.go @@ -0,0 +1,1647 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "reflect" + + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/intstr" +) + +// ClusterClassKind represents the Kind of ClusterClass. +const ClusterClassKind = "ClusterClass" + +// ClusterClass VariablesReady condition and corresponding reasons. +const ( + // ClusterClassVariablesReadyCondition is true if the ClusterClass variables, including both inline and external + // variables, have been successfully reconciled and thus ready to be used to default and validate variables on Clusters using + // this ClusterClass. + ClusterClassVariablesReadyCondition = "VariablesReady" + + // ClusterClassVariablesReadyReason surfaces that the variables are ready. + ClusterClassVariablesReadyReason = "VariablesReady" + + // ClusterClassVariablesReadyVariableDiscoveryFailedReason surfaces that variable discovery failed. + ClusterClassVariablesReadyVariableDiscoveryFailedReason = "VariableDiscoveryFailed" +) + +// ClusterClass RefVersionsUpToDate condition and corresponding reasons. +const ( + // ClusterClassRefVersionsUpToDateCondition documents if the references in the ClusterClass are + // up-to-date (i.e. they are using the latest apiVersion of the current Cluster API contract from + // the corresponding CRD). + ClusterClassRefVersionsUpToDateCondition = "RefVersionsUpToDate" + + // ClusterClassRefVersionsUpToDateReason surfaces that the references in the ClusterClass are + // up-to-date (i.e. they are using the latest apiVersion of the current Cluster API contract from + // the corresponding CRD). + ClusterClassRefVersionsUpToDateReason = "RefVersionsUpToDate" + + // ClusterClassRefVersionsNotUpToDateReason surfaces that the references in the ClusterClass are not + // up-to-date (i.e. they are not using the latest apiVersion of the current Cluster API contract from + // the corresponding CRD). + ClusterClassRefVersionsNotUpToDateReason = "RefVersionsNotUpToDate" + + // ClusterClassRefVersionsUpToDateInternalErrorReason surfaces that an unexpected error occurred when validating + // if the references are up-to-date. + ClusterClassRefVersionsUpToDateInternalErrorReason = InternalErrorReason +) + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=clusterclasses,shortName=cc,scope=Namespaced,categories=cluster-api +// +kubebuilder:storageversion +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Paused",type="string",JSONPath=`.status.conditions[?(@.type=="Paused")].status`,description="Reconciliation paused",priority=10 +// +kubebuilder:printcolumn:name="Variables Ready",type="string",JSONPath=`.status.conditions[?(@.type=="VariablesReady")].status`,description="Variables ready" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of ClusterClass" + +// ClusterClass is a template which can be used to create managed topologies. +// NOTE: This CRD can only be used if the ClusterTopology feature gate is enabled. +type ClusterClass struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is the desired state of ClusterClass. + // +required + Spec ClusterClassSpec `json:"spec,omitempty,omitzero"` + // status is the observed state of ClusterClass. + // +optional + Status ClusterClassStatus `json:"status,omitempty,omitzero"` +} + +// ClusterClassSpec describes the desired state of the ClusterClass. +type ClusterClassSpec struct { + // availabilityGates specifies additional conditions to include when evaluating Cluster Available condition. + // + // NOTE: If a Cluster is using this ClusterClass, and this Cluster defines a custom list of availabilityGates, + // such list overrides availabilityGates defined in this field. + // +optional + // +listType=map + // +listMapKey=conditionType + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + AvailabilityGates []ClusterAvailabilityGate `json:"availabilityGates,omitempty"` + + // infrastructure is a reference to a local struct that holds the details + // for provisioning the infrastructure cluster for the Cluster. + // +required + Infrastructure InfrastructureClass `json:"infrastructure,omitempty,omitzero"` + + // controlPlane is a reference to a local struct that holds the details + // for provisioning the Control Plane for the Cluster. + // +required + ControlPlane ControlPlaneClass `json:"controlPlane,omitempty,omitzero"` + + // workers describes the worker nodes for the cluster. + // It is a collection of node types which can be used to create + // the worker nodes of the cluster. + // +optional + Workers WorkersClass `json:"workers,omitempty,omitzero"` + + // variables defines the variables which can be configured + // in the Cluster topology and are then used in patches. + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=1000 + Variables []ClusterClassVariable `json:"variables,omitempty"` + + // patches defines the patches which are applied to customize + // referenced templates of a ClusterClass. + // Note: Patches will be applied in the order of the array. + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=1000 + Patches []ClusterClassPatch `json:"patches,omitempty"` +} + +// InfrastructureClass defines the class for the infrastructure cluster. +type InfrastructureClass struct { + // templateRef contains the reference to a provider-specific infrastructure cluster template. + // +required + TemplateRef ClusterClassTemplateReference `json:"templateRef,omitempty,omitzero"` + + // naming allows changing the naming pattern used when creating the infrastructure cluster object. + // +optional + Naming InfrastructureClassNamingSpec `json:"naming,omitempty,omitzero"` +} + +// ControlPlaneClass defines the class for the control plane. +type ControlPlaneClass struct { + // metadata is the metadata applied to the ControlPlane and the Machines of the ControlPlane + // if the ControlPlaneTemplate referenced is machine based. If not, it is applied only to the + // ControlPlane. + // At runtime this metadata is merged with the corresponding metadata from the topology. + // + // This field is supported if and only if the control plane provider template + // referenced is Machine based. + // +optional + Metadata ObjectMeta `json:"metadata,omitempty,omitzero"` + + // templateRef contains the reference to a provider-specific control plane template. + // +required + TemplateRef ClusterClassTemplateReference `json:"templateRef,omitempty,omitzero"` + + // machineInfrastructure defines the metadata and infrastructure information + // for control plane machines. + // + // This field is supported if and only if the control plane provider template + // referenced above is Machine based and supports setting replicas. + // + // +optional + MachineInfrastructure ControlPlaneClassMachineInfrastructureTemplate `json:"machineInfrastructure,omitempty,omitzero"` + + // healthCheck defines a MachineHealthCheck for this ControlPlaneClass. + // This field is supported if and only if the ControlPlane provider template + // referenced above is Machine based and supports setting replicas. + // +optional + HealthCheck ControlPlaneClassHealthCheck `json:"healthCheck,omitempty,omitzero"` + + // naming allows changing the naming pattern used when creating the control plane provider object. + // +optional + Naming ControlPlaneClassNamingSpec `json:"naming,omitempty,omitzero"` + + // deletion contains configuration options for Machine deletion. + // +optional + Deletion ControlPlaneClassMachineDeletionSpec `json:"deletion,omitempty,omitzero"` + + // readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + // + // This field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready + // computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine. + // + // NOTE: If a Cluster defines a custom list of readinessGates for the control plane, + // such list overrides readinessGates defined in this field. + // NOTE: Specific control plane provider implementations might automatically extend the list of readinessGates; + // e.g. the kubeadm control provider adds ReadinessGates for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + // +optional + // +listType=map + // +listMapKey=conditionType + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + ReadinessGates []MachineReadinessGate `json:"readinessGates,omitempty"` +} + +// ControlPlaneClassHealthCheck defines a MachineHealthCheck for control plane machines. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneClassHealthCheck struct { + // checks are the checks that are used to evaluate if a Machine is healthy. + // + // Independent of this configuration the MachineHealthCheck controller will always + // flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + // Machines with deleted Nodes as unhealthy. + // + // Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + // is defaulted to 10 minutes and evaluated accordingly. + // + // +optional + Checks ControlPlaneClassHealthCheckChecks `json:"checks,omitempty,omitzero"` + + // remediation configures if and how remediations are triggered if a Machine is unhealthy. + // + // If remediation or remediation.triggerIf is not set, + // remediation will always be triggered for unhealthy Machines. + // + // If remediation or remediation.templateRef is not set, + // the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + // the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + // + // +optional + Remediation ControlPlaneClassHealthCheckRemediation `json:"remediation,omitempty,omitzero"` +} + +// IsDefined returns true if one of checks and remediation are not zero. +func (m *ControlPlaneClassHealthCheck) IsDefined() bool { + return !reflect.ValueOf(m.Checks).IsZero() || !reflect.ValueOf(m.Remediation).IsZero() +} + +// ControlPlaneClassHealthCheckChecks are the checks that are used to evaluate if a control plane Machine is healthy. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneClassHealthCheckChecks struct { + // nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + // to consider a Machine unhealthy if a corresponding Node isn't associated + // through a `Spec.ProviderID` field. + // + // The duration set in this field is compared to the greatest of: + // - Cluster's infrastructure ready condition timestamp (if and when available) + // - Control Plane's initialized condition timestamp (if and when available) + // - Machine's infrastructure ready condition timestamp (if and when available) + // - Machine's metadata creation timestamp + // + // Defaults to 10 minutes. + // If you wish to disable this feature, set the value explicitly to 0. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeStartupTimeoutSeconds *int32 `json:"nodeStartupTimeoutSeconds,omitempty"` + + // unhealthyNodeConditions contains a list of conditions that determine + // whether a node is considered unhealthy. The conditions are combined in a + // logical OR, i.e. if any of the conditions is met, the node is unhealthy. + // + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + UnhealthyNodeConditions []UnhealthyNodeCondition `json:"unhealthyNodeConditions,omitempty"` +} + +// ControlPlaneClassHealthCheckRemediation configures if and how remediations are triggered if a control plane Machine is unhealthy. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneClassHealthCheckRemediation struct { + // triggerIf configures if remediations are triggered. + // If this field is not set, remediations are always triggered. + // +optional + TriggerIf ControlPlaneClassHealthCheckRemediationTriggerIf `json:"triggerIf,omitempty,omitzero"` + + // templateRef is a reference to a remediation template + // provided by an infrastructure provider. + // + // This field is completely optional, when filled, the MachineHealthCheck controller + // creates a new object from the template referenced and hands off remediation of the machine to + // a controller that lives outside of Cluster API. + // +optional + TemplateRef MachineHealthCheckRemediationTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// ControlPlaneClassHealthCheckRemediationTriggerIf configures if remediations are triggered. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneClassHealthCheckRemediationTriggerIf struct { + // unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + // unhealthy Machines is less than or equal to the configured value. + // unhealthyInRange takes precedence if set. + // + // +optional + UnhealthyLessThanOrEqualTo *intstr.IntOrString `json:"unhealthyLessThanOrEqualTo,omitempty"` + + // unhealthyInRange specifies that remediations are only triggered if the number of + // unhealthy Machines is in the configured range. + // Takes precedence over unhealthyLessThanOrEqualTo. + // Eg. "[3-5]" - This means that remediation will be allowed only when: + // (a) there are at least 3 unhealthy Machines (and) + // (b) there are at most 5 unhealthy Machines + // + // +optional + // +kubebuilder:validation:Pattern=^\[[0-9]+-[0-9]+\]$ + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=32 + UnhealthyInRange string `json:"unhealthyInRange,omitempty"` +} + +// ControlPlaneClassMachineDeletionSpec contains configuration options for Machine deletion. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneClassMachineDeletionSpec struct { + // nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + // The default value is 0, meaning that the node can be drained without any time limitations. + // NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + // NOTE: This value can be overridden while defining a Cluster.Topology. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDrainTimeoutSeconds *int32 `json:"nodeDrainTimeoutSeconds,omitempty"` + + // nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + // to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + // NOTE: This value can be overridden while defining a Cluster.Topology. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeVolumeDetachTimeoutSeconds *int32 `json:"nodeVolumeDetachTimeoutSeconds,omitempty"` + + // nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + // hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + // Defaults to 10 seconds. + // NOTE: This value can be overridden while defining a Cluster.Topology. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDeletionTimeoutSeconds *int32 `json:"nodeDeletionTimeoutSeconds,omitempty"` +} + +// ControlPlaneClassNamingSpec defines the naming strategy for control plane objects. +// +kubebuilder:validation:MinProperties=1 +type ControlPlaneClassNamingSpec struct { + // template defines the template to use for generating the name of the ControlPlane object. + // If not defined, it will fallback to `{{ .cluster.name }}-{{ .random }}`. + // If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will + // get concatenated with a random suffix of length 5. + // The templating mechanism provides the following arguments: + // * `.cluster.name`: The name of the cluster object. + // * `.random`: A random alphanumeric string, without vowels, of length 5. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + Template string `json:"template,omitempty"` +} + +// InfrastructureClassNamingSpec defines the naming strategy for infrastructure objects. +// +kubebuilder:validation:MinProperties=1 +type InfrastructureClassNamingSpec struct { + // template defines the template to use for generating the name of the Infrastructure object. + // If not defined, it will fallback to `{{ .cluster.name }}-{{ .random }}`. + // If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will + // get concatenated with a random suffix of length 5. + // The templating mechanism provides the following arguments: + // * `.cluster.name`: The name of the cluster object. + // * `.random`: A random alphanumeric string, without vowels, of length 5. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + Template string `json:"template,omitempty"` +} + +// WorkersClass is a collection of deployment classes. +// +kubebuilder:validation:MinProperties=1 +type WorkersClass struct { + // machineDeployments is a list of machine deployment classes that can be used to create + // a set of worker nodes. + // +optional + // +listType=map + // +listMapKey=class + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + MachineDeployments []MachineDeploymentClass `json:"machineDeployments,omitempty"` + + // machinePools is a list of machine pool classes that can be used to create + // a set of worker nodes. + // +optional + // +listType=map + // +listMapKey=class + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + MachinePools []MachinePoolClass `json:"machinePools,omitempty"` +} + +// MachineDeploymentClass serves as a template to define a set of worker nodes of the cluster +// provisioned using the `ClusterClass`. +type MachineDeploymentClass struct { + // metadata is the metadata applied to the MachineDeployment and the machines of the MachineDeployment. + // At runtime this metadata is merged with the corresponding metadata from the topology. + // +optional + Metadata ObjectMeta `json:"metadata,omitempty,omitzero"` + + // class denotes a type of worker node present in the cluster, + // this name MUST be unique within a ClusterClass and can be referenced + // in the Cluster to create a managed MachineDeployment. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Class string `json:"class,omitempty"` + + // bootstrap contains the bootstrap template reference to be used + // for the creation of worker Machines. + // +required + Bootstrap MachineDeploymentClassBootstrapTemplate `json:"bootstrap,omitempty,omitzero"` + + // infrastructure contains the infrastructure template reference to be used + // for the creation of worker Machines. + // +required + Infrastructure MachineDeploymentClassInfrastructureTemplate `json:"infrastructure,omitempty,omitzero"` + + // healthCheck defines a MachineHealthCheck for this MachineDeploymentClass. + // +optional + HealthCheck MachineDeploymentClassHealthCheck `json:"healthCheck,omitempty,omitzero"` + + // failureDomain is the failure domain the machines will be created in. + // Must match the name of a FailureDomain from the Cluster status. + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + FailureDomain string `json:"failureDomain,omitempty"` + + // naming allows changing the naming pattern used when creating the MachineDeployment. + // +optional + Naming MachineDeploymentClassNamingSpec `json:"naming,omitempty,omitzero"` + + // deletion contains configuration options for Machine deletion. + // +optional + Deletion MachineDeploymentClassMachineDeletionSpec `json:"deletion,omitempty,omitzero"` + + // minReadySeconds is the minimum number of seconds for which a newly created machine should + // be ready. + // Defaults to 0 (machine will be considered available as soon as it + // is ready) + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + // +optional + // +kubebuilder:validation:Minimum=0 + MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` + + // readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + // + // This field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready + // computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine. + // + // NOTE: If a Cluster defines a custom list of readinessGates for a MachineDeployment using this MachineDeploymentClass, + // such list overrides readinessGates defined in this field. + // +optional + // +listType=map + // +listMapKey=conditionType + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + ReadinessGates []MachineReadinessGate `json:"readinessGates,omitempty"` + + // rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. + // It allows you to define the strategy used during rolling replacements. + // +optional + Rollout MachineDeploymentClassRolloutSpec `json:"rollout,omitempty,omitzero"` +} + +// MachineDeploymentClassHealthCheck defines a MachineHealthCheck for MachineDeployment machines. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassHealthCheck struct { + // checks are the checks that are used to evaluate if a Machine is healthy. + // + // Independent of this configuration the MachineHealthCheck controller will always + // flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + // Machines with deleted Nodes as unhealthy. + // + // Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + // is defaulted to 10 minutes and evaluated accordingly. + // + // +optional + Checks MachineDeploymentClassHealthCheckChecks `json:"checks,omitempty,omitzero"` + + // remediation configures if and how remediations are triggered if a Machine is unhealthy. + // + // If remediation or remediation.triggerIf is not set, + // remediation will always be triggered for unhealthy Machines. + // + // If remediation or remediation.templateRef is not set, + // the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + // the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + // + // +optional + Remediation MachineDeploymentClassHealthCheckRemediation `json:"remediation,omitempty,omitzero"` +} + +// IsDefined returns true if one of checks and remediation are not zero. +func (m *MachineDeploymentClassHealthCheck) IsDefined() bool { + return !reflect.ValueOf(m.Checks).IsZero() || !reflect.ValueOf(m.Remediation).IsZero() +} + +// MachineDeploymentClassHealthCheckChecks are the checks that are used to evaluate if a MachineDeployment Machine is healthy. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassHealthCheckChecks struct { + // nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + // to consider a Machine unhealthy if a corresponding Node isn't associated + // through a `Spec.ProviderID` field. + // + // The duration set in this field is compared to the greatest of: + // - Cluster's infrastructure ready condition timestamp (if and when available) + // - Control Plane's initialized condition timestamp (if and when available) + // - Machine's infrastructure ready condition timestamp (if and when available) + // - Machine's metadata creation timestamp + // + // Defaults to 10 minutes. + // If you wish to disable this feature, set the value explicitly to 0. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeStartupTimeoutSeconds *int32 `json:"nodeStartupTimeoutSeconds,omitempty"` + + // unhealthyNodeConditions contains a list of conditions that determine + // whether a node is considered unhealthy. The conditions are combined in a + // logical OR, i.e. if any of the conditions is met, the node is unhealthy. + // + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + UnhealthyNodeConditions []UnhealthyNodeCondition `json:"unhealthyNodeConditions,omitempty"` +} + +// MachineDeploymentClassHealthCheckRemediation configures if and how remediations are triggered if a MachineDeployment Machine is unhealthy. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassHealthCheckRemediation struct { + // maxInFlight determines how many in flight remediations should happen at the same time. + // + // Remediation only happens on the MachineSet with the most current revision, while + // older MachineSets (usually present during rollout operations) aren't allowed to remediate. + // + // Note: In general (independent of remediations), unhealthy machines are always + // prioritized during scale down operations over healthy ones. + // + // MaxInFlight can be set to a fixed number or a percentage. + // Example: when this is set to 20%, the MachineSet controller deletes at most 20% of + // the desired replicas. + // + // If not set, remediation is limited to all machines (bounded by replicas) + // under the active MachineSet's management. + // + // +optional + MaxInFlight *intstr.IntOrString `json:"maxInFlight,omitempty"` + + // triggerIf configures if remediations are triggered. + // If this field is not set, remediations are always triggered. + // +optional + TriggerIf MachineDeploymentClassHealthCheckRemediationTriggerIf `json:"triggerIf,omitempty,omitzero"` + + // templateRef is a reference to a remediation template + // provided by an infrastructure provider. + // + // This field is completely optional, when filled, the MachineHealthCheck controller + // creates a new object from the template referenced and hands off remediation of the machine to + // a controller that lives outside of Cluster API. + // +optional + TemplateRef MachineHealthCheckRemediationTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// MachineDeploymentClassHealthCheckRemediationTriggerIf configures if remediations are triggered. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassHealthCheckRemediationTriggerIf struct { + // unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + // unhealthy Machines is less than or equal to the configured value. + // unhealthyInRange takes precedence if set. + // + // +optional + UnhealthyLessThanOrEqualTo *intstr.IntOrString `json:"unhealthyLessThanOrEqualTo,omitempty"` + + // unhealthyInRange specifies that remediations are only triggered if the number of + // unhealthy Machines is in the configured range. + // Takes precedence over unhealthyLessThanOrEqualTo. + // Eg. "[3-5]" - This means that remediation will be allowed only when: + // (a) there are at least 3 unhealthy Machines (and) + // (b) there are at most 5 unhealthy Machines + // + // +optional + // +kubebuilder:validation:Pattern=^\[[0-9]+-[0-9]+\]$ + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=32 + UnhealthyInRange string `json:"unhealthyInRange,omitempty"` +} + +// MachineDeploymentClassMachineDeletionSpec contains configuration options for Machine deletion. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassMachineDeletionSpec struct { + // order defines the order in which Machines are deleted when downscaling. + // Defaults to "Random". Valid values are "Random, "Newest", "Oldest" + // +optional + Order MachineSetDeletionOrder `json:"order,omitempty"` + + // nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + // The default value is 0, meaning that the node can be drained without any time limitations. + // NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDrainTimeoutSeconds *int32 `json:"nodeDrainTimeoutSeconds,omitempty"` + + // nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + // to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeVolumeDetachTimeoutSeconds *int32 `json:"nodeVolumeDetachTimeoutSeconds,omitempty"` + + // nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + // hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + // Defaults to 10 seconds. + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDeletionTimeoutSeconds *int32 `json:"nodeDeletionTimeoutSeconds,omitempty"` +} + +// MachineDeploymentClassNamingSpec defines the naming strategy for machine deployment objects. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassNamingSpec struct { + // template defines the template to use for generating the name of the MachineDeployment object. + // If not defined, it will fallback to `{{ .cluster.name }}-{{ .machineDeployment.topologyName }}-{{ .random }}`. + // If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will + // get concatenated with a random suffix of length 5. + // The templating mechanism provides the following arguments: + // * `.cluster.name`: The name of the cluster object. + // * `.random`: A random alphanumeric string, without vowels, of length 5. + // * `.machineDeployment.topologyName`: The name of the MachineDeployment topology (Cluster.spec.topology.workers.machineDeployments[].name). + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + Template string `json:"template,omitempty"` +} + +// MachineDeploymentClassRolloutSpec defines the rollout behavior. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassRolloutSpec struct { + // strategy specifies how to roll out control plane Machines. + // +optional + Strategy MachineDeploymentClassRolloutStrategy `json:"strategy,omitempty,omitzero"` +} + +// MachineDeploymentClassRolloutStrategy describes how to replace existing machines +// with new ones. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassRolloutStrategy struct { + // type of rollout. Allowed values are RollingUpdate and OnDelete. + // Default is RollingUpdate. + // +required + Type MachineDeploymentRolloutStrategyType `json:"type,omitempty"` + + // rollingUpdate is the rolling update config params. Present only if + // type = RollingUpdate. + // +optional + RollingUpdate MachineDeploymentClassRolloutStrategyRollingUpdate `json:"rollingUpdate,omitempty,omitzero"` +} + +// MachineDeploymentClassRolloutStrategyRollingUpdate is used to control the desired behavior of rolling update. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentClassRolloutStrategyRollingUpdate struct { + // maxUnavailable is the maximum number of machines that can be unavailable during the update. + // Value can be an absolute number (ex: 5) or a percentage of desired + // machines (ex: 10%). + // Absolute number is calculated from percentage by rounding down. + // This can not be 0 if MaxSurge is 0. + // Defaults to 0. + // Example: when this is set to 30%, the old MachineSet can be scaled + // down to 70% of desired machines immediately when the rolling update + // starts. Once new machines are ready, old MachineSet can be scaled + // down further, followed by scaling up the new MachineSet, ensuring + // that the total number of machines available at all times + // during the update is at least 70% of desired machines. + // +optional + MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty"` + + // maxSurge is the maximum number of machines that can be scheduled above the + // desired number of machines. + // Value can be an absolute number (ex: 5) or a percentage of + // desired machines (ex: 10%). + // This can not be 0 if MaxUnavailable is 0. + // Absolute number is calculated from percentage by rounding up. + // Defaults to 1. + // Example: when this is set to 30%, the new MachineSet can be scaled + // up immediately when the rolling update starts, such that the total + // number of old and new machines do not exceed 130% of desired + // machines. Once old machines have been killed, new MachineSet can + // be scaled up further, ensuring that total number of machines running + // at any time during the update is at most 130% of desired machines. + // +optional + MaxSurge *intstr.IntOrString `json:"maxSurge,omitempty"` +} + +// MachinePoolClass serves as a template to define a pool of worker nodes of the cluster +// provisioned using `ClusterClass`. +type MachinePoolClass struct { + // metadata is the metadata applied to the MachinePool. + // At runtime this metadata is merged with the corresponding metadata from the topology. + // +optional + Metadata ObjectMeta `json:"metadata,omitempty,omitzero"` + + // class denotes a type of machine pool present in the cluster, + // this name MUST be unique within a ClusterClass and can be referenced + // in the Cluster to create a managed MachinePool. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Class string `json:"class,omitempty"` + + // bootstrap contains the bootstrap template reference to be used + // for the creation of the Machines in the MachinePool. + // +required + Bootstrap MachinePoolClassBootstrapTemplate `json:"bootstrap,omitempty,omitzero"` + + // infrastructure contains the infrastructure template reference to be used + // for the creation of the MachinePool. + // +required + Infrastructure MachinePoolClassInfrastructureTemplate `json:"infrastructure,omitempty,omitzero"` + + // failureDomains is the list of failure domains the MachinePool should be attached to. + // Must match a key in the FailureDomains map stored on the cluster object. + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=100 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=256 + FailureDomains []string `json:"failureDomains,omitempty"` + + // naming allows changing the naming pattern used when creating the MachinePool. + // +optional + Naming MachinePoolClassNamingSpec `json:"naming,omitempty,omitzero"` + + // deletion contains configuration options for Machine deletion. + // +optional + Deletion MachinePoolClassMachineDeletionSpec `json:"deletion,omitempty,omitzero"` + + // minReadySeconds is the minimum number of seconds for which a newly created machine pool should + // be ready. + // Defaults to 0 (machine will be considered available as soon as it + // is ready) + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + // +optional + // +kubebuilder:validation:Minimum=0 + MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` +} + +// MachinePoolClassMachineDeletionSpec contains configuration options for Machine deletion. +// +kubebuilder:validation:MinProperties=1 +type MachinePoolClassMachineDeletionSpec struct { + // nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + // The default value is 0, meaning that the node can be drained without any time limitations. + // NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDrainTimeoutSeconds *int32 `json:"nodeDrainTimeoutSeconds,omitempty"` + + // nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + // to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeVolumeDetachTimeoutSeconds *int32 `json:"nodeVolumeDetachTimeoutSeconds,omitempty"` + + // nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + // hosts after the Machine Pool is marked for deletion. A duration of 0 will retry deletion indefinitely. + // Defaults to 10 seconds. + // NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDeletionTimeoutSeconds *int32 `json:"nodeDeletionTimeoutSeconds,omitempty"` +} + +// MachinePoolClassNamingSpec defines the naming strategy for MachinePool objects. +// +kubebuilder:validation:MinProperties=1 +type MachinePoolClassNamingSpec struct { + // template defines the template to use for generating the name of the MachinePool object. + // If not defined, it will fallback to `{{ .cluster.name }}-{{ .machinePool.topologyName }}-{{ .random }}`. + // If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will + // get concatenated with a random suffix of length 5. + // The templating mechanism provides the following arguments: + // * `.cluster.name`: The name of the cluster object. + // * `.random`: A random alphanumeric string, without vowels, of length 5. + // * `.machinePool.topologyName`: The name of the MachinePool topology (Cluster.spec.topology.workers.machinePools[].name). + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + Template string `json:"template,omitempty"` +} + +// ClusterClassVariable defines a variable which can +// be configured in the Cluster topology and used in patches. +type ClusterClassVariable struct { + // name of the variable. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Name string `json:"name,omitempty"` + + // required specifies if the variable is required. + // Note: this applies to the variable as a whole and thus the + // top-level object defined in the schema. If nested fields are + // required, this will be specified inside the schema. + // +required + Required *bool `json:"required,omitempty"` + + // deprecatedV1Beta1Metadata is the metadata of a variable. + // It can be used to add additional data for higher level tools to + // a ClusterClassVariable. + // + // Deprecated: This field is deprecated and will be removed when support for v1beta1 will be dropped. Please use XMetadata in JSONSchemaProps instead. + // + // +optional + DeprecatedV1Beta1Metadata ClusterClassVariableMetadata `json:"deprecatedV1Beta1Metadata,omitempty,omitzero"` + + // schema defines the schema of the variable. + // +required + Schema VariableSchema `json:"schema,omitempty,omitzero"` +} + +// ClusterClassVariableMetadata is the metadata of a variable. +// It can be used to add additional data for higher level tools to +// a ClusterClassVariable. +// +// Deprecated: This struct is deprecated and is going to be removed in the next apiVersion. +// +kubebuilder:validation:MinProperties=1 +type ClusterClassVariableMetadata struct { + // labels is a map of string keys and values that can be used to organize and categorize + // (scope and select) variables. + // +optional + Labels map[string]string `json:"labels,omitempty"` + + // annotations is an unstructured key value map that can be used to store and + // retrieve arbitrary metadata. + // They are not queryable. + // +optional + Annotations map[string]string `json:"annotations,omitempty"` +} + +// VariableSchema defines the schema of a variable. +type VariableSchema struct { + // openAPIV3Schema defines the schema of a variable via OpenAPI v3 + // schema. The schema is a subset of the schema used in + // Kubernetes CRDs. + // +required + OpenAPIV3Schema JSONSchemaProps `json:"openAPIV3Schema,omitempty,omitzero"` +} + +// Adapted from https://github.com/kubernetes/apiextensions-apiserver/blob/v0.28.5/pkg/apis/apiextensions/v1/types_jsonschema.go#L40 + +// JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/). +// This struct has been initially copied from apiextensionsv1.JSONSchemaProps, but all fields +// which are not supported in CAPI have been removed. +// +kubebuilder:validation:MinProperties=1 +type JSONSchemaProps struct { + // description is a human-readable description of this variable. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=4096 + Description string `json:"description,omitempty"` + + // example is an example for this variable. + // +optional + Example *apiextensionsv1.JSON `json:"example,omitempty"` + + // type is the type of the variable. + // Valid values are: object, array, string, integer, number or boolean. + // +optional + // +kubebuilder:validation:Enum=object;array;string;integer;number;boolean + Type string `json:"type,omitempty"` + + // properties specifies fields of an object. + // NOTE: Can only be set if type is object. + // NOTE: Properties is mutually exclusive with AdditionalProperties. + // NOTE: This field uses PreserveUnknownFields and Schemaless, + // because recursive validation is not possible. + // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + Properties map[string]JSONSchemaProps `json:"properties,omitempty"` + + // additionalProperties specifies the schema of values in a map (keys are always strings). + // NOTE: Can only be set if type is object. + // NOTE: AdditionalProperties is mutually exclusive with Properties. + // NOTE: This field uses PreserveUnknownFields and Schemaless, + // because recursive validation is not possible. + // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + AdditionalProperties *JSONSchemaProps `json:"additionalProperties,omitempty"` + + // maxProperties is the maximum amount of entries in a map or properties in an object. + // NOTE: Can only be set if type is object. + // +optional + MaxProperties *int64 `json:"maxProperties,omitempty"` + + // minProperties is the minimum amount of entries in a map or properties in an object. + // NOTE: Can only be set if type is object. + // +optional + MinProperties *int64 `json:"minProperties,omitempty"` + + // required specifies which fields of an object are required. + // NOTE: Can only be set if type is object. + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=1000 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=256 + Required []string `json:"required,omitempty"` + + // items specifies fields of an array. + // NOTE: Can only be set if type is array. + // NOTE: This field uses PreserveUnknownFields and Schemaless, + // because recursive validation is not possible. + // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + Items *JSONSchemaProps `json:"items,omitempty"` + + // maxItems is the max length of an array variable. + // NOTE: Can only be set if type is array. + // +optional + MaxItems *int64 `json:"maxItems,omitempty"` + + // minItems is the min length of an array variable. + // NOTE: Can only be set if type is array. + // +optional + MinItems *int64 `json:"minItems,omitempty"` + + // uniqueItems specifies if items in an array must be unique. + // NOTE: Can only be set if type is array. + // +optional + UniqueItems *bool `json:"uniqueItems,omitempty"` + + // format is an OpenAPI v3 format string. Unknown formats are ignored. + // For a list of supported formats please see: (of the k8s.io/apiextensions-apiserver version we're currently using) + // https://github.com/kubernetes/apiextensions-apiserver/blob/master/pkg/apiserver/validation/formats.go + // NOTE: Can only be set if type is string. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=32 + Format string `json:"format,omitempty"` + + // maxLength is the max length of a string variable. + // NOTE: Can only be set if type is string. + // +optional + MaxLength *int64 `json:"maxLength,omitempty"` + + // minLength is the min length of a string variable. + // NOTE: Can only be set if type is string. + // +optional + MinLength *int64 `json:"minLength,omitempty"` + + // pattern is the regex which a string variable must match. + // NOTE: Can only be set if type is string. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + Pattern string `json:"pattern,omitempty"` + + // maximum is the maximum of an integer or number variable. + // If ExclusiveMaximum is false, the variable is valid if it is lower than, or equal to, the value of Maximum. + // If ExclusiveMaximum is true, the variable is valid if it is strictly lower than the value of Maximum. + // NOTE: Can only be set if type is integer or number. + // +optional + Maximum *int64 `json:"maximum,omitempty"` + + // exclusiveMaximum specifies if the Maximum is exclusive. + // NOTE: Can only be set if type is integer or number. + // +optional + ExclusiveMaximum *bool `json:"exclusiveMaximum,omitempty"` + + // minimum is the minimum of an integer or number variable. + // If ExclusiveMinimum is false, the variable is valid if it is greater than, or equal to, the value of Minimum. + // If ExclusiveMinimum is true, the variable is valid if it is strictly greater than the value of Minimum. + // NOTE: Can only be set if type is integer or number. + // +optional + Minimum *int64 `json:"minimum,omitempty"` + + // exclusiveMinimum specifies if the Minimum is exclusive. + // NOTE: Can only be set if type is integer or number. + // +optional + ExclusiveMinimum *bool `json:"exclusiveMinimum,omitempty"` + + // x-kubernetes-preserve-unknown-fields allows setting fields in a variable object + // which are not defined in the variable schema. This affects fields recursively, + // except if nested properties or additionalProperties are specified in the schema. + // +optional + XPreserveUnknownFields *bool `json:"x-kubernetes-preserve-unknown-fields,omitempty"` + + // enum is the list of valid values of the variable. + // NOTE: Can be set for all types. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=100 + Enum []apiextensionsv1.JSON `json:"enum,omitempty"` + + // default is the default value of the variable. + // NOTE: Can be set for all types. + // +optional + Default *apiextensionsv1.JSON `json:"default,omitempty"` + + // x-kubernetes-validations describes a list of validation rules written in the CEL expression language. + // +optional + // +listType=map + // +listMapKey=rule + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + XValidations []ValidationRule `json:"x-kubernetes-validations,omitempty"` + + // x-metadata is the metadata of a variable or a nested field within a variable. + // It can be used to add additional data for higher level tools. + // +optional + XMetadata VariableSchemaMetadata `json:"x-metadata,omitempty,omitzero"` + + // x-kubernetes-int-or-string specifies that this value is + // either an integer or a string. If this is true, an empty + // type is allowed and type as child of anyOf is permitted + // if following one of the following patterns: + // + // 1) anyOf: + // - type: integer + // - type: string + // 2) allOf: + // - anyOf: + // - type: integer + // - type: string + // - ... zero or more + // +optional + XIntOrString *bool `json:"x-kubernetes-int-or-string,omitempty"` + + // allOf specifies that the variable must validate against all of the subschemas in the array. + // NOTE: This field uses PreserveUnknownFields and Schemaless, + // because recursive validation is not possible. + // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + AllOf []JSONSchemaProps `json:"allOf,omitempty"` + + // oneOf specifies that the variable must validate against exactly one of the subschemas in the array. + // NOTE: This field uses PreserveUnknownFields and Schemaless, + // because recursive validation is not possible. + // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + OneOf []JSONSchemaProps `json:"oneOf,omitempty"` + + // anyOf specifies that the variable must validate against one or more of the subschemas in the array. + // NOTE: This field uses PreserveUnknownFields and Schemaless, + // because recursive validation is not possible. + // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + AnyOf []JSONSchemaProps `json:"anyOf,omitempty"` + + // not specifies that the variable must not validate against the subschema. + // NOTE: This field uses PreserveUnknownFields and Schemaless, + // because recursive validation is not possible. + // +optional + // +kubebuilder:pruning:PreserveUnknownFields + // +kubebuilder:validation:Schemaless + Not *JSONSchemaProps `json:"not,omitempty"` +} + +// VariableSchemaMetadata is the metadata of a variable or a nested field within a variable. +// It can be used to add additional data for higher level tools. +// +kubebuilder:validation:MinProperties=1 +type VariableSchemaMetadata struct { + // labels is a map of string keys and values that can be used to organize and categorize + // (scope and select) variables. + // +optional + Labels map[string]string `json:"labels,omitempty"` + + // annotations is an unstructured key value map that can be used to store and + // retrieve arbitrary metadata. + // They are not queryable. + // +optional + Annotations map[string]string `json:"annotations,omitempty"` +} + +// ValidationRule describes a validation rule written in the CEL expression language. +type ValidationRule struct { + // rule represents the expression which will be evaluated by CEL. + // ref: https://github.com/google/cel-spec + // The Rule is scoped to the location of the x-kubernetes-validations extension in the schema. + // The `self` variable in the CEL expression is bound to the scoped value. + // If the Rule is scoped to an object with properties, the accessible properties of the object are field selectable + // via `self.field` and field presence can be checked via `has(self.field)`. + // If the Rule is scoped to an object with additionalProperties (i.e. a map) the value of the map + // are accessible via `self[mapKey]`, map containment can be checked via `mapKey in self` and all entries of the map + // are accessible via CEL macros and functions such as `self.all(...)`. + // If the Rule is scoped to an array, the elements of the array are accessible via `self[i]` and also by macros and + // functions. + // If the Rule is scoped to a scalar, `self` is bound to the scalar value. + // Examples: + // - Rule scoped to a map of objects: {"rule": "self.components['Widget'].priority < 10"} + // - Rule scoped to a list of integers: {"rule": "self.values.all(value, value >= 0 && value < 100)"} + // - Rule scoped to a string value: {"rule": "self.startsWith('kube')"} + // + // Unknown data preserved in custom resources via x-kubernetes-preserve-unknown-fields is not accessible in CEL + // expressions. This includes: + // - Unknown field values that are preserved by object schemas with x-kubernetes-preserve-unknown-fields. + // - Object properties where the property schema is of an "unknown type". An "unknown type" is recursively defined as: + // - A schema with no type and x-kubernetes-preserve-unknown-fields set to true + // - An array where the items schema is of an "unknown type" + // - An object where the additionalProperties schema is of an "unknown type" + // + // Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. + // Accessible property names are escaped according to the following rules when accessed in the expression: + // - '__' escapes to '__underscores__' + // - '.' escapes to '__dot__' + // - '-' escapes to '__dash__' + // - '/' escapes to '__slash__' + // - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are: + // "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if", + // "import", "let", "loop", "package", "namespace", "return". + // Examples: + // - Rule accessing a property named "namespace": {"rule": "self.__namespace__ > 0"} + // - Rule accessing a property named "x-prop": {"rule": "self.x__dash__prop > 0"} + // - Rule accessing a property named "redact__d": {"rule": "self.redact__underscores__d > 0"} + // + // + // If `rule` makes use of the `oldSelf` variable it is implicitly a + // `transition rule`. + // + // By default, the `oldSelf` variable is the same type as `self`. + // + // Transition rules by default are applied only on UPDATE requests and are + // skipped if an old value could not be found. + // + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=4096 + Rule string `json:"rule,omitempty"` + // message represents the message displayed when validation fails. The message is required if the Rule contains + // line breaks. The message must not contain line breaks. + // If unset, the message is "failed rule: {Rule}". + // e.g. "must be a URL with the host matching spec.host" + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + Message string `json:"message,omitempty"` + // messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. + // Since messageExpression is used as a failure message, it must evaluate to a string. + // If both message and messageExpression are present on a rule, then messageExpression will be used if validation + // fails. If messageExpression results in a runtime error, the validation failure message is produced + // as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string + // that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset. + // messageExpression has access to all the same variables as the rule; the only difference is the return type. + // Example: + // "x must be less than max ("+string(self.max)+")" + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + MessageExpression string `json:"messageExpression,omitempty"` + // reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule. + // The currently supported reasons are: "FieldValueInvalid", "FieldValueForbidden", "FieldValueRequired", "FieldValueDuplicate". + // If not set, default to use "FieldValueInvalid". + // All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid. + // +optional + // +kubebuilder:validation:Enum=FieldValueInvalid;FieldValueForbidden;FieldValueRequired;FieldValueDuplicate + // +kubebuilder:default=FieldValueInvalid + // +default=ref(sigs.k8s.io/cluster-api/api/core/v1beta2.FieldValueInvalid) + Reason FieldValueErrorReason `json:"reason,omitempty"` + // fieldPath represents the field path returned when the validation fails. + // It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. + // e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo` + // If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList` + // It does not support list numeric index. + // It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info. + // Numeric index of array is not supported. + // For field name which contains special characters, use `['specialName']` to refer the field name. + // e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']` + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + FieldPath string `json:"fieldPath,omitempty"` +} + +// FieldValueErrorReason is a machine-readable value providing more detail about why a field failed the validation. +type FieldValueErrorReason string + +const ( + // FieldValueRequired is used to report required values that are not + // provided (e.g. empty strings, null values, or empty arrays). + FieldValueRequired FieldValueErrorReason = "FieldValueRequired" + // FieldValueDuplicate is used to report collisions of values that must be + // unique (e.g. unique IDs). + FieldValueDuplicate FieldValueErrorReason = "FieldValueDuplicate" + // FieldValueInvalid is used to report malformed values (e.g. failed regex + // match, too long, out of bounds). + FieldValueInvalid FieldValueErrorReason = "FieldValueInvalid" + // FieldValueForbidden is used to report valid (as per formatting rules) + // values which would be accepted under some conditions, but which are not + // permitted by the current conditions (such as security policy). + FieldValueForbidden FieldValueErrorReason = "FieldValueForbidden" +) + +// ClusterClassPatch defines a patch which is applied to customize the referenced templates. +type ClusterClassPatch struct { + // name of the patch. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Name string `json:"name,omitempty"` + + // description is a human-readable description of this patch. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=1024 + Description string `json:"description,omitempty"` + + // enabledIf is a Go template to be used to calculate if a patch should be enabled. + // It can reference variables defined in .spec.variables and builtin variables. + // The patch will be enabled if the template evaluates to `true`, otherwise it will + // be disabled. + // If EnabledIf is not set, the patch will be enabled per default. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + EnabledIf string `json:"enabledIf,omitempty"` + + // definitions define inline patches. + // Note: Patches will be applied in the order of the array. + // Note: Exactly one of Definitions or External must be set. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=100 + Definitions []PatchDefinition `json:"definitions,omitempty"` + + // external defines an external patch. + // Note: Exactly one of Definitions or External must be set. + // +optional + External *ExternalPatchDefinition `json:"external,omitempty"` +} + +// PatchDefinition defines a patch which is applied to customize the referenced templates. +type PatchDefinition struct { + // selector defines on which templates the patch should be applied. + // +required + Selector PatchSelector `json:"selector,omitempty,omitzero"` + + // jsonPatches defines the patches which should be applied on the templates + // matching the selector. + // Note: Patches will be applied in the order of the array. + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + // +required + // +listType=atomic + JSONPatches []JSONPatch `json:"jsonPatches,omitempty"` +} + +// PatchSelector defines on which templates the patch should be applied. +// Note: Matching on APIVersion and Kind is mandatory, to enforce that the patches are +// written for the correct version. The version of the references in the ClusterClass may +// be automatically updated during reconciliation if there is a newer version for the same contract. +// Note: The results of selection based on the individual fields are ANDed. +type PatchSelector struct { + // apiVersion filters templates by apiVersion. + // apiVersion must be fully qualified domain name followed by / and a version. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=317 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$` + APIVersion string `json:"apiVersion,omitempty"` + + // kind filters templates by kind. + // kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$` + Kind string `json:"kind,omitempty"` + + // matchResources selects templates based on where they are referenced. + // +required + MatchResources PatchSelectorMatch `json:"matchResources,omitempty,omitzero"` +} + +// PatchSelectorMatch selects templates based on where they are referenced. +// Note: The selector must match at least one template. +// Note: The results of selection based on the individual fields are ORed. +// +kubebuilder:validation:MinProperties=1 +type PatchSelectorMatch struct { + // controlPlane selects templates referenced in .spec.ControlPlane. + // Note: this will match the controlPlane and also the controlPlane + // machineInfrastructure (depending on the kind and apiVersion). + // +optional + ControlPlane *bool `json:"controlPlane,omitempty"` + + // infrastructureCluster selects templates referenced in .spec.infrastructure. + // +optional + InfrastructureCluster *bool `json:"infrastructureCluster,omitempty"` + + // machineDeploymentClass selects templates referenced in specific MachineDeploymentClasses in + // .spec.workers.machineDeployments. + // +optional + MachineDeploymentClass *PatchSelectorMatchMachineDeploymentClass `json:"machineDeploymentClass,omitempty"` + + // machinePoolClass selects templates referenced in specific MachinePoolClasses in + // .spec.workers.machinePools. + // +optional + MachinePoolClass *PatchSelectorMatchMachinePoolClass `json:"machinePoolClass,omitempty"` +} + +// PatchSelectorMatchMachineDeploymentClass selects templates referenced +// in specific MachineDeploymentClasses in .spec.workers.machineDeployments. +type PatchSelectorMatchMachineDeploymentClass struct { + // names selects templates by class names. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=100 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=256 + Names []string `json:"names,omitempty"` +} + +// PatchSelectorMatchMachinePoolClass selects templates referenced +// in specific MachinePoolClasses in .spec.workers.machinePools. +type PatchSelectorMatchMachinePoolClass struct { + // names selects templates by class names. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=100 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=256 + Names []string `json:"names,omitempty"` +} + +// JSONPatch defines a JSON patch. +type JSONPatch struct { + // op defines the operation of the patch. + // Note: Only `add`, `replace` and `remove` are supported. + // +required + // +kubebuilder:validation:Enum=add;replace;remove + Op string `json:"op,omitempty"` + + // path defines the path of the patch. + // Note: Only the spec of a template can be patched, thus the path has to start with /spec/. + // Note: For now the only allowed array modifications are `append` and `prepend`, i.e.: + // * for op: `add`: only index 0 (prepend) and - (append) are allowed + // * for op: `replace` or `remove`: no indexes are allowed + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + Path string `json:"path,omitempty"` + + // value defines the value of the patch. + // Note: Either Value or ValueFrom is required for add and replace + // operations. Only one of them is allowed to be set at the same time. + // Note: We have to use apiextensionsv1.JSON instead of our JSON type, + // because controller-tools has a hard-coded schema for apiextensionsv1.JSON + // which cannot be produced by another type (unset type field). + // Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111 + // +optional + Value *apiextensionsv1.JSON `json:"value,omitempty"` + + // valueFrom defines the value of the patch. + // Note: Either Value or ValueFrom is required for add and replace + // operations. Only one of them is allowed to be set at the same time. + // +optional + ValueFrom *JSONPatchValue `json:"valueFrom,omitempty"` +} + +// JSONPatchValue defines the value of a patch. +// Note: Only one of the fields is allowed to be set at the same time. +type JSONPatchValue struct { + // variable is the variable to be used as value. + // Variable can be one of the variables defined in .spec.variables or a builtin variable. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Variable string `json:"variable,omitempty"` + + // template is the Go template to be used to calculate the value. + // A template can reference variables defined in .spec.variables and builtin variables. + // Note: The template must evaluate to a valid YAML or JSON value. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=10240 + Template string `json:"template,omitempty"` +} + +// ExternalPatchDefinition defines an external patch. +// Note: At least one of GeneratePatchesExtension or ValidateTopologyExtension must be set. +type ExternalPatchDefinition struct { + // generatePatchesExtension references an extension which is called to generate patches. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + GeneratePatchesExtension string `json:"generatePatchesExtension,omitempty"` + + // validateTopologyExtension references an extension which is called to validate the topology. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + ValidateTopologyExtension string `json:"validateTopologyExtension,omitempty"` + + // discoverVariablesExtension references an extension which is called to discover variables. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + DiscoverVariablesExtension string `json:"discoverVariablesExtension,omitempty"` + + // settings defines key value pairs to be passed to the extensions. + // Values defined here take precedence over the values defined in the + // corresponding ExtensionConfig. + // +optional + Settings map[string]string `json:"settings,omitempty"` +} + +// ControlPlaneClassMachineInfrastructureTemplate defines the template for a MachineInfrastructure of a ControlPlane. +type ControlPlaneClassMachineInfrastructureTemplate struct { + // templateRef is a required reference to the template for a MachineInfrastructure of a ControlPlane. + // +required + TemplateRef ClusterClassTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// MachineDeploymentClassBootstrapTemplate defines the BootstrapTemplate for a MachineDeployment. +type MachineDeploymentClassBootstrapTemplate struct { + // templateRef is a required reference to the BootstrapTemplate for a MachineDeployment. + // +required + TemplateRef ClusterClassTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// MachineDeploymentClassInfrastructureTemplate defines the InfrastructureTemplate for a MachineDeployment. +type MachineDeploymentClassInfrastructureTemplate struct { + // templateRef is a required reference to the InfrastructureTemplate for a MachineDeployment. + // +required + TemplateRef ClusterClassTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// MachinePoolClassBootstrapTemplate defines the BootstrapTemplate for a MachinePool. +type MachinePoolClassBootstrapTemplate struct { + // templateRef is a required reference to the BootstrapTemplate for a MachinePool. + // +required + TemplateRef ClusterClassTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// MachinePoolClassInfrastructureTemplate defines the InfrastructureTemplate for a MachinePool. +type MachinePoolClassInfrastructureTemplate struct { + // templateRef is a required reference to the InfrastructureTemplate for a MachinePool. + // +required + TemplateRef ClusterClassTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// ClusterClassTemplateReference is a reference to a ClusterClass template. +type ClusterClassTemplateReference struct { + // kind of the template. + // kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$` + Kind string `json:"kind,omitempty"` + + // name of the template. + // name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` + + // apiVersion of the template. + // apiVersion must be fully qualified domain name followed by / and a version. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=317 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$` + APIVersion string `json:"apiVersion,omitempty"` +} + +// IsDefined returns true if the ClusterClassTemplateReference is set. +func (r *ClusterClassTemplateReference) IsDefined() bool { + if r == nil { + return false + } + return r.Kind != "" || r.Name != "" || r.APIVersion != "" +} + +// ToObjectReference returns an object reference for the ClusterClassTemplateReference in a given namespace. +func (r *ClusterClassTemplateReference) ToObjectReference(namespace string) *corev1.ObjectReference { + if r == nil || !r.IsDefined() { + return nil + } + return &corev1.ObjectReference{ + APIVersion: r.APIVersion, + Kind: r.Kind, + Namespace: namespace, + Name: r.Name, + } +} + +// GroupVersionKind gets the GroupVersionKind for a ClusterClassTemplateReference. +func (r *ClusterClassTemplateReference) GroupVersionKind() schema.GroupVersionKind { + return schema.FromAPIVersionAndKind(r.APIVersion, r.Kind) +} + +// ClusterClassStatus defines the observed state of the ClusterClass. +// +kubebuilder:validation:MinProperties=1 +type ClusterClassStatus struct { + // conditions represents the observations of a ClusterClass's current state. + // Known condition types are VariablesReady, RefVersionsUpToDate, Paused. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // variables is a list of ClusterClassStatusVariable that are defined for the ClusterClass. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=1000 + Variables []ClusterClassStatusVariable `json:"variables,omitempty"` + + // observedGeneration is the latest generation observed by the controller. + // +optional + // +kubebuilder:validation:Minimum=1 + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. + // +optional + Deprecated *ClusterClassDeprecatedStatus `json:"deprecated,omitempty"` +} + +// ClusterClassDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type ClusterClassDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + // +optional + V1Beta1 *ClusterClassV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` +} + +// ClusterClassV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type ClusterClassV1Beta1DeprecatedStatus struct { + // conditions defines current observed state of the ClusterClass. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + Conditions Conditions `json:"conditions,omitempty"` +} + +// ClusterClassStatusVariable defines a variable which appears in the status of a ClusterClass. +type ClusterClassStatusVariable struct { + // name is the name of the variable. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Name string `json:"name,omitempty"` + + // definitionsConflict specifies whether or not there are conflicting definitions for a single variable name. + // +optional + DefinitionsConflict *bool `json:"definitionsConflict,omitempty"` + + // definitions is a list of definitions for a variable. + // +required + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + Definitions []ClusterClassStatusVariableDefinition `json:"definitions,omitempty"` +} + +// ClusterClassStatusVariableDefinition defines a variable which appears in the status of a ClusterClass. +type ClusterClassStatusVariableDefinition struct { + // from specifies the origin of the variable definition. + // This will be `inline` for variables defined in the ClusterClass or the name of a patch defined in the ClusterClass + // for variables discovered from a DiscoverVariables runtime extensions. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + From string `json:"from,omitempty"` + + // required specifies if the variable is required. + // Note: this applies to the variable as a whole and thus the + // top-level object defined in the schema. If nested fields are + // required, this will be specified inside the schema. + // +required + Required *bool `json:"required,omitempty"` + + // deprecatedV1Beta1Metadata is the metadata of a variable. + // It can be used to add additional data for higher level tools to + // a ClusterClassVariable. + // + // Deprecated: This field is deprecated and will be removed when support for v1beta1 will be dropped. Please use XMetadata in JSONSchemaProps instead. + // + // +optional + DeprecatedV1Beta1Metadata ClusterClassVariableMetadata `json:"deprecatedV1Beta1Metadata,omitempty,omitzero"` + + // schema defines the schema of the variable. + // +required + Schema VariableSchema `json:"schema,omitempty,omitzero"` +} + +// GetV1Beta1Conditions returns the set of conditions for this object. +func (c *ClusterClass) GetV1Beta1Conditions() Conditions { + if c.Status.Deprecated == nil || c.Status.Deprecated.V1Beta1 == nil { + return nil + } + return c.Status.Deprecated.V1Beta1.Conditions +} + +// SetV1Beta1Conditions sets the conditions on this object. +func (c *ClusterClass) SetV1Beta1Conditions(conditions Conditions) { + if c.Status.Deprecated == nil { + c.Status.Deprecated = &ClusterClassDeprecatedStatus{} + } + if c.Status.Deprecated.V1Beta1 == nil { + c.Status.Deprecated.V1Beta1 = &ClusterClassV1Beta1DeprecatedStatus{} + } + c.Status.Deprecated.V1Beta1.Conditions = conditions +} + +// GetConditions returns the set of conditions for this object. +func (c *ClusterClass) GetConditions() []metav1.Condition { + return c.Status.Conditions +} + +// SetConditions sets conditions for an API object. +func (c *ClusterClass) SetConditions(conditions []metav1.Condition) { + c.Status.Conditions = conditions +} + +// +kubebuilder:object:root=true + +// ClusterClassList contains a list of Cluster. +type ClusterClassList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + // items is the list of ClusterClasses. + Items []ClusterClass `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &ClusterClass{}, &ClusterClassList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/common_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/common_types.go new file mode 100644 index 000000000000..9e409f6928d5 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/common_types.go @@ -0,0 +1,403 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + apivalidation "k8s.io/apimachinery/pkg/api/validation" + metav1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +const ( + // ClusterNameLabel is the label set on machines linked to a cluster and + // external objects(bootstrap and infrastructure providers). + ClusterNameLabel = "cluster.x-k8s.io/cluster-name" + + // ClusterTopologyOwnedLabel is the label set on all the object which are managed as part of a ClusterTopology. + ClusterTopologyOwnedLabel = "topology.cluster.x-k8s.io/owned" + + // ClusterTopologyMachineDeploymentNameLabel is the label set on the generated MachineDeployment objects + // to track the name of the MachineDeployment topology it represents. + ClusterTopologyMachineDeploymentNameLabel = "topology.cluster.x-k8s.io/deployment-name" + + // ClusterTopologyHoldUpgradeSequenceAnnotation can be used to hold the entire MachineDeployment upgrade sequence. + // If the annotation is set on a MachineDeployment topology in Cluster.spec.topology.workers, the Kubernetes upgrade + // for this MachineDeployment topology and all subsequent ones is deferred. + // Examples: + // - If you want to pause upgrade after CP upgrade, this annotation should be applied to the first MachineDeployment + // in the list of MachineDeployments in Cluster.spec.topology. The upgrade will not be completed until the annotation + // is removed and all MachineDeployments are upgraded. + // - If you want to pause upgrade after the 50th MachineDeployment, this annotation should be applied to the 51st + // MachineDeployment in the list. + ClusterTopologyHoldUpgradeSequenceAnnotation = "topology.cluster.x-k8s.io/hold-upgrade-sequence" + + // ClusterTopologyDeferUpgradeAnnotation can be used to defer the Kubernetes upgrade of a single MachineDeployment topology. + // If the annotation is set on a MachineDeployment topology in Cluster.spec.topology.workers, the Kubernetes upgrade + // for this MachineDeployment topology is deferred. It doesn't affect other MachineDeployment topologies. + // Example: + // - If you want to defer the upgrades of the 3rd and 5th MachineDeployments of the list, set the annotation on them. + // The upgrade process will upgrade MachineDeployment in position 1,2, (skip 3), 4, (skip 5), 6 etc. The upgrade + // will not be completed until the annotation is removed and all MachineDeployments are upgraded. + ClusterTopologyDeferUpgradeAnnotation = "topology.cluster.x-k8s.io/defer-upgrade" + + // ClusterTopologyUpgradeConcurrencyAnnotation can be set as top-level annotation on the Cluster object of + // a classy Cluster to define the maximum concurrency while upgrading MachineDeployments. + ClusterTopologyUpgradeConcurrencyAnnotation = "topology.cluster.x-k8s.io/upgrade-concurrency" + + // ClusterTopologyMachinePoolNameLabel is the label set on the generated MachinePool objects + // to track the name of the MachinePool topology it represents. + ClusterTopologyMachinePoolNameLabel = "topology.cluster.x-k8s.io/pool-name" + + // ClusterTopologyUnsafeUpdateClassNameAnnotation can be used to disable the webhook check on + // update that disallows a pre-existing Cluster to be populated with Topology information and Class. + ClusterTopologyUnsafeUpdateClassNameAnnotation = "unsafe.topology.cluster.x-k8s.io/disable-update-class-name-check" + + // ClusterTopologyUnsafeUpdateVersionAnnotation can be used to disable the webhook checks on + // update that disallows updating the .topology.spec.version on certain conditions. + ClusterTopologyUnsafeUpdateVersionAnnotation = "unsafe.topology.cluster.x-k8s.io/disable-update-version-check" + + // ProviderNameLabel is the label set on components in the provider manifest. + // This label allows to easily identify all the components belonging to a provider; the clusterctl + // tool uses this label for implementing provider's lifecycle operations. + ProviderNameLabel = "cluster.x-k8s.io/provider" + + // ClusterNameAnnotation is the annotation set on nodes identifying the name of the cluster the node belongs to. + ClusterNameAnnotation = "cluster.x-k8s.io/cluster-name" + + // ClusterNamespaceAnnotation is the annotation set on nodes identifying the namespace of the cluster the node belongs to. + ClusterNamespaceAnnotation = "cluster.x-k8s.io/cluster-namespace" + + // MachineAnnotation is the annotation set on nodes identifying the machine the node belongs to. + MachineAnnotation = "cluster.x-k8s.io/machine" + + // OwnerKindAnnotation is the annotation set on nodes identifying the owner kind. + OwnerKindAnnotation = "cluster.x-k8s.io/owner-kind" + + // LabelsFromMachineAnnotation is the annotation set on nodes to track the labels originated from machines. + LabelsFromMachineAnnotation = "cluster.x-k8s.io/labels-from-machine" + + // AnnotationsFromMachineAnnotation is the annotation set on nodes to track the annotations that originated from machines. + AnnotationsFromMachineAnnotation = "cluster.x-k8s.io/annotations-from-machine" + + // OwnerNameAnnotation is the annotation set on nodes identifying the owner name. + OwnerNameAnnotation = "cluster.x-k8s.io/owner-name" + + // PausedAnnotation is an annotation that can be applied to any Cluster API + // object to prevent a controller from processing a resource. + // + // Controllers working with Cluster API objects must check the existence of this annotation + // on the reconciled object. + PausedAnnotation = "cluster.x-k8s.io/paused" + + // DisableMachineCreateAnnotation is an annotation that can be used to signal a MachineSet to stop creating new machines. + // It is utilized in the OnDelete rollout strategy to allow the MachineDeployment controller to scale down + // older MachineSets when Machines are deleted and add the new replicas to the latest MachineSet. + DisableMachineCreateAnnotation = "cluster.x-k8s.io/disable-machine-create" + + // WatchLabel is a label othat can be applied to any Cluster API object. + // + // Controllers which allow for selective reconciliation may check this label and proceed + // with reconciliation of the object only if this label and a configured value is present. + WatchLabel = "cluster.x-k8s.io/watch-filter" + + // DeleteMachineAnnotation marks control plane and worker nodes that will be given priority for deletion + // when KCP or a machineset scales down. This annotation is given top priority on all delete policies. + DeleteMachineAnnotation = "cluster.x-k8s.io/delete-machine" + + // TemplateClonedFromNameAnnotation is the infrastructure machine annotation that stores the name of the infrastructure template resource + // that was cloned for the machine. This annotation is set only during cloning a template. Older/adopted machines will not have this annotation. + TemplateClonedFromNameAnnotation = "cluster.x-k8s.io/cloned-from-name" + + // TemplateClonedFromGroupKindAnnotation is the infrastructure machine annotation that stores the group-kind of the infrastructure template resource + // that was cloned for the machine. This annotation is set only during cloning a template. Older/adopted machines will not have this annotation. + TemplateClonedFromGroupKindAnnotation = "cluster.x-k8s.io/cloned-from-groupkind" + + // MachineSkipRemediationAnnotation is the annotation used to mark the machines that should not be considered for remediation by MachineHealthCheck reconciler. + MachineSkipRemediationAnnotation = "cluster.x-k8s.io/skip-remediation" + + // RemediateMachineAnnotation request the MachineHealthCheck reconciler to mark a Machine as unhealthy. CAPI builtin remediation will prioritize Machines with the annotation to be remediated. + RemediateMachineAnnotation = "cluster.x-k8s.io/remediate-machine" + + // MachineSetSkipPreflightChecksAnnotation is the annotation used to provide a comma-separated list of + // preflight checks that should be skipped during the MachineSet reconciliation. + // Supported items are: + // - KubeadmVersion (skips the kubeadm version skew preflight check) + // - KubernetesVersion (skips the kubernetes version skew preflight check) + // - ControlPlaneStable (skips checking that the control plane is neither provisioning nor upgrading) + // - All (skips all preflight checks) + // Example: "machineset.cluster.x-k8s.io/skip-preflight-checks": "ControlPlaneStable,KubernetesVersion". + // Note: The annotation can also be set on a MachineDeployment as MachineDeployment annotations are synced to + // the MachineSet. + MachineSetSkipPreflightChecksAnnotation = "machineset.cluster.x-k8s.io/skip-preflight-checks" + + // ClusterSecretType defines the type of secret created by core components. + // Note: This is used by core CAPI, CAPBK, and KCP to determine whether a secret is created by the controllers + // themselves or supplied by the user (e.g. bring your own certificates). + ClusterSecretType corev1.SecretType = "cluster.x-k8s.io/secret" //nolint:gosec + + // InterruptibleLabel is the label used to mark the nodes that run on interruptible instances. + InterruptibleLabel = "cluster.x-k8s.io/interruptible" + + // ManagedByAnnotation is an annotation that can be applied to InfraCluster resources to signify that + // some external system is managing the cluster infrastructure. + // + // Provider InfraCluster controllers will ignore resources with this annotation. + // An external controller must fulfill the contract of the InfraCluster resource. + // External infrastructure providers should ensure that the annotation, once set, cannot be removed. + ManagedByAnnotation = "cluster.x-k8s.io/managed-by" + + // TopologyDryRunAnnotation is an annotation that gets set on objects by the topology controller + // only during a server side dry run apply operation. It is used for validating + // update webhooks for objects which get updated by template rotation (e.g. InfrastructureMachineTemplate). + // When the annotation is set and the admission request is a dry run, the webhook should + // skip validation due to immutability. By that the request will succeed (without + // any changes to the actual object because it is a dry run) and the topology controller + // will receive the resulting object. + TopologyDryRunAnnotation = "topology.cluster.x-k8s.io/dry-run" + + // ReplicasManagedByAnnotation is an annotation that indicates external (non-Cluster API) management of infra scaling. + // The practical effect of this is that the capi "replica" count should be passively derived from the number of observed infra machines, + // instead of being a source of truth for eventual consistency. + // This annotation can be used to inform MachinePool status during in-progress scaling scenarios. + ReplicasManagedByAnnotation = "cluster.x-k8s.io/replicas-managed-by" + + // AutoscalerMinSizeAnnotation defines the minimum node group size. + // The annotation is used by autoscaler. + // The annotation is copied from kubernetes/autoscaler. + // Ref:https://github.com/kubernetes/autoscaler/blob/d8336cca37dbfa5d1cb7b7e453bd511172d6e5e7/cluster-autoscaler/cloudprovider/clusterapi/clusterapi_utils.go#L256-L259 + // Note: With the Kubernetes autoscaler it is possible to use different annotations by configuring a different + // "Cluster API group" than "cluster.x-k8s.io" via the "CAPI_GROUP" environment variable. + // We only handle the default group in our implementation. + // Note: It can be used by setting as top level annotation on MachineDeployment and MachineSets. + AutoscalerMinSizeAnnotation = "cluster.x-k8s.io/cluster-api-autoscaler-node-group-min-size" + + // AutoscalerMaxSizeAnnotation defines the maximum node group size. + // The annotations is used by the autoscaler. + // The annotation definition is copied from kubernetes/autoscaler. + // Ref:https://github.com/kubernetes/autoscaler/blob/d8336cca37dbfa5d1cb7b7e453bd511172d6e5e7/cluster-autoscaler/cloudprovider/clusterapi/clusterapi_utils.go#L264-L267 + // Note: With the Kubernetes autoscaler it is possible to use different annotations by configuring a different + // "Cluster API group" than "cluster.x-k8s.io" via the "CAPI_GROUP" environment variable. + // We only handle the default group in our implementation. + // Note: It can be used by setting as top level annotation on MachineDeployment and MachineSets. + AutoscalerMaxSizeAnnotation = "cluster.x-k8s.io/cluster-api-autoscaler-node-group-max-size" + + // VariableDefinitionFromInline indicates a patch or variable was defined in the `.spec` of a ClusterClass + // rather than from an external patch extension. + VariableDefinitionFromInline = "inline" + + // CRDMigrationObservedGenerationAnnotation indicates on a CRD for which generation CRD migration is completed. + CRDMigrationObservedGenerationAnnotation = "crd-migration.cluster.x-k8s.io/observed-generation" + + // BeforeClusterUpgradeHookAnnotationPrefix annotation specifies the prefix we search each annotation + // for during the before-upgrade lifecycle hook to block propagating the new version to the control plane. + // This hook can be used to execute pre-upgrade add-on tasks and block upgrades of the ControlPlane and Workers. + // Note: While the upgrade is blocked changes made to the Cluster Topology will be delayed propagating to the underlying + // objects while the object is waiting for upgrade. + BeforeClusterUpgradeHookAnnotationPrefix = "before-upgrade.hook.cluster.cluster.x-k8s.io" +) + +// MachineSetPreflightCheck defines a valid MachineSet preflight check. +type MachineSetPreflightCheck string + +const ( + // MachineSetPreflightCheckAll can be used to represent all the MachineSet preflight checks. + MachineSetPreflightCheckAll MachineSetPreflightCheck = "All" + + // MachineSetPreflightCheckKubeadmVersionSkew is the name of the preflight check + // that verifies if the machine being created or remediated for the MachineSet conforms to the kubeadm version + // skew policy that requires the machine to be at the same minor version as the control plane. + // The preflight check is only run if a ControlPlane is used (controlPlaneRef must exist in the Cluster), + // the ControlPlane has a version, the MachineSet has a version and the MachineSet uses the Kubeadm bootstrap + // provider. + MachineSetPreflightCheckKubeadmVersionSkew MachineSetPreflightCheck = "KubeadmVersionSkew" + + // MachineSetPreflightCheckKubernetesVersionSkew is the name of the preflight check that verifies + // if the machines being created or remediated for the MachineSet conform to the Kubernetes version skew policy + // that requires the machines to be at a version that is not more than 2 (< v1.28) or 3 (>= v1.28) minor + // lower than the ControlPlane version. + // The preflight check is only run if a ControlPlane is used (controlPlaneRef must exist in the Cluster), + // the ControlPlane has a version and the MachineSet has a version. + MachineSetPreflightCheckKubernetesVersionSkew MachineSetPreflightCheck = "KubernetesVersionSkew" + + // MachineSetPreflightCheckControlPlaneIsStable is the name of the preflight check + // that verifies if the control plane is not provisioning and not upgrading. + // For Clusters with a managed topology it also checks if a control plane upgrade is pending. + // The preflight check is only run if a ControlPlane is used (controlPlaneRef must exist in the Cluster) + // and the ControlPlane has a version. + MachineSetPreflightCheckControlPlaneIsStable MachineSetPreflightCheck = "ControlPlaneIsStable" + + // MachineSetPreflightCheckControlPlaneVersionSkew is the name of the preflight check + // that verifies if the machine being created or remediated for the MachineSet has exactly the same version + // as the control plane. + // The idea behind this check is that it doesn't make sense to create a Machine with an old version, if we already + // know based on the control plane version that the Machine has to be replaced soon. + // The preflight check is only run if the Cluster has a managed topology, a ControlPlane is used (controlPlaneRef + // must exist in the Cluster), the ControlPlane has a version and the MachineSet has a version. + MachineSetPreflightCheckControlPlaneVersionSkew MachineSetPreflightCheck = "ControlPlaneVersionSkew" +) + +// NodeOutdatedRevisionTaint can be added to Nodes at rolling updates in general triggered by updating MachineDeployment +// This taint is used to prevent unnecessary pod churn, i.e., as the first node is drained, pods previously running on +// that node are scheduled onto nodes who have yet to be replaced, but will be torn down soon. +var NodeOutdatedRevisionTaint = corev1.Taint{ + Key: "node.cluster.x-k8s.io/outdated-revision", + Effect: corev1.TaintEffectPreferNoSchedule, +} + +// NodeUninitializedTaint can be added to Nodes at creation by the bootstrap provider, e.g. the +// KubeadmBootstrap provider will add the taint. +// This taint is used to prevent workloads to be scheduled on Nodes before the node is initialized by Cluster API. +// As of today the Node initialization consists of syncing labels from Machines to Nodes. Once the labels +// have been initially synced the taint is removed from the Node. +var NodeUninitializedTaint = corev1.Taint{ + Key: "node.cluster.x-k8s.io/uninitialized", + Effect: corev1.TaintEffectNoSchedule, +} + +const ( + // TemplateSuffix is the object kind suffix used by template types. + TemplateSuffix = "Template" +) + +// MachineAddressType describes a valid MachineAddress type. +// +kubebuilder:validation:Enum=Hostname;ExternalIP;InternalIP;ExternalDNS;InternalDNS +type MachineAddressType string + +// Define the MachineAddressType constants. +const ( + MachineHostName MachineAddressType = "Hostname" + MachineExternalIP MachineAddressType = "ExternalIP" + MachineInternalIP MachineAddressType = "InternalIP" + MachineExternalDNS MachineAddressType = "ExternalDNS" + MachineInternalDNS MachineAddressType = "InternalDNS" +) + +// MachineAddress contains information for the node's address. +type MachineAddress struct { + // type is the machine address type, one of Hostname, ExternalIP, InternalIP, ExternalDNS or InternalDNS. + // +required + Type MachineAddressType `json:"type,omitempty"` + + // address is the machine address. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Address string `json:"address,omitempty"` +} + +// MachineAddresses is a slice of MachineAddress items to be used by infrastructure providers. +// +kubebuilder:validation:MaxItems=128 +// +listType=atomic +type MachineAddresses []MachineAddress + +// ObjectMeta is metadata that all persisted resources must have, which includes all objects +// users must create. This is a copy of customizable fields from metav1.ObjectMeta. +// +// ObjectMeta is embedded in `Machine.Spec`, `MachineDeployment.Template` and `MachineSet.Template`, +// which are not top-level Kubernetes objects. Given that metav1.ObjectMeta has lots of special cases +// and read-only fields which end up in the generated CRD validation, having it as a subset simplifies +// the API and some issues that can impact user experience. +// +// During the [upgrade to controller-tools@v2](https://github.com/kubernetes-sigs/cluster-api/pull/1054) +// for v1alpha2, we noticed a failure would occur running Cluster API test suite against the new CRDs, +// specifically `spec.metadata.creationTimestamp in body must be of type string: "null"`. +// The investigation showed that `controller-tools@v2` behaves differently than its previous version +// when handling types from [metav1](k8s.io/apimachinery/pkg/apis/meta/v1) package. +// +// In more details, we found that embedded (non-top level) types that embedded `metav1.ObjectMeta` +// had validation properties, including for `creationTimestamp` (metav1.Time). +// The `metav1.Time` type specifies a custom json marshaller that, when IsZero() is true, returns `null` +// which breaks validation because the field isn't marked as nullable. +// +// In future versions, controller-tools@v2 might allow overriding the type and validation for embedded +// types. When that happens, this hack should be revisited. +// +kubebuilder:validation:MinProperties=1 +type ObjectMeta struct { + // labels is a map of string keys and values that can be used to organize and categorize + // (scope and select) objects. May match selectors of replication controllers + // and services. + // More info: http://kubernetes.io/docs/user-guide/labels + // +optional + Labels map[string]string `json:"labels,omitempty"` + + // annotations is an unstructured key value map stored with a resource that may be + // set by external tools to store and retrieve arbitrary metadata. They are not + // queryable and should be preserved when modifying objects. + // More info: http://kubernetes.io/docs/user-guide/annotations + // +optional + Annotations map[string]string `json:"annotations,omitempty"` +} + +// Validate validates the labels and annotations in ObjectMeta. +func (metadata *ObjectMeta) Validate(parent *field.Path) field.ErrorList { + allErrs := metav1validation.ValidateLabels( + metadata.Labels, + parent.Child("labels"), + ) + allErrs = append(allErrs, apivalidation.ValidateAnnotations( + metadata.Annotations, + parent.Child("annotations"), + )...) + return allErrs +} + +// ContractVersionedObjectReference is a reference to a resource for which the version is inferred from contract labels. +type ContractVersionedObjectReference struct { + // kind of the resource being referenced. + // kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$` + Kind string `json:"kind,omitempty"` + + // name of the resource being referenced. + // name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` + + // apiGroup is the group of the resource being referenced. + // apiGroup must be fully qualified domain name. + // The corresponding version for this reference will be looked up from the contract + // labels of the corresponding CRD of the resource being referenced. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + APIGroup string `json:"apiGroup,omitempty"` +} + +// IsDefined returns true if the ContractVersionedObjectReference is set. +func (r *ContractVersionedObjectReference) IsDefined() bool { + if r == nil { + return false + } + return r.Kind != "" || r.Name != "" || r.APIGroup != "" +} + +// GroupKind returns the GroupKind of the reference. +func (r *ContractVersionedObjectReference) GroupKind() schema.GroupKind { + return schema.GroupKind{ + Group: r.APIGroup, + Kind: r.Kind, + } +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/condition_consts.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/condition_consts.go new file mode 100644 index 000000000000..23abc6c2ba2e --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/condition_consts.go @@ -0,0 +1,215 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +// Conditions types that are used across different objects. +const ( + // AvailableCondition reports if an object is available. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + AvailableCondition = "Available" + + // ReadyCondition reports if an object is ready. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + ReadyCondition = "Ready" + + // BootstrapConfigReadyCondition reports if an object's bootstrap config is ready. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + BootstrapConfigReadyCondition = "BootstrapConfigReady" + + // InfrastructureReadyCondition reports if an object's infrastructure is ready. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + InfrastructureReadyCondition = "InfrastructureReady" + + // MachinesReadyCondition surfaces detail of issues on the controlled machines, if any. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + MachinesReadyCondition = "MachinesReady" + + // MachinesUpToDateCondition surfaces details of controlled machines not up to date, if any. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + MachinesUpToDateCondition = "MachinesUpToDate" + + // RollingOutCondition reports if an object is rolling out changes to machines; Cluster API usually + // rolls out changes to machines by replacing not up-to-date machines with new ones. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + RollingOutCondition = "RollingOut" + + // ScalingUpCondition reports if an object is scaling up. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + ScalingUpCondition = "ScalingUp" + + // ScalingDownCondition reports if an object is scaling down. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + ScalingDownCondition = "ScalingDown" + + // RemediatingCondition surfaces details about ongoing remediation of the controlled machines, if any. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + RemediatingCondition = "Remediating" + + // DeletingCondition surfaces details about progress of the object deletion workflow. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + DeletingCondition = "Deleting" + + // PausedCondition reports if reconciliation for an object or the cluster is paused. + // Note: This condition type is defined to ensure consistent naming of conditions across objects. + // Please use object specific variants of this condition which provides more details for each context where + // the same condition type exists. + PausedCondition = "Paused" +) + +// Reasons that are used across different objects. +const ( + // AvailableReason applies to a condition surfacing object availability. + AvailableReason = "Available" + + // NotAvailableReason applies to a condition surfacing object not satisfying availability criteria. + NotAvailableReason = "NotAvailable" + + // AvailableUnknownReason applies to a condition surfacing object availability unknown. + AvailableUnknownReason = "AvailableUnknown" + + // ReadyReason applies to a condition surfacing object readiness. + ReadyReason = "Ready" + + // NotReadyReason applies to a condition surfacing object not satisfying readiness criteria. + NotReadyReason = "NotReady" + + // ReadyUnknownReason applies to a condition surfacing object readiness unknown. + ReadyUnknownReason = "ReadyUnknown" + + // UpToDateReason applies to a condition surfacing object up-tp-date. + UpToDateReason = "UpToDate" + + // NotUpToDateReason applies to a condition surfacing object not up-tp-date. + NotUpToDateReason = "NotUpToDate" + + // UpToDateUnknownReason applies to a condition surfacing object up-tp-date unknown. + UpToDateUnknownReason = "UpToDateUnknown" + + // RollingOutReason surfaces when an object is rolling out. + RollingOutReason = "RollingOut" + + // NotRollingOutReason surfaces when an object is not rolling out. + NotRollingOutReason = "NotRollingOut" + + // ScalingUpReason surfaces when an object is scaling up. + ScalingUpReason = "ScalingUp" + + // NotScalingUpReason surfaces when an object is not scaling up. + NotScalingUpReason = "NotScalingUp" + + // ScalingDownReason surfaces when an object is scaling down. + ScalingDownReason = "ScalingDown" + + // NotScalingDownReason surfaces when an object is not scaling down. + NotScalingDownReason = "NotScalingDown" + + // RemediatingReason surfaces when an object owns at least one machine with HealthCheckSucceeded + // set to false and with the OwnerRemediated condition set to false by the MachineHealthCheck controller. + RemediatingReason = "Remediating" + + // NotRemediatingReason surfaces when an object does not own any machines with HealthCheckSucceeded + // set to false and with the OwnerRemediated condition set to false by the MachineHealthCheck controller. + NotRemediatingReason = "NotRemediating" + + // NoReplicasReason surfaces when an object that manage replicas does not have any. + NoReplicasReason = "NoReplicas" + + // WaitingForReplicasSetReason surfaces when the replica field of an object is not set. + WaitingForReplicasSetReason = "WaitingForReplicasSet" + + // InvalidConditionReportedReason applies to a condition, usually read from an external object, that is invalid + // (e.g. its status is missing). + InvalidConditionReportedReason = "InvalidConditionReported" + + // InternalErrorReason surfaces unexpected errors reporting by controllers. + // In most cases, it will be required to look at controllers logs to properly triage those issues. + InternalErrorReason = "InternalError" + + // ObjectDoesNotExistReason surfaces when a referenced object does not exist. + ObjectDoesNotExistReason = "ObjectDoesNotExist" + + // ObjectDeletedReason surfaces when a referenced object has been deleted. + // Note: controllers can't identify if the object was deleted by the controller itself, e.g. + // during the deletion workflow, or by a users. + ObjectDeletedReason = "ObjectDeleted" + + // NotPausedReason surfaces when an object is not paused. + NotPausedReason = "NotPaused" + + // PausedReason surfaces when an object is paused. + PausedReason = "Paused" + + // ConnectionDownReason surfaces that the connection to the workload cluster is down. + ConnectionDownReason = "ConnectionDown" + + // NotDeletingReason surfaces when an object is not deleting because the + // DeletionTimestamp is not set. + NotDeletingReason = "NotDeleting" + + // DeletingReason surfaces when an object is deleting because the + // DeletionTimestamp is set. This reason is used if none of the more specific reasons apply. + DeletingReason = "Deleting" + + // DeletionCompletedReason surfaces when the deletion process has been completed. + // This reason is set right after the corresponding finalizer is removed. + // This means that the object will go away (i.e. be removed from etcd), except if there are other + // finalizers on the object. + DeletionCompletedReason = "DeletionCompleted" + + // InspectionFailedReason applies to a condition when inspection of the underlying object failed. + InspectionFailedReason = "InspectionFailed" + + // WaitingForClusterInfrastructureReadyReason documents an infra Machine waiting for the cluster + // infrastructure to be ready. + WaitingForClusterInfrastructureReadyReason = "WaitingForClusterInfrastructureReady" + + // WaitingForControlPlaneInitializedReason documents an infra Machine waiting + // for the control plane to be initialized. + WaitingForControlPlaneInitializedReason = "WaitingForControlPlaneInitialized" + + // WaitingForBootstrapDataReason documents an infra Machine waiting for the bootstrap + // data to be ready before starting to create the Machine's infrastructure. + WaitingForBootstrapDataReason = "WaitingForBootstrapData" + + // ProvisionedReason documents an object or a piece of infrastructure being provisioned. + ProvisionedReason = "Provisioned" + + // NotProvisionedReason documents an object or a piece of infrastructure is not provisioned. + NotProvisionedReason = "NotProvisioned" +) diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/condition_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/condition_types.go new file mode 100644 index 000000000000..c609b34c7e9e --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/condition_types.go @@ -0,0 +1,88 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// ConditionSeverity expresses the severity of a Condition Type failing. +// +kubebuilder:validation:MaxLength=32 +type ConditionSeverity string + +const ( + // ConditionSeverityError specifies that a condition with `Status=False` is an error. + ConditionSeverityError ConditionSeverity = "Error" + + // ConditionSeverityWarning specifies that a condition with `Status=False` is a warning. + ConditionSeverityWarning ConditionSeverity = "Warning" + + // ConditionSeverityInfo specifies that a condition with `Status=False` is informative. + ConditionSeverityInfo ConditionSeverity = "Info" + + // ConditionSeverityNone should apply only to conditions with `Status=True`. + ConditionSeverityNone ConditionSeverity = "" +) + +// ConditionType is a valid value for Condition.Type. +// +kubebuilder:validation:MinLength=1 +// +kubebuilder:validation:MaxLength=256 +type ConditionType string + +// Condition defines an observation of a Cluster API resource operational state. +type Condition struct { + // type of condition in CamelCase or in foo.example.com/CamelCase. + // Many .condition.type values are consistent across resources like Available, but because arbitrary conditions + // can be useful (see .node.status.conditions), the ability to deconflict is important. + // +required + Type ConditionType `json:"type"` + + // status of the condition, one of True, False, Unknown. + // +required + Status corev1.ConditionStatus `json:"status"` + + // severity provides an explicit classification of Reason code, so the users or machines can immediately + // understand the current situation and act accordingly. + // The Severity field MUST be set only when Status=False. + // +optional + Severity ConditionSeverity `json:"severity,omitempty"` //nolint:kubeapilinter // the Condition type will be removed when v1beta1 is removed + + // lastTransitionTime is the last time the condition transitioned from one status to another. + // This should be when the underlying condition changed. If that is not known, then using the time when + // the API field changed is acceptable. + // +required + LastTransitionTime metav1.Time `json:"lastTransitionTime"` + + // reason is the reason for the condition's last transition in CamelCase. + // The specific API may choose whether or not this field is considered a guaranteed API. + // This field may be empty. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Reason string `json:"reason,omitempty"` + + // message is a human readable message indicating details about the transition. + // This field may be empty. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=10240 + Message string `json:"message,omitempty"` +} + +// Conditions provide observations of the operational state of a Cluster API resource. +type Conditions []Condition diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/conversion.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/conversion.go new file mode 100644 index 000000000000..ad42bde84bec --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/conversion.go @@ -0,0 +1,106 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "math" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" +) + +func (*Cluster) Hub() {} +func (*ClusterClass) Hub() {} +func (*Machine) Hub() {} +func (*MachineSet) Hub() {} +func (*MachineDeployment) Hub() {} +func (*MachineHealthCheck) Hub() {} +func (*MachinePool) Hub() {} +func (*MachineDrainRule) Hub() {} + +// ConvertToSeconds takes *metav1.Duration and returns a *int32. +// Durations longer than MaxInt32 are capped. +// NOTE: this is a util function intended only for usage in API conversions. +func ConvertToSeconds(in *metav1.Duration) *int32 { + if in == nil { + return nil + } + seconds := math.Trunc(in.Seconds()) + if seconds > math.MaxInt32 { + return ptr.To[int32](math.MaxInt32) + } + return ptr.To(int32(seconds)) +} + +// ConvertFromSeconds takes *int32 and returns a *metav1.Duration. +// Durations longer than MaxInt32 are capped. +// NOTE: this is a util function intended only for usage in API conversions. +func ConvertFromSeconds(in *int32) *metav1.Duration { + if in == nil { + return nil + } + return ptr.To(metav1.Duration{Duration: time.Duration(*in) * time.Second}) +} + +func Convert_bool_To_Pointer_bool(in bool, hasRestored bool, restoredIn *bool, out **bool) { + // If the value is false, convert to *false only if the value was *false before (we know it was intentionally set to false). + // In all the other cases we do not know if the value was intentionally set to false, so convert to nil. + if !in { + if hasRestored && restoredIn != nil && !*restoredIn { + *out = ptr.To(false) + return + } + *out = nil + return + } + + // Otherwise, if the value is true, convert to *true. + *out = ptr.To(true) +} + +func Convert_int32_To_Pointer_int32(in int32, hasRestored bool, restoredIn *int32, out **int32) { + // If the value is 0, convert to *0 only if the value was *0 before (we know it was intentionally set to 0). + // In all the other cases we do not know if the value was intentionally set to 0, so convert to nil. + if in == 0 { + if hasRestored && restoredIn != nil && *restoredIn == 0 { + *out = ptr.To[int32](0) + return + } + *out = nil + return + } + + // Otherwise, if the value is not 0, convert to *value. + *out = ptr.To(in) +} + +func Convert_Duration_To_Pointer_int32(in metav1.Duration, hasRestored bool, restoredIn *int32, out **int32) { + // If the value is 0s, convert to *0 only if the value was *0 before (we know it was intentionally set to 0). + // In all the other cases we do not know if the value was intentionally set to 0, so convert to nil. + if in.Nanoseconds() == 0 { + if hasRestored && restoredIn != nil && *restoredIn == 0 { + *out = ptr.To[int32](0) + return + } + *out = nil + return + } + + // Otherwise, if the value is not 0, convert to *value. + *out = ConvertToSeconds(&in) +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/doc.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/doc.go similarity index 72% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/doc.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/doc.go index 38da784101e1..504212fb6dea 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/doc.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2021 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1beta1 contains the v1beta1 API implementation. +// Package v1beta2 contains API Schema definitions for the cluster v1beta2 API group // +k8s:openapi-gen=true -package v1beta1 +// +kubebuilder:object:generate=true +// +groupName=cluster.x-k8s.io +package v1beta2 diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/groupversion_info.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/groupversion_info.go similarity index 65% rename from vendor/sigs.k8s.io/cluster-api/api/v1beta1/groupversion_info.go rename to vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/groupversion_info.go index 95968743c68f..3695797c119a 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/groupversion_info.go +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/groupversion_info.go @@ -1,5 +1,5 @@ /* -Copyright 2021 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,10 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1beta1 contains API Schema definitions for the cluster v1beta1 API group -// +kubebuilder:object:generate=true -// +groupName=cluster.x-k8s.io -package v1beta1 +package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -27,7 +24,7 @@ import ( var ( // GroupVersion is group version used to register these objects. - GroupVersion = schema.GroupVersion{Group: "cluster.x-k8s.io", Version: "v1beta1"} + GroupVersion = schema.GroupVersion{Group: "cluster.x-k8s.io", Version: "v1beta2"} // schemeBuilder is used to add go types to the GroupVersionKind scheme. schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) @@ -36,6 +33,15 @@ var ( AddToScheme = schemeBuilder.AddToScheme objectTypes = []runtime.Object{} + + // GroupVersionInfrastructure is the recommended group version for infrastructure objects. + GroupVersionInfrastructure = schema.GroupVersion{Group: "infrastructure.cluster.x-k8s.io", Version: "v1beta2"} + + // GroupVersionBootstrap is the recommended group version for bootstrap objects. + GroupVersionBootstrap = schema.GroupVersion{Group: "bootstrap.cluster.x-k8s.io", Version: "v1beta2"} + + // GroupVersionControlPlane is the recommended group version for controlplane objects. + GroupVersionControlPlane = schema.GroupVersion{Group: "controlplane.cluster.x-k8s.io", Version: "v1beta2"} ) func addKnownTypes(scheme *runtime.Scheme) error { diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machine_phase_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machine_phase_types.go new file mode 100644 index 000000000000..1ca955156444 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machine_phase_types.go @@ -0,0 +1,69 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +// MachinePhase is a string representation of a Machine Phase. +// +// This type is a high-level indicator of the status of the Machine as it is provisioned, +// from the API user’s perspective. +// +// The value should not be interpreted by any software components as a reliable indication +// of the actual state of the Machine, and controllers should not use the Machine Phase field +// value when making decisions about what action to take. +// +// Controllers should always look at the actual state of the Machine’s fields to make those decisions. +type MachinePhase string + +const ( + // MachinePhasePending is the first state a Machine is assigned by + // Cluster API Machine controller after being created. + MachinePhasePending = MachinePhase("Pending") + + // MachinePhaseProvisioning is the state when the + // Machine infrastructure is being created. + MachinePhaseProvisioning = MachinePhase("Provisioning") + + // MachinePhaseProvisioned is the state when its + // infrastructure has been created and configured. + MachinePhaseProvisioned = MachinePhase("Provisioned") + + // MachinePhaseRunning is the Machine state when it has + // become a Kubernetes Node in a Ready state. + MachinePhaseRunning = MachinePhase("Running") + + // MachinePhaseDeleting is the Machine state when a delete + // request has been sent to the API Server, + // but its infrastructure has not yet been fully deleted. + MachinePhaseDeleting = MachinePhase("Deleting") + + // MachinePhaseDeleted is the Machine state when the object + // and the related infrastructure is deleted and + // ready to be garbage collected by the API Server. + MachinePhaseDeleted = MachinePhase("Deleted") + + // MachinePhaseFailed is the Machine state when the system + // might require user intervention. + // + // Deprecated: This enum value is deprecated; the Failed phase won't be set anymore by controllers, and it is preserved only + // for conversion from v1beta1 objects; the Failed phase is going to be removed when support for v1beta1 will be dropped. + // Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + MachinePhaseFailed = MachinePhase("Failed") + + // MachinePhaseUnknown is returned if the Machine state cannot be determined. + MachinePhaseUnknown = MachinePhase("Unknown") +) diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machine_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machine_types.go new file mode 100644 index 000000000000..a60f736ba21c --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machine_types.go @@ -0,0 +1,802 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + capierrors "sigs.k8s.io/cluster-api/errors" +) + +const ( + // MachineFinalizer is set on PrepareForCreate callback. + MachineFinalizer = "machine.cluster.x-k8s.io" + + // MachineControlPlaneLabel is the label set on machines or related objects that are part of a control plane. + MachineControlPlaneLabel = "cluster.x-k8s.io/control-plane" + + // ExcludeNodeDrainingAnnotation annotation explicitly skips node draining if set. + ExcludeNodeDrainingAnnotation = "machine.cluster.x-k8s.io/exclude-node-draining" + + // ExcludeWaitForNodeVolumeDetachAnnotation annotation explicitly skips the waiting for node volume detaching if set. + ExcludeWaitForNodeVolumeDetachAnnotation = "machine.cluster.x-k8s.io/exclude-wait-for-node-volume-detach" + + // MachineSetNameLabel is the label set on machines if they're controlled by MachineSet. + // Note: The value of this label may be a hash if the MachineSet name is longer than 63 characters. + MachineSetNameLabel = "cluster.x-k8s.io/set-name" + + // MachineDeploymentNameLabel is the label set on machines if they're controlled by MachineDeployment. + MachineDeploymentNameLabel = "cluster.x-k8s.io/deployment-name" + + // MachinePoolNameLabel is the label indicating the name of the MachinePool a Machine is controlled by. + // Note: The value of this label may be a hash if the MachinePool name is longer than 63 characters. + MachinePoolNameLabel = "cluster.x-k8s.io/pool-name" + + // MachineControlPlaneNameLabel is the label set on machines if they're controlled by a ControlPlane. + // Note: The value of this label may be a hash if the control plane name is longer than 63 characters. + MachineControlPlaneNameLabel = "cluster.x-k8s.io/control-plane-name" + + // PreDrainDeleteHookAnnotationPrefix annotation specifies the prefix we + // search each annotation for during the pre-drain.delete lifecycle hook + // to pause reconciliation of deletion. These hooks will prevent removal of + // draining the associated node until all are removed. + PreDrainDeleteHookAnnotationPrefix = "pre-drain.delete.hook.machine.cluster.x-k8s.io" + + // PreTerminateDeleteHookAnnotationPrefix annotation specifies the prefix we + // search each annotation for during the pre-terminate.delete lifecycle hook + // to pause reconciliation of deletion. These hooks will prevent removal of + // an instance from an infrastructure provider until all are removed. + // + // Notes for Machines managed by KCP (starting with Cluster API v1.8.2): + // * KCP adds its own pre-terminate hook on all Machines it controls. This is done to ensure it can later remove + // the etcd member right before Machine termination (i.e. before InfraMachine deletion). + // * Starting with Kubernetes v1.31 the KCP pre-terminate hook will wait for all other pre-terminate hooks to finish to + // ensure it runs last (thus ensuring that kubelet is still working while other pre-terminate hooks run). This is only done + // for v1.31 or above because the kubeadm ControlPlaneKubeletLocalMode was introduced with kubeadm 1.31. This feature configures + // the kubelet to communicate with the local apiserver. Only because of that the kubelet immediately starts failing after the etcd + // member is removed. We need the ControlPlaneKubeletLocalMode feature with 1.31 to adhere to the kubelet skew policy. + PreTerminateDeleteHookAnnotationPrefix = "pre-terminate.delete.hook.machine.cluster.x-k8s.io" + + // MachineCertificatesExpiryDateAnnotation annotation specifies the expiry date of the machine certificates in RFC3339 format. + // This annotation can be used on control plane machines to trigger rollout before certificates expire. + // This annotation can be set on BootstrapConfig or Machine objects. The value set on the Machine object takes precedence. + // This annotation can only be used on Control Plane Machines. + MachineCertificatesExpiryDateAnnotation = "machine.cluster.x-k8s.io/certificates-expiry" + + // NodeRoleLabelPrefix is one of the CAPI managed Node label prefixes. + NodeRoleLabelPrefix = "node-role.kubernetes.io" + // NodeRestrictionLabelDomain is one of the CAPI managed Node label domains. + NodeRestrictionLabelDomain = "node-restriction.kubernetes.io" + // ManagedNodeLabelDomain is one of the CAPI managed Node label domains. + ManagedNodeLabelDomain = "node.cluster.x-k8s.io" + + // ManagedNodeAnnotationDomain is one of the CAPI managed Node annotation domains. + ManagedNodeAnnotationDomain = "node.cluster.x-k8s.io" +) + +// Machine's Available condition and corresponding reasons. +const ( + // MachineAvailableCondition is true if the machine is Ready for at least MinReadySeconds, as defined by the Machine's MinReadySeconds field. + // Note: MinReadySeconds is assumed 0 until it will be implemented in v1beta2 API. + MachineAvailableCondition = AvailableCondition + + // MachineWaitingForMinReadySecondsReason surfaces when a machine is ready for less than MinReadySeconds (and thus not yet available). + MachineWaitingForMinReadySecondsReason = "WaitingForMinReadySeconds" + + // MachineAvailableReason surfaces when a machine is ready for at least MinReadySeconds. + // Note: MinReadySeconds is assumed 0 until it will be implemented in v1beta2 API. + MachineAvailableReason = AvailableReason + + // MachineAvailableInternalErrorReason surfaces unexpected error when computing the Available condition. + MachineAvailableInternalErrorReason = InternalErrorReason +) + +// Machine's Ready condition and corresponding reasons. +const ( + // MachineReadyCondition is true if the Machine's deletionTimestamp is not set, Machine's BootstrapConfigReady, InfrastructureReady, + // NodeHealthy and HealthCheckSucceeded (if present) conditions are true; if other conditions are defined in spec.readinessGates, + // these conditions must be true as well. + // Note: + // - When summarizing the Deleting condition: + // - Details about Pods stuck in draining or volumes waiting for detach are dropped, in order to improve readability & reduce flickering + // of the condition that bubbles up to the owning resources/ to the Cluster (it also makes it more likely this condition might be aggregated with + // conditions reported by other machines). + // - If deletion is in progress for more than 15m, this surfaces on the summary condition (hint about a possible stale deletion). + // - if drain is in progress for more than 5 minutes, a summery of what is blocking drain also surfaces in the message. + // - When summarizing BootstrapConfigReady, InfrastructureReady, NodeHealthy, in case the Machine is deleting, the absence of the + // referenced object won't be considered as an issue. + MachineReadyCondition = ReadyCondition + + // MachineReadyReason surfaces when the machine readiness criteria is met. + MachineReadyReason = ReadyReason + + // MachineNotReadyReason surfaces when the machine readiness criteria is not met. + // Note: when a machine is not ready, it is also not available. + MachineNotReadyReason = NotReadyReason + + // MachineReadyUnknownReason surfaces when at least one machine readiness criteria is unknown + // and no machine readiness criteria is not met. + MachineReadyUnknownReason = ReadyUnknownReason + + // MachineReadyInternalErrorReason surfaces unexpected error when computing the Ready condition. + MachineReadyInternalErrorReason = InternalErrorReason +) + +// Machine's UpToDate condition and corresponding reasons. +// Note: UpToDate condition is set by the controller owning the machine. +const ( + // MachineUpToDateCondition is true if the Machine spec matches the spec of the Machine's owner resource, e.g. KubeadmControlPlane or MachineDeployment. + // The Machine's owner (e.g. MachineDeployment) is authoritative to set their owned Machine's UpToDate conditions based on its current spec. + // NOTE: The Machine's owner might use this condition to surface also other use cases when Machine is considered not up to date, e.g. when MachineDeployment spec.rolloutAfter + // is expired and the Machine needs to be rolled out. + MachineUpToDateCondition = "UpToDate" + + // MachineUpToDateReason surface when a Machine spec matches the spec of the Machine's owner resource, e.g. KubeadmControlPlane or MachineDeployment. + MachineUpToDateReason = "UpToDate" + + // MachineNotUpToDateReason surface when a Machine spec does not match the spec of the Machine's owner resource, e.g. KubeadmControlPlane or MachineDeployment. + MachineNotUpToDateReason = "NotUpToDate" +) + +// Machine's BootstrapConfigReady condition and corresponding reasons. +// Note: when possible, BootstrapConfigReady condition will use reasons surfaced from the underlying bootstrap config object. +const ( + // MachineBootstrapConfigReadyCondition condition mirrors the corresponding Ready condition from the Machine's BootstrapConfig resource. + MachineBootstrapConfigReadyCondition = BootstrapConfigReadyCondition + + // MachineBootstrapDataSecretProvidedReason surfaces when a bootstrap data secret is provided (not originated + // from a BoostrapConfig object referenced from the machine). + MachineBootstrapDataSecretProvidedReason = "DataSecretProvided" + + // MachineBootstrapConfigReadyReason surfaces when the machine bootstrap config is ready. + MachineBootstrapConfigReadyReason = ReadyReason + + // MachineBootstrapConfigNotReadyReason surfaces when the machine bootstrap config is not ready. + MachineBootstrapConfigNotReadyReason = NotReadyReason + + // MachineBootstrapConfigInvalidConditionReportedReason surfaces a BootstrapConfig Ready condition (read from a bootstrap config object) which is invalid. + // (e.g. its status is missing). + MachineBootstrapConfigInvalidConditionReportedReason = InvalidConditionReportedReason + + // MachineBootstrapConfigInternalErrorReason surfaces unexpected failures when reading a BootstrapConfig object. + MachineBootstrapConfigInternalErrorReason = InternalErrorReason + + // MachineBootstrapConfigDoesNotExistReason surfaces when a referenced bootstrap config object does not exist. + // Note: this could happen when creating the machine. However, this state should be treated as an error if it lasts indefinitely. + MachineBootstrapConfigDoesNotExistReason = ObjectDoesNotExistReason + + // MachineBootstrapConfigDeletedReason surfaces when a referenced bootstrap config object has been deleted. + // Note: controllers can't identify if the bootstrap config object was deleted the controller itself, e.g. + // during the deletion workflow, or by a users. + MachineBootstrapConfigDeletedReason = ObjectDeletedReason +) + +// Machine's InfrastructureReady condition and corresponding reasons. +// Note: when possible, InfrastructureReady condition will use reasons surfaced from the underlying infra machine object. +const ( + // MachineInfrastructureReadyCondition mirrors the corresponding Ready condition from the Machine's infrastructure resource. + MachineInfrastructureReadyCondition = InfrastructureReadyCondition + + // MachineInfrastructureReadyReason surfaces when the machine infrastructure is ready. + MachineInfrastructureReadyReason = ReadyReason + + // MachineInfrastructureNotReadyReason surfaces when the machine infrastructure is not ready. + MachineInfrastructureNotReadyReason = NotReadyReason + + // MachineInfrastructureInvalidConditionReportedReason surfaces a infrastructure Ready condition (read from an infra machine object) which is invalid. + // (e.g. its status is missing). + MachineInfrastructureInvalidConditionReportedReason = InvalidConditionReportedReason + + // MachineInfrastructureInternalErrorReason surfaces unexpected failures when reading an infra machine object. + MachineInfrastructureInternalErrorReason = InternalErrorReason + + // MachineInfrastructureDoesNotExistReason surfaces when a referenced infrastructure object does not exist. + // Note: this could happen when creating the machine. However, this state should be treated as an error if it lasts indefinitely. + MachineInfrastructureDoesNotExistReason = ObjectDoesNotExistReason + + // MachineInfrastructureDeletedReason surfaces when a referenced infrastructure object has been deleted. + // Note: controllers can't identify if the infrastructure object was deleted by the controller itself, e.g. + // during the deletion workflow, or by a users. + MachineInfrastructureDeletedReason = ObjectDeletedReason +) + +// Machine's NodeHealthy and NodeReady conditions and corresponding reasons. +// Note: when possible, NodeHealthy and NodeReady conditions will use reasons surfaced from the underlying node. +const ( + // MachineNodeHealthyCondition is true if the Machine's Node is ready and it does not report MemoryPressure, DiskPressure and PIDPressure. + MachineNodeHealthyCondition = "NodeHealthy" + + // MachineNodeReadyCondition is true if the Machine's Node is ready. + MachineNodeReadyCondition = "NodeReady" + + // MachineNodeReadyReason surfaces when Machine's Node Ready condition is true. + MachineNodeReadyReason = "NodeReady" + + // MachineNodeNotReadyReason surfaces when Machine's Node Ready condition is false. + MachineNodeNotReadyReason = "NodeNotReady" + + // MachineNodeReadyUnknownReason surfaces when Machine's Node Ready condition is unknown. + MachineNodeReadyUnknownReason = "NodeReadyUnknown" + + // MachineNodeHealthyReason surfaces when all the node conditions report healthy state. + MachineNodeHealthyReason = "NodeHealthy" + + // MachineNodeNotHealthyReason surfaces when at least one node conditions report not healthy state. + MachineNodeNotHealthyReason = "NodeNotHealthy" + + // MachineNodeHealthUnknownReason surfaces when at least one node conditions report healthy state unknown + // and no node conditions report not healthy state. + MachineNodeHealthUnknownReason = "NodeHealthyUnknown" + + // MachineNodeInternalErrorReason surfaces unexpected failures when reading a Node object. + MachineNodeInternalErrorReason = InternalErrorReason + + // MachineNodeDoesNotExistReason surfaces when the node hosted on the machine does not exist. + // Note: this could happen when creating the machine. However, this state should be treated as an error if it lasts indefinitely. + MachineNodeDoesNotExistReason = "NodeDoesNotExist" + + // MachineNodeDeletedReason surfaces when the node hosted on the machine has been deleted. + // Note: controllers can't identify if the Node was deleted by the controller itself, e.g. + // during the deletion workflow, or by a users. + MachineNodeDeletedReason = "NodeDeleted" + + // MachineNodeInspectionFailedReason documents a failure when inspecting the status of a Node. + MachineNodeInspectionFailedReason = InspectionFailedReason + + // MachineNodeConnectionDownReason surfaces that the connection to the workload cluster is down. + MachineNodeConnectionDownReason = ConnectionDownReason +) + +// Machine's HealthCheckSucceeded condition and corresponding reasons. +// Note: HealthCheckSucceeded condition is set by the MachineHealthCheck controller. +const ( + // MachineHealthCheckSucceededCondition is true if MHC instances targeting this machine report the Machine + // is healthy according to the definition of healthy present in the spec of the MachineHealthCheck object. + MachineHealthCheckSucceededCondition = "HealthCheckSucceeded" + + // MachineHealthCheckSucceededReason surfaces when a machine passes all the health checks defined by a MachineHealthCheck object. + MachineHealthCheckSucceededReason = "HealthCheckSucceeded" + + // MachineHealthCheckUnhealthyNodeReason surfaces when the node hosted on the machine does not pass the health checks + // defined by a MachineHealthCheck object. + MachineHealthCheckUnhealthyNodeReason = "UnhealthyNode" + + // MachineHealthCheckNodeStartupTimeoutReason surfaces when the node hosted on the machine does not appear within + // the timeout defined by a MachineHealthCheck object. + MachineHealthCheckNodeStartupTimeoutReason = "NodeStartupTimeout" + + // MachineHealthCheckNodeDeletedReason surfaces when a MachineHealthCheck detects that the node hosted on the + // machine has been deleted while the Machine is still running. + MachineHealthCheckNodeDeletedReason = "NodeDeleted" + + // MachineHealthCheckHasRemediateAnnotationReason surfaces when a MachineHealthCheck detects that a Machine was + // marked for remediation via the `cluster.x-k8s.io/remediate-machine` annotation. + MachineHealthCheckHasRemediateAnnotationReason = "HasRemediateAnnotation" +) + +// Machine's OwnerRemediated conditions and corresponding reasons. +// Note: OwnerRemediated condition is initially set by the MachineHealthCheck controller; then it is up to the Machine's +// owner controller to update or delete this condition. +const ( + // MachineOwnerRemediatedCondition is only present if MHC instances targeting this machine + // determine that the controller owning this machine should perform remediation. + MachineOwnerRemediatedCondition = "OwnerRemediated" + + // MachineOwnerRemediatedWaitingForRemediationReason surfaces the machine is waiting for the owner controller + // to start remediation. + MachineOwnerRemediatedWaitingForRemediationReason = "WaitingForRemediation" +) + +// Machine's ExternallyRemediated conditions and corresponding reasons. +// Note: ExternallyRemediated condition is initially set by the MachineHealthCheck controller; then it is up to the external +// remediation controller to update or delete this condition. +const ( + // MachineExternallyRemediatedCondition is only present if MHC instances targeting this machine + // determine that an external controller should perform remediation. + MachineExternallyRemediatedCondition = "ExternallyRemediated" + + // MachineExternallyRemediatedWaitingForRemediationReason surfaces the machine is waiting for the + // external remediation controller to start remediation. + MachineExternallyRemediatedWaitingForRemediationReason = "WaitingForRemediation" + + // MachineExternallyRemediatedRemediationTemplateNotFoundReason surfaces that the MachineHealthCheck cannot + // find the template for an external remediation request. + MachineExternallyRemediatedRemediationTemplateNotFoundReason = "RemediationTemplateNotFound" + + // MachineExternallyRemediatedRemediationRequestCreationFailedReason surfaces that the MachineHealthCheck cannot + // create a request for the external remediation controller. + MachineExternallyRemediatedRemediationRequestCreationFailedReason = "RemediationRequestCreationFailed" +) + +// Machine's Deleting condition and corresponding reasons. +const ( + // MachineDeletingCondition surfaces details about progress in the machine deletion workflow. + MachineDeletingCondition = DeletingCondition + + // MachineNotDeletingReason surfaces when the Machine is not deleting because the + // DeletionTimestamp is not set. + MachineNotDeletingReason = NotDeletingReason + + // MachineDeletingReason surfaces when the Machine is deleting because the + // DeletionTimestamp is set. This reason is used if none of the more specific reasons apply. + MachineDeletingReason = DeletingReason + + // MachineDeletingInternalErrorReason surfaces unexpected failures when deleting a Machine. + MachineDeletingInternalErrorReason = InternalErrorReason + + // MachineDeletingWaitingForPreDrainHookReason surfaces when the Machine deletion + // waits for pre-drain hooks to complete. I.e. it waits until there are no annotations + // with the `pre-drain.delete.hook.machine.cluster.x-k8s.io` prefix on the Machine anymore. + MachineDeletingWaitingForPreDrainHookReason = "WaitingForPreDrainHook" + + // MachineDeletingDrainingNodeReason surfaces when the Machine deletion is draining the Node. + MachineDeletingDrainingNodeReason = "DrainingNode" + + // MachineDeletingWaitingForVolumeDetachReason surfaces when the Machine deletion is + // waiting for volumes to detach from the Node. + MachineDeletingWaitingForVolumeDetachReason = "WaitingForVolumeDetach" + + // MachineDeletingWaitingForPreTerminateHookReason surfaces when the Machine deletion + // waits for pre-terminate hooks to complete. I.e. it waits until there are no annotations + // with the `pre-terminate.delete.hook.machine.cluster.x-k8s.io` prefix on the Machine anymore. + MachineDeletingWaitingForPreTerminateHookReason = "WaitingForPreTerminateHook" + + // MachineDeletingWaitingForInfrastructureDeletionReason surfaces when the Machine deletion + // waits for InfraMachine deletion to complete. + MachineDeletingWaitingForInfrastructureDeletionReason = "WaitingForInfrastructureDeletion" + + // MachineDeletingWaitingForBootstrapDeletionReason surfaces when the Machine deletion + // waits for BootstrapConfig deletion to complete. + MachineDeletingWaitingForBootstrapDeletionReason = "WaitingForBootstrapDeletion" + + // MachineDeletingDeletingNodeReason surfaces when the Machine deletion is + // deleting the Node. + MachineDeletingDeletingNodeReason = "DeletingNode" + + // MachineDeletingDeletionCompletedReason surfaces when the Machine deletion has been completed. + // This reason is set right after the `machine.cluster.x-k8s.io` finalizer is removed. + // This means that the object will go away (i.e. be removed from etcd), except if there are other + // finalizers on the Machine object. + MachineDeletingDeletionCompletedReason = DeletionCompletedReason +) + +// MachineSpec defines the desired state of Machine. +type MachineSpec struct { + // clusterName is the name of the Cluster this object belongs to. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + ClusterName string `json:"clusterName,omitempty"` + + // bootstrap is a reference to a local struct which encapsulates + // fields to configure the Machine’s bootstrapping mechanism. + // +required + Bootstrap Bootstrap `json:"bootstrap,omitempty,omitzero"` + + // infrastructureRef is a required reference to a custom resource + // offered by an infrastructure provider. + // +required + InfrastructureRef ContractVersionedObjectReference `json:"infrastructureRef,omitempty,omitzero"` + + // version defines the desired Kubernetes version. + // This field is meant to be optionally used by bootstrap providers. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Version string `json:"version,omitempty"` + + // providerID is the identification ID of the machine provided by the provider. + // This field must match the provider ID as seen on the node object corresponding to this machine. + // This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler + // with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out + // machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a + // generic out-of-tree provider for autoscaler, this field is required by autoscaler to be + // able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver + // and then a comparison is done to find out unregistered machines and are marked for delete. + // This field will be set by the actuators and consumed by higher level entities like autoscaler that will + // be interfacing with cluster-api as generic provider. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=512 + ProviderID string `json:"providerID,omitempty"` + + // failureDomain is the failure domain the machine will be created in. + // Must match the name of a FailureDomain from the Cluster status. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + FailureDomain string `json:"failureDomain,omitempty"` + + // minReadySeconds is the minimum number of seconds for which a Machine should be ready before considering it available. + // Defaults to 0 (Machine will be considered available as soon as the Machine is ready) + // +optional + // +kubebuilder:validation:Minimum=0 + MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` + + // readinessGates specifies additional conditions to include when evaluating Machine Ready condition. + // + // This field can be used e.g. by Cluster API control plane providers to extend the semantic of the + // Ready condition for the Machine they control, like the kubeadm control provider adding ReadinessGates + // for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc. + // + // Another example are external controllers, e.g. responsible to install special software/hardware on the Machines; + // they can include the status of those components with a new condition and add this condition to ReadinessGates. + // + // NOTE: In case readinessGates conditions start with the APIServer, ControllerManager, Scheduler prefix, and all those + // readiness gates condition are reporting the same message, when computing the Machine's Ready condition those + // readinessGates will be replaced by a single entry reporting "Control plane components: " + message. + // This helps to improve readability of conditions bubbling up to the Machine's owner resource / to the Cluster). + // +optional + // +listType=map + // +listMapKey=conditionType + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + ReadinessGates []MachineReadinessGate `json:"readinessGates,omitempty"` + + // deletion contains configuration options for Machine deletion. + // +optional + Deletion MachineDeletionSpec `json:"deletion,omitempty,omitzero"` +} + +// MachineDeletionSpec contains configuration options for Machine deletion. +// +kubebuilder:validation:MinProperties=1 +type MachineDeletionSpec struct { + // nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. + // The default value is 0, meaning that the node can be drained without any time limitations. + // NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDrainTimeoutSeconds *int32 `json:"nodeDrainTimeoutSeconds,omitempty"` + + // nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes + // to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeVolumeDetachTimeoutSeconds *int32 `json:"nodeVolumeDetachTimeoutSeconds,omitempty"` + + // nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine + // hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. + // Defaults to 10 seconds. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeDeletionTimeoutSeconds *int32 `json:"nodeDeletionTimeoutSeconds,omitempty"` +} + +// MachineReadinessGate contains the type of a Machine condition to be used as a readiness gate. +type MachineReadinessGate struct { + // conditionType refers to a condition with matching type in the Machine's condition list. + // If the conditions doesn't exist, it will be treated as unknown. + // Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates. + // +required + // +kubebuilder:validation:Pattern=`^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$` + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=316 + ConditionType string `json:"conditionType,omitempty"` + + // polarity of the conditionType specified in this readinessGate. + // Valid values are Positive, Negative and omitted. + // When omitted, the default behaviour will be Positive. + // A positive polarity means that the condition should report a true status under normal conditions. + // A negative polarity means that the condition should report a false status under normal conditions. + // +optional + Polarity ConditionPolarity `json:"polarity,omitempty"` +} + +// MachineStatus defines the observed state of Machine. +// +kubebuilder:validation:MinProperties=1 +type MachineStatus struct { + // conditions represents the observations of a Machine's current state. + // Known condition types are Available, Ready, UpToDate, BootstrapConfigReady, InfrastructureReady, NodeReady, + // NodeHealthy, Deleting, Paused. + // If a MachineHealthCheck is targeting this machine, also HealthCheckSucceeded, OwnerRemediated conditions are added. + // Additionally control plane Machines controlled by KubeadmControlPlane will have following additional conditions: + // APIServerPodHealthy, ControllerManagerPodHealthy, SchedulerPodHealthy, EtcdPodHealthy, EtcdMemberHealthy. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // initialization provides observations of the Machine initialization process. + // NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Machine provisioning. + // +optional + Initialization MachineInitializationStatus `json:"initialization,omitempty,omitzero"` + + // nodeRef will point to the corresponding Node if it exists. + // +optional + NodeRef MachineNodeReference `json:"nodeRef,omitempty,omitzero"` + + // nodeInfo is a set of ids/uuids to uniquely identify the node. + // More info: https://kubernetes.io/docs/concepts/nodes/node/#info + // +optional + NodeInfo *corev1.NodeSystemInfo `json:"nodeInfo,omitempty"` + + // lastUpdated identifies when the phase of the Machine last transitioned. + // +optional + LastUpdated metav1.Time `json:"lastUpdated,omitempty,omitzero"` + + // addresses is a list of addresses assigned to the machine. + // This field is copied from the infrastructure provider reference. + // +optional + Addresses MachineAddresses `json:"addresses,omitempty"` + + // phase represents the current phase of machine actuation. + // +optional + // +kubebuilder:validation:Enum=Pending;Provisioning;Provisioned;Running;Deleting;Deleted;Failed;Unknown + Phase string `json:"phase,omitempty"` + + // certificatesExpiryDate is the expiry date of the machine certificates. + // This value is only set for control plane machines. + // +optional + CertificatesExpiryDate metav1.Time `json:"certificatesExpiryDate,omitempty,omitzero"` + + // observedGeneration is the latest generation observed by the controller. + // +optional + // +kubebuilder:validation:Minimum=1 + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // deletion contains information relating to removal of the Machine. + // Only present when the Machine has a deletionTimestamp and drain or wait for volume detach started. + // +optional + Deletion *MachineDeletionStatus `json:"deletion,omitempty"` + + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. + // +optional + Deprecated *MachineDeprecatedStatus `json:"deprecated,omitempty"` +} + +// MachineNodeReference is a reference to the node running on the machine. +type MachineNodeReference struct { + // name of the node. + // name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` +} + +// IsDefined returns true if the MachineNodeReference is set. +func (r *MachineNodeReference) IsDefined() bool { + if r == nil { + return false + } + return r.Name != "" +} + +// MachineInitializationStatus provides observations of the Machine initialization process. +// NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Machine provisioning. +// +kubebuilder:validation:MinProperties=1 +type MachineInitializationStatus struct { + // infrastructureProvisioned is true when the infrastructure provider reports that Machine's infrastructure is fully provisioned. + // NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + // The value of this field is never updated after provisioning is completed. + // +optional + InfrastructureProvisioned *bool `json:"infrastructureProvisioned,omitempty"` + + // bootstrapDataSecretCreated is true when the bootstrap provider reports that the Machine's boostrap secret is created. + // NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + // The value of this field is never updated after provisioning is completed. + // +optional + BootstrapDataSecretCreated *bool `json:"bootstrapDataSecretCreated,omitempty"` +} + +// MachineDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachineDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + V1Beta1 *MachineV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` +} + +// MachineV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachineV1Beta1DeprecatedStatus struct { + // conditions defines current service state of the Machine. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + Conditions Conditions `json:"conditions,omitempty"` + + // failureReason will be set in the event that there is a terminal problem + // reconciling the Machine and will contain a succinct value suitable + // for machine interpretation. + // + // This field should not be set for transitive errors that a controller + // faces that are expected to be fixed automatically over + // time (like service outages), but instead indicate that something is + // fundamentally wrong with the Machine's spec or the configuration of + // the controller, and that manual intervention is required. Examples + // of terminal errors would be invalid combinations of settings in the + // spec, values that are unsupported by the controller, or the + // responsible controller itself being critically misconfigured. + // + // Any transient errors that occur during the reconciliation of Machines + // can be added as events to the Machine object and/or logged in the + // controller's output. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + FailureReason *capierrors.MachineStatusError `json:"failureReason,omitempty"` + + // failureMessage will be set in the event that there is a terminal problem + // reconciling the Machine and will contain a more verbose string suitable + // for logging and human consumption. + // + // This field should not be set for transitive errors that a controller + // faces that are expected to be fixed automatically over + // time (like service outages), but instead indicate that something is + // fundamentally wrong with the Machine's spec or the configuration of + // the controller, and that manual intervention is required. Examples + // of terminal errors would be invalid combinations of settings in the + // spec, values that are unsupported by the controller, or the + // responsible controller itself being critically misconfigured. + // + // Any transient errors that occur during the reconciliation of Machines + // can be added as events to the Machine object and/or logged in the + // controller's output. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=10240 + FailureMessage *string `json:"failureMessage,omitempty"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed +} + +// MachineDeletionStatus is the deletion state of the Machine. +type MachineDeletionStatus struct { + // nodeDrainStartTime is the time when the drain of the node started and is used to determine + // if the nodeDrainTimeoutSeconds is exceeded. + // Only present when the Machine has a deletionTimestamp and draining the node had been started. + // +optional + NodeDrainStartTime metav1.Time `json:"nodeDrainStartTime,omitempty,omitzero"` + + // waitForNodeVolumeDetachStartTime is the time when waiting for volume detachment started + // and is used to determine if the nodeVolumeDetachTimeoutSeconds is exceeded. + // Detaching volumes from nodes is usually done by CSI implementations and the current state + // is observed from the node's `.Status.VolumesAttached` field. + // Only present when the Machine has a deletionTimestamp and waiting for volume detachments had been started. + // +optional + WaitForNodeVolumeDetachStartTime metav1.Time `json:"waitForNodeVolumeDetachStartTime,omitempty,omitzero"` +} + +// SetTypedPhase sets the Phase field to the string representation of MachinePhase. +func (m *MachineStatus) SetTypedPhase(p MachinePhase) { + m.Phase = string(p) +} + +// GetTypedPhase attempts to parse the Phase field and return +// the typed MachinePhase representation as described in `machine_phase_types.go`. +func (m *MachineStatus) GetTypedPhase() MachinePhase { + switch phase := MachinePhase(m.Phase); phase { + case + MachinePhasePending, + MachinePhaseProvisioning, + MachinePhaseProvisioned, + MachinePhaseRunning, + MachinePhaseDeleting, + MachinePhaseDeleted, + MachinePhaseFailed: + return phase + default: + return MachinePhaseUnknown + } +} + +// Bootstrap encapsulates fields to configure the Machine’s bootstrapping mechanism. +type Bootstrap struct { + // configRef is a reference to a bootstrap provider-specific resource + // that holds configuration details. The reference is optional to + // allow users/operators to specify Bootstrap.DataSecretName without + // the need of a controller. + // +optional + ConfigRef ContractVersionedObjectReference `json:"configRef,omitempty,omitzero"` + + // dataSecretName is the name of the secret that stores the bootstrap data script. + // If nil, the Machine should remain in the Pending state. + // +optional + // +kubebuilder:validation:MinLength=0 + // +kubebuilder:validation:MaxLength=253 + DataSecretName *string `json:"dataSecretName,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=machines,shortName=ma,scope=Namespaced,categories=cluster-api +// +kubebuilder:subresource:status +// +kubebuilder:storageversion +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" +// +kubebuilder:printcolumn:name="Node Name",type="string",JSONPath=".status.nodeRef.name",description="Node name associated with this machine" +// +kubebuilder:printcolumn:name="Provider ID",type="string",JSONPath=".spec.providerID",description="Provider ID",priority=10 +// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,description="Machine pass all readiness checks" +// +kubebuilder:printcolumn:name="Available",type="string",JSONPath=`.status.conditions[?(@.type=="Available")].status`,description="Machine is Ready for at least MinReadySeconds" +// +kubebuilder:printcolumn:name="Up-to-date",type="string",JSONPath=`.status.conditions[?(@.type=="UpToDate")].status`,description=" Machine spec matches the spec of the Machine's owner resource, e.g. MachineDeployment" +// +kubebuilder:printcolumn:name="Internal-IP",type="string",JSONPath=`.status.addresses[?(@.type=="InternalIP")].address`,description="Internal IP of the machine",priority=10 +// +kubebuilder:printcolumn:name="External-IP",type="string",JSONPath=`.status.addresses[?(@.type=="ExternalIP")].address`,description="External IP of the machine",priority=10 +// +kubebuilder:printcolumn:name="OS-Image",type="string",JSONPath=`.status.nodeInfo.osImage`,description="OS Image reported by the node",priority=10 +// +kubebuilder:printcolumn:name="Paused",type="string",JSONPath=`.status.conditions[?(@.type=="Paused")].status`,description="Reconciliation paused",priority=10 +// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase",description="Machine status such as Terminating/Pending/Running/Failed etc" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of Machine" +// +kubebuilder:printcolumn:name="Version",type="string",JSONPath=".spec.version",description="Kubernetes version associated with this Machine" + +// Machine is the Schema for the machines API. +type Machine struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is the desired state of Machine. + // +required + Spec MachineSpec `json:"spec,omitempty,omitzero"` + // status is the observed state of Machine. + // +optional + Status MachineStatus `json:"status,omitempty,omitzero"` +} + +// GetV1Beta1Conditions returns the set of conditions for this object. +func (m *Machine) GetV1Beta1Conditions() Conditions { + if m.Status.Deprecated == nil || m.Status.Deprecated.V1Beta1 == nil { + return nil + } + return m.Status.Deprecated.V1Beta1.Conditions +} + +// SetV1Beta1Conditions sets the conditions on this object. +func (m *Machine) SetV1Beta1Conditions(conditions Conditions) { + if m.Status.Deprecated == nil { + m.Status.Deprecated = &MachineDeprecatedStatus{} + } + if m.Status.Deprecated.V1Beta1 == nil { + m.Status.Deprecated.V1Beta1 = &MachineV1Beta1DeprecatedStatus{} + } + m.Status.Deprecated.V1Beta1.Conditions = conditions +} + +// GetConditions returns the set of conditions for this object. +func (m *Machine) GetConditions() []metav1.Condition { + return m.Status.Conditions +} + +// SetConditions sets conditions for an API object. +func (m *Machine) SetConditions(conditions []metav1.Condition) { + m.Status.Conditions = conditions +} + +// +kubebuilder:object:root=true + +// MachineList contains a list of Machine. +type MachineList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + // items is the list of Machines. + Items []Machine `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &Machine{}, &MachineList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinedeployment_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinedeployment_types.go new file mode 100644 index 000000000000..b7182c278ef6 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinedeployment_types.go @@ -0,0 +1,648 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" +) + +const ( + // MachineDeploymentTopologyFinalizer is the finalizer used by the topology MachineDeployment controller to + // clean up referenced template resources if necessary when a MachineDeployment is being deleted. + MachineDeploymentTopologyFinalizer = "machinedeployment.topology.cluster.x-k8s.io" + + // MachineDeploymentFinalizer is the finalizer used by the MachineDeployment controller to + // ensure ordered cleanup of corresponding MachineSets when a MachineDeployment is being deleted. + MachineDeploymentFinalizer = "cluster.x-k8s.io/machinedeployment" +) + +// MachineDeploymentRolloutStrategyType defines the type of MachineDeployment rollout strategies. +// +kubebuilder:validation:Enum=RollingUpdate;OnDelete +type MachineDeploymentRolloutStrategyType string + +const ( + // RollingUpdateMachineDeploymentStrategyType replaces the old MachineSet by new one using rolling update + // i.e. gradually scale down the old MachineSet and scale up the new one. + RollingUpdateMachineDeploymentStrategyType MachineDeploymentRolloutStrategyType = "RollingUpdate" + + // OnDeleteMachineDeploymentStrategyType replaces old MachineSets when the deletion of the associated machines are completed. + OnDeleteMachineDeploymentStrategyType MachineDeploymentRolloutStrategyType = "OnDelete" + + // RevisionAnnotation is the revision annotation of a machine deployment's machine sets which records its rollout sequence. + RevisionAnnotation = "machinedeployment.clusters.x-k8s.io/revision" + + // DesiredReplicasAnnotation is the desired replicas for a machine deployment recorded as an annotation + // in its machine sets. Helps in separating scaling events from the rollout process and for + // determining if the new machine set for a deployment is really saturated. + DesiredReplicasAnnotation = "machinedeployment.clusters.x-k8s.io/desired-replicas" + + // MaxReplicasAnnotation is the maximum replicas a deployment can have at a given point, which + // is machinedeployment.spec.replicas + maxSurge. Used by the underlying machine sets to estimate their + // proportions in case the deployment has surge replicas. + MaxReplicasAnnotation = "machinedeployment.clusters.x-k8s.io/max-replicas" + + // MachineDeploymentUniqueLabel is used to uniquely identify the Machines of a MachineSet. + // The MachineDeployment controller will set this label on a MachineSet when it is created. + // The label is also applied to the Machines of the MachineSet and used in the MachineSet selector. + // Note: For the lifetime of the MachineSet the label's value has to stay the same, otherwise the + // MachineSet selector would no longer match its Machines. + // Note: In previous Cluster API versions (< v1.4.0), the label value was the hash of the full machine template. + // With the introduction of in-place mutation the machine template of the MachineSet can change. + // Because of that it is impossible that the label's value to always be the hash of the full machine template. + // (Because the hash changes when the machine template changes). + // As a result, we use the hash of the machine template while ignoring all in-place mutable fields, i.e. the + // machine template with only fields that could trigger a rollout for the machine-template-hash, making it + // independent of the changes to any in-place mutable fields. + // A random string is appended at the end of the label value (label value format is "-")) + // to distinguish duplicate MachineSets that have the exact same spec but were created as a result of rolloutAfter. + MachineDeploymentUniqueLabel = "machine-template-hash" +) + +// MachineDeployment's Available condition and corresponding reasons. +const ( + // MachineDeploymentAvailableCondition is true if the MachineDeployment is not deleted, and it has minimum + // availability according to parameters specified in the deployment strategy, e.g. If using RollingUpgrade strategy, + // availableReplicas must be greater or equal than desired replicas - MaxUnavailable replicas. + MachineDeploymentAvailableCondition = AvailableCondition + + // MachineDeploymentAvailableWaitingForReplicasSetReason surfaces when the .spec.replicas + // field of the MachineDeployment is not set. + MachineDeploymentAvailableWaitingForReplicasSetReason = WaitingForReplicasSetReason + + // MachineDeploymentAvailableWaitingForAvailableReplicasSetReason surfaces when the .status.v1beta2.availableReplicas + // field of the MachineDeployment is not set. + MachineDeploymentAvailableWaitingForAvailableReplicasSetReason = "WaitingForAvailableReplicasSet" + + // MachineDeploymentAvailableReason surfaces when a Deployment is available. + MachineDeploymentAvailableReason = AvailableReason + + // MachineDeploymentNotAvailableReason surfaces when a Deployment is not available. + MachineDeploymentNotAvailableReason = NotAvailableReason + + // MachineDeploymentAvailableInternalErrorReason surfaces unexpected failures when computing the Available condition. + MachineDeploymentAvailableInternalErrorReason = InternalErrorReason +) + +// MachineDeployment's MachinesReady condition and corresponding reasons. +const ( + // MachineDeploymentMachinesReadyCondition surfaces detail of issues on the controlled machines, if any. + MachineDeploymentMachinesReadyCondition = MachinesReadyCondition + + // MachineDeploymentMachinesReadyReason surfaces when all the controlled machine's Ready conditions are true. + MachineDeploymentMachinesReadyReason = ReadyReason + + // MachineDeploymentMachinesNotReadyReason surfaces when at least one of the controlled machine's Ready conditions is false. + MachineDeploymentMachinesNotReadyReason = NotReadyReason + + // MachineDeploymentMachinesReadyUnknownReason surfaces when at least one of the controlled machine's Ready conditions is unknown + // and none of the controlled machine's Ready conditions is false. + MachineDeploymentMachinesReadyUnknownReason = ReadyUnknownReason + + // MachineDeploymentMachinesReadyNoReplicasReason surfaces when no machines exist for the MachineDeployment. + MachineDeploymentMachinesReadyNoReplicasReason = NoReplicasReason + + // MachineDeploymentMachinesReadyInternalErrorReason surfaces unexpected failures when listing machines + // or aggregating machine's conditions. + MachineDeploymentMachinesReadyInternalErrorReason = InternalErrorReason +) + +// MachineDeployment's MachinesUpToDate condition and corresponding reasons. +const ( + // MachineDeploymentMachinesUpToDateCondition surfaces details of controlled machines not up to date, if any. + // Note: New machines are considered 10s after machine creation. This gives time to the machine's owner controller to recognize the new machine and add the UpToDate condition. + MachineDeploymentMachinesUpToDateCondition = MachinesUpToDateCondition + + // MachineDeploymentMachinesUpToDateReason surfaces when all the controlled machine's UpToDate conditions are true. + MachineDeploymentMachinesUpToDateReason = UpToDateReason + + // MachineDeploymentMachinesNotUpToDateReason surfaces when at least one of the controlled machine's UpToDate conditions is false. + MachineDeploymentMachinesNotUpToDateReason = NotUpToDateReason + + // MachineDeploymentMachinesUpToDateUnknownReason surfaces when at least one of the controlled machine's UpToDate conditions is unknown + // and none of the controlled machine's UpToDate conditions is false. + MachineDeploymentMachinesUpToDateUnknownReason = UpToDateUnknownReason + + // MachineDeploymentMachinesUpToDateNoReplicasReason surfaces when no machines exist for the MachineDeployment. + MachineDeploymentMachinesUpToDateNoReplicasReason = NoReplicasReason + + // MachineDeploymentMachinesUpToDateInternalErrorReason surfaces unexpected failures when listing machines + // or aggregating status. + MachineDeploymentMachinesUpToDateInternalErrorReason = InternalErrorReason +) + +// MachineDeployment's RollingOut condition and corresponding reasons. +const ( + // MachineDeploymentRollingOutCondition is true if there is at least one machine not up-to-date. + MachineDeploymentRollingOutCondition = RollingOutCondition + + // MachineDeploymentRollingOutReason surfaces when there is at least one machine not up-to-date. + MachineDeploymentRollingOutReason = RollingOutReason + + // MachineDeploymentNotRollingOutReason surfaces when all the machines are up-to-date. + MachineDeploymentNotRollingOutReason = NotRollingOutReason + + // MachineDeploymentRollingOutInternalErrorReason surfaces unexpected failures when listing machines. + MachineDeploymentRollingOutInternalErrorReason = InternalErrorReason +) + +// MachineDeployment's ScalingUp condition and corresponding reasons. +const ( + // MachineDeploymentScalingUpCondition is true if actual replicas < desired replicas. + MachineDeploymentScalingUpCondition = ScalingUpCondition + + // MachineDeploymentScalingUpReason surfaces when actual replicas < desired replicas. + MachineDeploymentScalingUpReason = ScalingUpReason + + // MachineDeploymentNotScalingUpReason surfaces when actual replicas >= desired replicas. + MachineDeploymentNotScalingUpReason = NotScalingUpReason + + // MachineDeploymentScalingUpInternalErrorReason surfaces unexpected failures when listing machines. + MachineDeploymentScalingUpInternalErrorReason = InternalErrorReason + + // MachineDeploymentScalingUpWaitingForReplicasSetReason surfaces when the .spec.replicas + // field of the MachineDeployment is not set. + MachineDeploymentScalingUpWaitingForReplicasSetReason = WaitingForReplicasSetReason +) + +// MachineDeployment's ScalingDown condition and corresponding reasons. +const ( + // MachineDeploymentScalingDownCondition is true if actual replicas > desired replicas. + MachineDeploymentScalingDownCondition = ScalingDownCondition + + // MachineDeploymentScalingDownReason surfaces when actual replicas > desired replicas. + MachineDeploymentScalingDownReason = ScalingDownReason + + // MachineDeploymentNotScalingDownReason surfaces when actual replicas <= desired replicas. + MachineDeploymentNotScalingDownReason = NotScalingDownReason + + // MachineDeploymentScalingDownInternalErrorReason surfaces unexpected failures when listing machines. + MachineDeploymentScalingDownInternalErrorReason = InternalErrorReason + + // MachineDeploymentScalingDownWaitingForReplicasSetReason surfaces when the .spec.replicas + // field of the MachineDeployment is not set. + MachineDeploymentScalingDownWaitingForReplicasSetReason = WaitingForReplicasSetReason +) + +// MachineDeployment's Remediating condition and corresponding reasons. +const ( + // MachineDeploymentRemediatingCondition surfaces details about ongoing remediation of the controlled machines, if any. + MachineDeploymentRemediatingCondition = RemediatingCondition + + // MachineDeploymentRemediatingReason surfaces when the MachineDeployment has at least one machine with HealthCheckSucceeded set to false + // and with the OwnerRemediated condition set to false. + MachineDeploymentRemediatingReason = RemediatingReason + + // MachineDeploymentNotRemediatingReason surfaces when the MachineDeployment does not have any machine with HealthCheckSucceeded set to false + // and with the OwnerRemediated condition set to false. + MachineDeploymentNotRemediatingReason = NotRemediatingReason + + // MachineDeploymentRemediatingInternalErrorReason surfaces unexpected failures when computing the Remediating condition. + MachineDeploymentRemediatingInternalErrorReason = InternalErrorReason +) + +// MachineDeployment's Deleting condition and corresponding reasons. +const ( + // MachineDeploymentDeletingCondition surfaces details about ongoing deletion of the controlled machines. + MachineDeploymentDeletingCondition = DeletingCondition + + // MachineDeploymentNotDeletingReason surfaces when the MachineDeployment is not deleting because the + // DeletionTimestamp is not set. + MachineDeploymentNotDeletingReason = NotDeletingReason + + // MachineDeploymentDeletingReason surfaces when the MachineDeployment is deleting because the + // DeletionTimestamp is set. + MachineDeploymentDeletingReason = DeletingReason + + // MachineDeploymentDeletingInternalErrorReason surfaces unexpected failures when deleting a MachineDeployment. + MachineDeploymentDeletingInternalErrorReason = InternalErrorReason +) + +// MachineDeploymentSpec defines the desired state of MachineDeployment. +type MachineDeploymentSpec struct { + // clusterName is the name of the Cluster this object belongs to. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + ClusterName string `json:"clusterName,omitempty"` + + // replicas is the number of desired machines. + // This is a pointer to distinguish between explicit zero and not specified. + // + // Defaults to: + // * if the Kubernetes autoscaler min size and max size annotations are set: + // - if it's a new MachineDeployment, use min size + // - if the replicas field of the old MachineDeployment is < min size, use min size + // - if the replicas field of the old MachineDeployment is > max size, use max size + // - if the replicas field of the old MachineDeployment is in the (min size, max size) range, keep the value from the oldMD + // * otherwise use 1 + // Note: Defaulting will be run whenever the replicas field is not set: + // * A new MachineDeployment is created with replicas not set. + // * On an existing MachineDeployment the replicas field was first set and is now unset. + // Those cases are especially relevant for the following Kubernetes autoscaler use cases: + // * A new MachineDeployment is created and replicas should be managed by the autoscaler + // * An existing MachineDeployment which initially wasn't controlled by the autoscaler + // should be later controlled by the autoscaler + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. + // It allows you to require that all Machines are replaced after a certain time, + // and allows you to define the strategy used during rolling replacements. + // +optional + Rollout MachineDeploymentRolloutSpec `json:"rollout,omitempty,omitzero"` + + // selector is the label selector for machines. Existing MachineSets whose machines are + // selected by this will be the ones affected by this deployment. + // It must match the machine template's labels. + // +required + Selector metav1.LabelSelector `json:"selector,omitempty,omitzero"` + + // template describes the machines that will be created. + // +required + Template MachineTemplateSpec `json:"template,omitempty,omitzero"` + + // machineNaming allows changing the naming pattern used when creating Machines. + // Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines. + // +optional + MachineNaming MachineNamingSpec `json:"machineNaming,omitempty,omitzero"` + + // remediation controls how unhealthy Machines are remediated. + // +optional + Remediation MachineDeploymentRemediationSpec `json:"remediation,omitempty,omitzero"` + + // deletion contains configuration options for MachineDeployment deletion. + // +optional + Deletion MachineDeploymentDeletionSpec `json:"deletion,omitempty,omitzero"` + + // paused indicates that the deployment is paused. + // +optional + Paused *bool `json:"paused,omitempty"` +} + +// MachineDeploymentRolloutSpec defines the rollout behavior. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentRolloutSpec struct { + // after is a field to indicate a rollout should be performed + // after the specified time even if no changes have been made to the + // MachineDeployment. + // Example: In the YAML the time can be specified in the RFC3339 format. + // To specify the rolloutAfter target as March 9, 2023, at 9 am UTC + // use "2023-03-09T09:00:00Z". + // +optional + After metav1.Time `json:"after,omitempty,omitzero"` + + // strategy specifies how to roll out control plane Machines. + // +optional + Strategy MachineDeploymentRolloutStrategy `json:"strategy,omitempty,omitzero"` +} + +// MachineDeploymentRolloutStrategy describes how to replace existing machines +// with new ones. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentRolloutStrategy struct { + // type of rollout. Allowed values are RollingUpdate and OnDelete. + // Default is RollingUpdate. + // +required + Type MachineDeploymentRolloutStrategyType `json:"type,omitempty"` + + // rollingUpdate is the rolling update config params. Present only if + // type = RollingUpdate. + // +optional + RollingUpdate MachineDeploymentRolloutStrategyRollingUpdate `json:"rollingUpdate,omitempty,omitzero"` +} + +// MachineDeploymentRolloutStrategyRollingUpdate is used to control the desired behavior of rolling update. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentRolloutStrategyRollingUpdate struct { + // maxUnavailable is the maximum number of machines that can be unavailable during the update. + // Value can be an absolute number (ex: 5) or a percentage of desired + // machines (ex: 10%). + // Absolute number is calculated from percentage by rounding down. + // This can not be 0 if MaxSurge is 0. + // Defaults to 0. + // Example: when this is set to 30%, the old MachineSet can be scaled + // down to 70% of desired machines immediately when the rolling update + // starts. Once new machines are ready, old MachineSet can be scaled + // down further, followed by scaling up the new MachineSet, ensuring + // that the total number of machines available at all times + // during the update is at least 70% of desired machines. + // +optional + MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty"` + + // maxSurge is the maximum number of machines that can be scheduled above the + // desired number of machines. + // Value can be an absolute number (ex: 5) or a percentage of + // desired machines (ex: 10%). + // This can not be 0 if MaxUnavailable is 0. + // Absolute number is calculated from percentage by rounding up. + // Defaults to 1. + // Example: when this is set to 30%, the new MachineSet can be scaled + // up immediately when the rolling update starts, such that the total + // number of old and new machines do not exceed 130% of desired + // machines. Once old machines have been killed, new MachineSet can + // be scaled up further, ensuring that total number of machines running + // at any time during the update is at most 130% of desired machines. + // +optional + MaxSurge *intstr.IntOrString `json:"maxSurge,omitempty"` +} + +// MachineDeploymentRemediationSpec controls how unhealthy Machines are remediated. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentRemediationSpec struct { + // maxInFlight determines how many in flight remediations should happen at the same time. + // + // Remediation only happens on the MachineSet with the most current revision, while + // older MachineSets (usually present during rollout operations) aren't allowed to remediate. + // + // Note: In general (independent of remediations), unhealthy machines are always + // prioritized during scale down operations over healthy ones. + // + // MaxInFlight can be set to a fixed number or a percentage. + // Example: when this is set to 20%, the MachineSet controller deletes at most 20% of + // the desired replicas. + // + // If not set, remediation is limited to all machines (bounded by replicas) + // under the active MachineSet's management. + // + // +optional + MaxInFlight *intstr.IntOrString `json:"maxInFlight,omitempty"` +} + +// MachineNamingSpec allows changing the naming pattern used when creating +// Machines. +// Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines. +// +kubebuilder:validation:MinProperties=1 +type MachineNamingSpec struct { + // template defines the template to use for generating the names of the + // Machine objects. + // If not defined, it will fallback to `{{ .machineSet.name }}-{{ .random }}`. + // If the generated name string exceeds 63 characters, it will be trimmed to + // 58 characters and will + // get concatenated with a random suffix of length 5. + // Length of the template string must not exceed 256 characters. + // The template allows the following variables `.cluster.name`, + // `.machineSet.name` and `.random`. + // The variable `.cluster.name` retrieves the name of the cluster object + // that owns the Machines being created. + // The variable `.machineSet.name` retrieves the name of the MachineSet + // object that owns the Machines being created. + // The variable `.random` is substituted with random alphanumeric string, + // without vowels, of length 5. This variable is required part of the + // template. If not provided, validation will fail. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=256 + Template string `json:"template,omitempty"` +} + +// MachineDeploymentDeletionSpec contains configuration options for MachineDeployment deletion. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentDeletionSpec struct { + // order defines the order in which Machines are deleted when downscaling. + // Defaults to "Random". Valid values are "Random, "Newest", "Oldest" + // +optional + Order MachineSetDeletionOrder `json:"order,omitempty"` +} + +// MachineDeploymentStatus defines the observed state of MachineDeployment. +// +kubebuilder:validation:MinProperties=1 +type MachineDeploymentStatus struct { + // conditions represents the observations of a MachineDeployment's current state. + // Known condition types are Available, MachinesReady, MachinesUpToDate, ScalingUp, ScalingDown, Remediating, Deleting, Paused. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // observedGeneration is the generation observed by the deployment controller. + // +optional + // +kubebuilder:validation:Minimum=1 + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // selector is the same as the label selector but in the string format to avoid introspection + // by clients. The string will be in the same format as the query-param syntax. + // More info about label selectors: http://kubernetes.io/docs/user-guide/labels#label-selectors + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=4096 + Selector string `json:"selector,omitempty"` + + // replicas is the total number of non-terminated machines targeted by this deployment + // (their labels match the selector). + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // readyReplicas is the number of ready replicas for this MachineDeployment. A machine is considered ready when Machine's Ready condition is true. + // +optional + ReadyReplicas *int32 `json:"readyReplicas,omitempty"` + + // availableReplicas is the number of available replicas for this MachineDeployment. A machine is considered available when Machine's Available condition is true. + // +optional + AvailableReplicas *int32 `json:"availableReplicas,omitempty"` + + // upToDateReplicas is the number of up-to-date replicas targeted by this deployment. A machine is considered up-to-date when Machine's UpToDate condition is true. + // +optional + UpToDateReplicas *int32 `json:"upToDateReplicas,omitempty"` + + // phase represents the current phase of a MachineDeployment (ScalingUp, ScalingDown, Running, Failed, or Unknown). + // +optional + // +kubebuilder:validation:Enum=ScalingUp;ScalingDown;Running;Failed;Unknown + Phase string `json:"phase,omitempty"` + + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. + // +optional + Deprecated *MachineDeploymentDeprecatedStatus `json:"deprecated,omitempty"` +} + +// MachineDeploymentDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachineDeploymentDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + // +optional + V1Beta1 *MachineDeploymentV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` +} + +// MachineDeploymentV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachineDeploymentV1Beta1DeprecatedStatus struct { + // conditions defines current service state of the MachineDeployment. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + Conditions Conditions `json:"conditions,omitempty"` + + // updatedReplicas is the total number of non-terminated machines targeted by this deployment + // that have the desired template spec. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + UpdatedReplicas int32 `json:"updatedReplicas"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // readyReplicas is the total number of ready machines targeted by this deployment. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + ReadyReplicas int32 `json:"readyReplicas"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // availableReplicas is the total number of available machines (ready for at least minReadySeconds) + // targeted by this deployment. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + AvailableReplicas int32 `json:"availableReplicas"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // unavailableReplicas is the total number of unavailable machines targeted by this deployment. + // This is the total number of machines that are still required for + // the deployment to have 100% available capacity. They may either + // be machines that are running but not yet available or machines + // that still have not been created. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + UnavailableReplicas int32 `json:"unavailableReplicas"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed +} + +// MachineDeploymentPhase indicates the progress of the machine deployment. +type MachineDeploymentPhase string + +const ( + // MachineDeploymentPhaseScalingUp indicates the MachineDeployment is scaling up. + MachineDeploymentPhaseScalingUp = MachineDeploymentPhase("ScalingUp") + + // MachineDeploymentPhaseScalingDown indicates the MachineDeployment is scaling down. + MachineDeploymentPhaseScalingDown = MachineDeploymentPhase("ScalingDown") + + // MachineDeploymentPhaseRunning indicates scaling has completed and all Machines are running. + MachineDeploymentPhaseRunning = MachineDeploymentPhase("Running") + + // MachineDeploymentPhaseFailed indicates there was a problem scaling and user intervention might be required. + // + // Deprecated: This enum value is deprecated; the Failed phase won't be set anymore by controllers, and it is preserved only + // for conversion from v1beta1 objects; the Failed phase is going to be removed when support for v1beta1 will be dropped. + // Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + MachineDeploymentPhaseFailed = MachineDeploymentPhase("Failed") + + // MachineDeploymentPhaseUnknown indicates the state of the MachineDeployment cannot be determined. + MachineDeploymentPhaseUnknown = MachineDeploymentPhase("Unknown") +) + +// SetTypedPhase sets the Phase field to the string representation of MachineDeploymentPhase. +func (md *MachineDeploymentStatus) SetTypedPhase(p MachineDeploymentPhase) { + md.Phase = string(p) +} + +// GetTypedPhase attempts to parse the Phase field and return +// the typed MachineDeploymentPhase representation. +func (md *MachineDeploymentStatus) GetTypedPhase() MachineDeploymentPhase { + switch phase := MachineDeploymentPhase(md.Phase); phase { + case + MachineDeploymentPhaseScalingDown, + MachineDeploymentPhaseScalingUp, + MachineDeploymentPhaseRunning, + MachineDeploymentPhaseFailed: + return phase + default: + return MachineDeploymentPhaseUnknown + } +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=machinedeployments,shortName=md,scope=Namespaced,categories=cluster-api +// +kubebuilder:storageversion +// +kubebuilder:subresource:status +// +kubebuilder:subresource:scale:specpath=.spec.replicas,statuspath=.status.replicas,selectorpath=.status.selector +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" +// +kubebuilder:printcolumn:name="Available",type="string",JSONPath=`.status.conditions[?(@.type=="Available")].status`,description="Cluster pass all availability checks" +// +kubebuilder:printcolumn:name="Desired",type=integer,JSONPath=".spec.replicas",description="The desired number of machines" +// +kubebuilder:printcolumn:name="Current",type="integer",JSONPath=".status.replicas",description="The number of machines" +// +kubebuilder:printcolumn:name="Ready",type="integer",JSONPath=".status.readyReplicas",description="The number of machines with Ready condition true" +// +kubebuilder:printcolumn:name="Available",type=integer,JSONPath=".status.availableReplicas",description="The number of machines with Available condition true" +// +kubebuilder:printcolumn:name="Up-to-date",type=integer,JSONPath=".status.upToDateReplicas",description="The number of machines with UpToDate condition true" +// +kubebuilder:printcolumn:name="Paused",type="string",JSONPath=`.status.conditions[?(@.type=="Paused")].status`,description="Reconciliation paused",priority=10 +// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase",description="MachineDeployment status such as ScalingUp/ScalingDown/Running/Failed/Unknown" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of MachineDeployment" +// +kubebuilder:printcolumn:name="Version",type="string",JSONPath=".spec.template.spec.version",description="Kubernetes version associated with this MachineDeployment" + +// MachineDeployment is the Schema for the machinedeployments API. +type MachineDeployment struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is the desired state of MachineDeployment. + // +required + Spec MachineDeploymentSpec `json:"spec,omitempty,omitzero"` + // status is the observed state of MachineDeployment. + // +optional + Status MachineDeploymentStatus `json:"status,omitempty,omitzero"` +} + +// +kubebuilder:object:root=true + +// MachineDeploymentList contains a list of MachineDeployment. +type MachineDeploymentList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + // items is the list of MachineDeployments. + Items []MachineDeployment `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &MachineDeployment{}, &MachineDeploymentList{}) +} + +// GetV1Beta1Conditions returns the set of conditions for the machinedeployment. +func (m *MachineDeployment) GetV1Beta1Conditions() Conditions { + if m.Status.Deprecated == nil || m.Status.Deprecated.V1Beta1 == nil { + return nil + } + return m.Status.Deprecated.V1Beta1.Conditions +} + +// SetV1Beta1Conditions updates the set of conditions on the machinedeployment. +func (m *MachineDeployment) SetV1Beta1Conditions(conditions Conditions) { + if m.Status.Deprecated == nil { + m.Status.Deprecated = &MachineDeploymentDeprecatedStatus{} + } + if m.Status.Deprecated.V1Beta1 == nil { + m.Status.Deprecated.V1Beta1 = &MachineDeploymentV1Beta1DeprecatedStatus{} + } + m.Status.Deprecated.V1Beta1.Conditions = conditions +} + +// GetConditions returns the set of conditions for this object. +func (m *MachineDeployment) GetConditions() []metav1.Condition { + return m.Status.Conditions +} + +// SetConditions sets conditions for an API object. +func (m *MachineDeployment) SetConditions(conditions []metav1.Condition) { + m.Status.Conditions = conditions +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinedrainrules_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinedrainrules_types.go new file mode 100644 index 000000000000..baac401f0d71 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinedrainrules_types.go @@ -0,0 +1,235 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + // PodDrainLabel is the label that can be set on Pods in workload clusters to ensure a Pod is not drained. + // The only valid values are "skip" and "wait-completed". + // This label takes precedence over MachineDrainRules defined in the management cluster. + PodDrainLabel = "cluster.x-k8s.io/drain" +) + +// MachineDrainRuleDrainBehavior defines the drain behavior. Can be either "Drain", "Skip", or "WaitCompleted". +// +kubebuilder:validation:Enum=Drain;Skip;WaitCompleted +type MachineDrainRuleDrainBehavior string + +const ( + // MachineDrainRuleDrainBehaviorDrain means a Pod should be drained. + MachineDrainRuleDrainBehaviorDrain MachineDrainRuleDrainBehavior = "Drain" + + // MachineDrainRuleDrainBehaviorSkip means the drain for a Pod should be skipped. + MachineDrainRuleDrainBehaviorSkip MachineDrainRuleDrainBehavior = "Skip" + + // MachineDrainRuleDrainBehaviorWaitCompleted means the Pod should not be evicted, + // but overall drain should wait until the Pod completes. + MachineDrainRuleDrainBehaviorWaitCompleted MachineDrainRuleDrainBehavior = "WaitCompleted" +) + +// MachineDrainRuleSpec defines the spec of a MachineDrainRule. +type MachineDrainRuleSpec struct { + // drain configures if and how Pods are drained. + // +required + Drain MachineDrainRuleDrainConfig `json:"drain,omitempty,omitzero"` + + // machines defines to which Machines this MachineDrainRule should be applied. + // + // If machines is not set, the MachineDrainRule applies to all Machines in the Namespace. + // If machines contains multiple selectors, the results are ORed. + // Within a single Machine selector the results of selector and clusterSelector are ANDed. + // Machines will be selected from all Clusters in the Namespace unless otherwise + // restricted with the clusterSelector. + // + // Example: Selects control plane Machines in all Clusters or + // Machines with label "os" == "linux" in Clusters with label + // "stage" == "production". + // + // - selector: + // matchExpressions: + // - key: cluster.x-k8s.io/control-plane + // operator: Exists + // - selector: + // matchLabels: + // os: linux + // clusterSelector: + // matchExpressions: + // - key: stage + // operator: In + // values: + // - production + // + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + // +kubebuilder:validation:XValidation:rule="self.all(x, self.exists_one(y, x == y))",message="entries in machines must be unique" + Machines []MachineDrainRuleMachineSelector `json:"machines,omitempty"` + + // pods defines to which Pods this MachineDrainRule should be applied. + // + // If pods is not set, the MachineDrainRule applies to all Pods in all Namespaces. + // If pods contains multiple selectors, the results are ORed. + // Within a single Pod selector the results of selector and namespaceSelector are ANDed. + // Pods will be selected from all Namespaces unless otherwise + // restricted with the namespaceSelector. + // + // Example: Selects Pods with label "app" == "logging" in all Namespaces or + // Pods with label "app" == "prometheus" in the "monitoring" + // Namespace. + // + // - selector: + // matchExpressions: + // - key: app + // operator: In + // values: + // - logging + // - selector: + // matchLabels: + // app: prometheus + // namespaceSelector: + // matchLabels: + // kubernetes.io/metadata.name: monitoring + // + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=32 + // +kubebuilder:validation:XValidation:rule="self.all(x, self.exists_one(y, x == y))",message="entries in pods must be unique" + Pods []MachineDrainRulePodSelector `json:"pods,omitempty"` +} + +// MachineDrainRuleDrainConfig configures if and how Pods are drained. +type MachineDrainRuleDrainConfig struct { + // behavior defines the drain behavior. + // Can be either "Drain", "Skip", or "WaitCompleted". + // "Drain" means that the Pods to which this MachineDrainRule applies will be drained. + // If behavior is set to "Drain" the order in which Pods are drained can be configured + // with the order field. When draining Pods of a Node the Pods will be grouped by order + // and one group after another will be drained (by increasing order). Cluster API will + // wait until all Pods of a group are terminated / removed from the Node before starting + // with the next group. + // "Skip" means that the Pods to which this MachineDrainRule applies will be skipped during drain. + // "WaitCompleted" means that the pods to which this MachineDrainRule applies will never be evicted + // and we wait for them to be completed, it is enforced that pods marked with this behavior always have Order=0. + // +required + Behavior MachineDrainRuleDrainBehavior `json:"behavior,omitempty"` + + // order defines the order in which Pods are drained. + // Pods with higher order are drained after Pods with lower order. + // order can only be set if behavior is set to "Drain". + // If order is not set, 0 will be used. + // Valid values for order are from -2147483648 to 2147483647 (inclusive). + // +optional + Order *int32 `json:"order,omitempty"` +} + +// MachineDrainRuleMachineSelector defines to which Machines this MachineDrainRule should be applied. +// +kubebuilder:validation:MinProperties=1 +type MachineDrainRuleMachineSelector struct { + // selector is a label selector which selects Machines by their labels. + // This field follows standard label selector semantics; if not present or + // empty, it selects all Machines. + // + // If clusterSelector is also set, then the selector as a whole selects + // Machines matching selector belonging to Clusters selected by clusterSelector. + // If clusterSelector is not set, it selects all Machines matching selector in + // all Clusters. + // +optional + Selector *metav1.LabelSelector `json:"selector,omitempty"` + + // clusterSelector is a label selector which selects Machines by the labels of + // their Clusters. + // This field follows standard label selector semantics; if not present or + // empty, it selects Machines of all Clusters. + // + // If selector is also set, then the selector as a whole selects + // Machines matching selector belonging to Clusters selected by clusterSelector. + // If selector is not set, it selects all Machines belonging to Clusters + // selected by clusterSelector. + // +optional + ClusterSelector *metav1.LabelSelector `json:"clusterSelector,omitempty"` +} + +// MachineDrainRulePodSelector defines to which Pods this MachineDrainRule should be applied. +// +kubebuilder:validation:MinProperties=1 +type MachineDrainRulePodSelector struct { + // selector is a label selector which selects Pods by their labels. + // This field follows standard label selector semantics; if not present or + // empty, it selects all Pods. + // + // If namespaceSelector is also set, then the selector as a whole selects + // Pods matching selector in Namespaces selected by namespaceSelector. + // If namespaceSelector is not set, it selects all Pods matching selector in + // all Namespaces. + // +optional + Selector *metav1.LabelSelector `json:"selector,omitempty"` + + // namespaceSelector is a label selector which selects Pods by the labels of + // their Namespaces. + // This field follows standard label selector semantics; if not present or + // empty, it selects Pods of all Namespaces. + // + // If selector is also set, then the selector as a whole selects + // Pods matching selector in Namespaces selected by namespaceSelector. + // If selector is not set, it selects all Pods in Namespaces selected by + // namespaceSelector. + // +optional + NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=machinedrainrules,scope=Namespaced,categories=cluster-api +// +kubebuilder:storageversion +// +kubebuilder:printcolumn:name="Behavior",type="string",JSONPath=".spec.drain.behavior",description="Drain behavior" +// +kubebuilder:printcolumn:name="Order",type="string",JSONPath=".spec.drain.order",description="Drain order" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of the MachineDrainRule" + +// MachineDrainRule is the Schema for the MachineDrainRule API. +type MachineDrainRule struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +required + metav1.ObjectMeta `json:"metadata"` + + // spec defines the spec of a MachineDrainRule. + // +required + Spec MachineDrainRuleSpec `json:"spec,omitempty,omitzero"` +} + +// +kubebuilder:object:root=true + +// MachineDrainRuleList contains a list of MachineDrainRules. +type MachineDrainRuleList struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +required + metav1.ListMeta `json:"metadata"` + + // items contains the items of the MachineDrainRuleList. + Items []MachineDrainRule `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &MachineDrainRule{}, &MachineDrainRuleList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinehealthcheck_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinehealthcheck_types.go new file mode 100644 index 000000000000..9a7e31cae44d --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinehealthcheck_types.go @@ -0,0 +1,372 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/intstr" +) + +// MachineHealthCheck's RemediationAllowed condition and corresponding reasons. +const ( + // MachineHealthCheckRemediationAllowedCondition surfaces whether the MachineHealthCheck is + // allowed to remediate any Machines or whether it is blocked from remediating any further. + MachineHealthCheckRemediationAllowedCondition = "RemediationAllowed" + + // MachineHealthCheckTooManyUnhealthyReason is the reason used when too many Machines are unhealthy and + // the MachineHealthCheck is blocked from making any further remediation. + MachineHealthCheckTooManyUnhealthyReason = "TooManyUnhealthy" + + // MachineHealthCheckRemediationAllowedReason is the reason used when the number of unhealthy machine + // is within the limits defined by the MachineHealthCheck, and thus remediation is allowed. + MachineHealthCheckRemediationAllowedReason = "RemediationAllowed" +) + +var ( + // DefaultNodeStartupTimeoutSeconds is the time allowed for a node to start up. + // Can be made longer as part of spec if required for particular provider. + // 10 minutes should allow the instance to start and the node to join the + // cluster on most providers. + DefaultNodeStartupTimeoutSeconds = int32(600) +) + +// MachineHealthCheckSpec defines the desired state of MachineHealthCheck. +type MachineHealthCheckSpec struct { + // clusterName is the name of the Cluster this object belongs to. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + ClusterName string `json:"clusterName,omitempty"` + + // selector is a label selector to match machines whose health will be exercised + // +required + Selector metav1.LabelSelector `json:"selector,omitempty,omitzero"` + + // checks are the checks that are used to evaluate if a Machine is healthy. + // + // Independent of this configuration the MachineHealthCheck controller will always + // flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and + // Machines with deleted Nodes as unhealthy. + // + // Furthermore, if checks.nodeStartupTimeoutSeconds is not set it + // is defaulted to 10 minutes and evaluated accordingly. + // + // +optional + Checks MachineHealthCheckChecks `json:"checks,omitempty,omitzero"` + + // remediation configures if and how remediations are triggered if a Machine is unhealthy. + // + // If remediation or remediation.triggerIf is not set, + // remediation will always be triggered for unhealthy Machines. + // + // If remediation or remediation.templateRef is not set, + // the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via + // the owner of the Machines, for example a MachineSet or a KubeadmControlPlane. + // + // +optional + Remediation MachineHealthCheckRemediation `json:"remediation,omitempty,omitzero"` +} + +// MachineHealthCheckChecks are the checks that are used to evaluate if a Machine is healthy. +// +kubebuilder:validation:MinProperties=1 +type MachineHealthCheckChecks struct { + // nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck + // to consider a Machine unhealthy if a corresponding Node isn't associated + // through a `Spec.ProviderID` field. + // + // The duration set in this field is compared to the greatest of: + // - Cluster's infrastructure ready condition timestamp (if and when available) + // - Control Plane's initialized condition timestamp (if and when available) + // - Machine's infrastructure ready condition timestamp (if and when available) + // - Machine's metadata creation timestamp + // + // Defaults to 10 minutes. + // If you wish to disable this feature, set the value explicitly to 0. + // +optional + // +kubebuilder:validation:Minimum=0 + NodeStartupTimeoutSeconds *int32 `json:"nodeStartupTimeoutSeconds,omitempty"` + + // unhealthyNodeConditions contains a list of conditions that determine + // whether a node is considered unhealthy. The conditions are combined in a + // logical OR, i.e. if any of the conditions is met, the node is unhealthy. + // + // +optional + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:MaxItems=100 + UnhealthyNodeConditions []UnhealthyNodeCondition `json:"unhealthyNodeConditions,omitempty"` +} + +// MachineHealthCheckRemediation configures if and how remediations are triggered if a Machine is unhealthy. +// +kubebuilder:validation:MinProperties=1 +type MachineHealthCheckRemediation struct { + // triggerIf configures if remediations are triggered. + // If this field is not set, remediations are always triggered. + // +optional + TriggerIf MachineHealthCheckRemediationTriggerIf `json:"triggerIf,omitempty,omitzero"` + + // templateRef is a reference to a remediation template + // provided by an infrastructure provider. + // + // This field is completely optional, when filled, the MachineHealthCheck controller + // creates a new object from the template referenced and hands off remediation of the machine to + // a controller that lives outside of Cluster API. + // +optional + TemplateRef MachineHealthCheckRemediationTemplateReference `json:"templateRef,omitempty,omitzero"` +} + +// MachineHealthCheckRemediationTriggerIf configures if remediations are triggered. +// +kubebuilder:validation:MinProperties=1 +type MachineHealthCheckRemediationTriggerIf struct { + // unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of + // unhealthy Machines is less than or equal to the configured value. + // unhealthyInRange takes precedence if set. + // + // +optional + UnhealthyLessThanOrEqualTo *intstr.IntOrString `json:"unhealthyLessThanOrEqualTo,omitempty"` + + // unhealthyInRange specifies that remediations are only triggered if the number of + // unhealthy Machines is in the configured range. + // Takes precedence over unhealthyLessThanOrEqualTo. + // Eg. "[3-5]" - This means that remediation will be allowed only when: + // (a) there are at least 3 unhealthy Machines (and) + // (b) there are at most 5 unhealthy Machines + // + // +optional + // +kubebuilder:validation:Pattern=^\[[0-9]+-[0-9]+\]$ + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=32 + UnhealthyInRange string `json:"unhealthyInRange,omitempty"` +} + +// MachineHealthCheckRemediationTemplateReference is a reference to a remediation template. +type MachineHealthCheckRemediationTemplateReference struct { + // kind of the remediation template. + // kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$` + Kind string `json:"kind,omitempty"` + + // name of the remediation template. + // name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` + + // apiVersion of the remediation template. + // apiVersion must be fully qualified domain name followed by / and a version. + // NOTE: This field must be kept in sync with the APIVersion of the remediation template. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=317 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[a-z]([-a-z0-9]*[a-z0-9])?$` + APIVersion string `json:"apiVersion,omitempty"` +} + +// IsDefined returns true if the MachineHealthCheckRemediationTemplateReference is set. +func (r *MachineHealthCheckRemediationTemplateReference) IsDefined() bool { + if r == nil { + return false + } + return r.Kind != "" || r.Name != "" || r.APIVersion != "" +} + +// ToObjectReference returns an object reference for the MachineHealthCheckRemediationTemplateReference in a given namespace. +func (r *MachineHealthCheckRemediationTemplateReference) ToObjectReference(namespace string) *corev1.ObjectReference { + if r == nil { + return nil + } + return &corev1.ObjectReference{ + APIVersion: r.APIVersion, + Kind: r.Kind, + Namespace: namespace, + Name: r.Name, + } +} + +// GroupVersionKind gets the GroupVersionKind for a MachineHealthCheckRemediationTemplateReference. +func (r *MachineHealthCheckRemediationTemplateReference) GroupVersionKind() schema.GroupVersionKind { + return schema.FromAPIVersionAndKind(r.APIVersion, r.Kind) +} + +// UnhealthyNodeCondition represents a Node condition type and value with a timeout +// specified as a duration. When the named condition has been in the given +// status for at least the timeout value, a node is considered unhealthy. +type UnhealthyNodeCondition struct { + // type of Node condition + // +kubebuilder:validation:Type=string + // +kubebuilder:validation:MinLength=1 + // +required + Type corev1.NodeConditionType `json:"type,omitempty"` + + // status of the condition, one of True, False, Unknown. + // +kubebuilder:validation:Type=string + // +kubebuilder:validation:MinLength=1 + // +required + Status corev1.ConditionStatus `json:"status,omitempty"` + + // timeoutSeconds is the duration that a node must be in a given status for, + // after which the node is considered unhealthy. + // For example, with a value of "1h", the node must match the status + // for at least 1 hour before being considered unhealthy. + // +required + // +kubebuilder:validation:Minimum=0 + TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty"` +} + +// MachineHealthCheckStatus defines the observed state of MachineHealthCheck. +// +kubebuilder:validation:MinProperties=1 +type MachineHealthCheckStatus struct { + // conditions represents the observations of a MachineHealthCheck's current state. + // Known condition types are RemediationAllowed, Paused. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // expectedMachines is the total number of machines counted by this machine health check + // +kubebuilder:validation:Minimum=0 + // +optional + ExpectedMachines *int32 `json:"expectedMachines,omitempty"` + + // currentHealthy is the total number of healthy machines counted by this machine health check + // +kubebuilder:validation:Minimum=0 + // +optional + CurrentHealthy *int32 `json:"currentHealthy,omitempty"` + + // remediationsAllowed is the number of further remediations allowed by this machine health check before + // maxUnhealthy short circuiting will be applied + // +kubebuilder:validation:Minimum=0 + // +optional + RemediationsAllowed *int32 `json:"remediationsAllowed,omitempty"` + + // observedGeneration is the latest generation observed by the controller. + // +optional + // +kubebuilder:validation:Minimum=1 + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // targets shows the current list of machines the machine health check is watching + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=10000 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=253 + Targets []string `json:"targets,omitempty"` + + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. + // +optional + Deprecated *MachineHealthCheckDeprecatedStatus `json:"deprecated,omitempty"` +} + +// MachineHealthCheckDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachineHealthCheckDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + // +optional + V1Beta1 *MachineHealthCheckV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` +} + +// MachineHealthCheckV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachineHealthCheckV1Beta1DeprecatedStatus struct { + // conditions defines current service state of the MachineHealthCheck. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + Conditions Conditions `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=machinehealthchecks,shortName=mhc;mhcs,scope=Namespaced,categories=cluster-api +// +kubebuilder:storageversion +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" +// +kubebuilder:printcolumn:name="Replicas",type="integer",JSONPath=".status.expectedMachines",description="Number of machines currently monitored" +// +kubebuilder:printcolumn:name="Healthy",type="integer",JSONPath=".status.currentHealthy",description="Current observed healthy machines" +// +kubebuilder:printcolumn:name="Paused",type="string",JSONPath=`.status.conditions[?(@.type=="Paused")].status`,description="Reconciliation paused",priority=10 +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of MachineHealthCheck" + +// MachineHealthCheck is the Schema for the machinehealthchecks API. +type MachineHealthCheck struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is the specification of machine health check policy + // +required + Spec MachineHealthCheckSpec `json:"spec,omitempty,omitzero"` + + // status is the most recently observed status of MachineHealthCheck resource + // +optional + Status MachineHealthCheckStatus `json:"status,omitempty,omitzero"` +} + +// GetV1Beta1Conditions returns the set of conditions for this object. +func (m *MachineHealthCheck) GetV1Beta1Conditions() Conditions { + if m.Status.Deprecated == nil || m.Status.Deprecated.V1Beta1 == nil { + return nil + } + return m.Status.Deprecated.V1Beta1.Conditions +} + +// SetV1Beta1Conditions sets the conditions on this object. +func (m *MachineHealthCheck) SetV1Beta1Conditions(conditions Conditions) { + if m.Status.Deprecated == nil { + m.Status.Deprecated = &MachineHealthCheckDeprecatedStatus{} + } + if m.Status.Deprecated.V1Beta1 == nil { + m.Status.Deprecated.V1Beta1 = &MachineHealthCheckV1Beta1DeprecatedStatus{} + } + m.Status.Deprecated.V1Beta1.Conditions = conditions +} + +// GetConditions returns the set of conditions for this object. +func (m *MachineHealthCheck) GetConditions() []metav1.Condition { + return m.Status.Conditions +} + +// SetConditions sets conditions for an API object. +func (m *MachineHealthCheck) SetConditions(conditions []metav1.Condition) { + m.Status.Conditions = conditions +} + +// +kubebuilder:object:root=true + +// MachineHealthCheckList contains a list of MachineHealthCheck. +type MachineHealthCheckList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + // items is the list of MachineHealthChecks. + Items []MachineHealthCheck `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &MachineHealthCheck{}, &MachineHealthCheckList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinepool_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinepool_types.go new file mode 100644 index 000000000000..a6d16aff1467 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machinepool_types.go @@ -0,0 +1,398 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + capierrors "sigs.k8s.io/cluster-api/errors" +) + +const ( + // MachinePoolFinalizer is used to ensure deletion of dependencies (nodes, infra). + MachinePoolFinalizer = "machinepool.cluster.x-k8s.io" +) + +/* +NOTE: we are commenting const for MachinePool's V1Beta2 conditions and reasons because not yet implemented for the 1.9 CAPI release. +However, we are keeping the v1beta2 struct in the MachinePool struct because the code that will collect conditions and replica +counters at cluster level is already implemented. + +// Conditions that will be used for the MachinePool object in v1Beta2 API version. +const ( + // MachinePoolAvailableCondition is true when InfrastructureReady and available replicas >= desired replicas. + MachinePoolAvailableCondition = clusterv1.AvailableCondition + + // MachinePoolBootstrapConfigReadyCondition mirrors the corresponding condition from the MachinePool's BootstrapConfig resource. + MachinePoolBootstrapConfigReadyCondition = clusterv1.BootstrapConfigReadyCondition + + // MachinePoolInfrastructureReadyCondition mirrors the corresponding condition from the MachinePool's Infrastructure resource. + MachinePoolInfrastructureReadyCondition = clusterv1.InfrastructureReadyCondition + + // MachinePoolMachinesReadyCondition surfaces detail of issues on the controlled machines, if any. + MachinePoolMachinesReadyCondition = clusterv1.MachinesReadyCondition + + // MachinePoolMachinesUpToDateCondition surfaces details of controlled machines not up to date, if any. + MachinePoolMachinesUpToDateCondition = clusterv1.MachinesUpToDateCondition + + // MachinePoolScalingUpCondition is true if available replicas < desired replicas. + MachinePoolScalingUpCondition = clusterv1.ScalingUpCondition + + // MachinePoolScalingDownCondition is true if replicas > desired replicas. + MachinePoolScalingDownCondition = clusterv1.ScalingDownCondition + + // MachinePoolRemediatingCondition surfaces details about ongoing remediation of the controlled machines, if any. + MachinePoolRemediatingCondition = clusterv1.RemediatingCondition + + // MachinePoolDeletingCondition surfaces details about ongoing deletion of the controlled machines. + MachinePoolDeletingCondition = clusterv1.DeletingCondition +). +*/ + +// MachinePoolSpec defines the desired state of MachinePool. +type MachinePoolSpec struct { + // clusterName is the name of the Cluster this object belongs to. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + ClusterName string `json:"clusterName,omitempty"` + + // replicas is the number of desired machines. Defaults to 1. + // This is a pointer to distinguish between explicit zero and not specified. + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // template describes the machines that will be created. + // +required + Template MachineTemplateSpec `json:"template,omitempty,omitzero"` + + // providerIDList are the identification IDs of machine instances provided by the provider. + // This field must match the provider IDs as seen on the node objects corresponding to a machine pool's machine instances. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=10000 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=512 + ProviderIDList []string `json:"providerIDList,omitempty"` + + // failureDomains is the list of failure domains this MachinePool should be attached to. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=100 + // +kubebuilder:validation:items:MinLength=1 + // +kubebuilder:validation:items:MaxLength=256 + FailureDomains []string `json:"failureDomains,omitempty"` +} + +// MachinePoolStatus defines the observed state of MachinePool. +// +kubebuilder:validation:MinProperties=1 +type MachinePoolStatus struct { + // conditions represents the observations of a MachinePool's current state. + // Known condition types are Available, BootstrapConfigReady, InfrastructureReady, MachinesReady, MachinesUpToDate, + // ScalingUp, ScalingDown, Remediating, Deleting, Paused. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // initialization provides observations of the MachinePool initialization process. + // NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial MachinePool provisioning. + // +optional + Initialization MachinePoolInitializationStatus `json:"initialization,omitempty,omitzero"` + + // nodeRefs will point to the corresponding Nodes if it they exist. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=10000 + NodeRefs []corev1.ObjectReference `json:"nodeRefs,omitempty"` + + // replicas is the most recently observed number of replicas. + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // readyReplicas is the number of ready replicas for this MachinePool. A machine is considered ready when Machine's Ready condition is true. + // +optional + ReadyReplicas *int32 `json:"readyReplicas,omitempty"` + + // availableReplicas is the number of available replicas for this MachinePool. A machine is considered available when Machine's Available condition is true. + // +optional + AvailableReplicas *int32 `json:"availableReplicas,omitempty"` + + // upToDateReplicas is the number of up-to-date replicas targeted by this MachinePool. A machine is considered up-to-date when Machine's UpToDate condition is true. + // +optional + UpToDateReplicas *int32 `json:"upToDateReplicas,omitempty"` + + // phase represents the current phase of cluster actuation. + // +optional + // +kubebuilder:validation:Enum=Pending;Provisioning;Provisioned;Running;ScalingUp;ScalingDown;Scaling;Deleting;Failed;Unknown + Phase string `json:"phase,omitempty"` + + // observedGeneration is the latest generation observed by the controller. + // +optional + // +kubebuilder:validation:Minimum=1 + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. + // +optional + Deprecated *MachinePoolDeprecatedStatus `json:"deprecated,omitempty"` +} + +// MachinePoolInitializationStatus provides observations of the MachinePool initialization process. +// NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial MachinePool provisioning. +// +kubebuilder:validation:MinProperties=1 +type MachinePoolInitializationStatus struct { + // infrastructureProvisioned is true when the infrastructure provider reports that MachinePool's infrastructure is fully provisioned. + // NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + // The value of this field is never updated after provisioning is completed. + // +optional + InfrastructureProvisioned *bool `json:"infrastructureProvisioned,omitempty"` + + // bootstrapDataSecretCreated is true when the bootstrap provider reports that the MachinePool's boostrap secret is created. + // NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. + // The value of this field is never updated after provisioning is completed. + // +optional + BootstrapDataSecretCreated *bool `json:"bootstrapDataSecretCreated,omitempty"` +} + +// MachinePoolDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachinePoolDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + // +optional + V1Beta1 *MachinePoolV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` +} + +// MachinePoolV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachinePoolV1Beta1DeprecatedStatus struct { + // conditions define the current service state of the MachinePool. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + Conditions Conditions `json:"conditions,omitempty"` + + // failureReason indicates that there is a problem reconciling the state, and + // will be set to a token value suitable for programmatic interpretation. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + FailureReason *capierrors.MachinePoolStatusFailure `json:"failureReason,omitempty"` + + // failureMessage indicates that there is a problem reconciling the state, + // and will be set to a descriptive error message. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=10240 + FailureMessage *string `json:"failureMessage,omitempty"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // readyReplicas is the number of ready replicas for this MachinePool. A machine is considered ready when the node has been created and is "Ready". + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + ReadyReplicas int32 `json:"readyReplicas,omitempty"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // availableReplicas is the number of available replicas (ready for at least minReadySeconds) for this MachinePool. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + AvailableReplicas int32 `json:"availableReplicas,omitempty"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // unavailableReplicas is the total number of unavailable machine instances targeted by this machine pool. + // This is the total number of machine instances that are still required for + // the machine pool to have 100% available capacity. They may either + // be machine instances that are running but not yet available or machine instances + // that still have not been created. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + UnavailableReplicas int32 `json:"unavailableReplicas,omitempty"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed +} + +// MachinePoolPhase is a string representation of a MachinePool Phase. +// +// This type is a high-level indicator of the status of the MachinePool as it is provisioned, +// from the API user’s perspective. +// +// The value should not be interpreted by any software components as a reliable indication +// of the actual state of the MachinePool, and controllers should not use the MachinePool Phase field +// value when making decisions about what action to take. +// +// Controllers should always look at the actual state of the MachinePool’s fields to make those decisions. +type MachinePoolPhase string + +const ( + // MachinePoolPhasePending is the first state a MachinePool is assigned by + // Cluster API MachinePool controller after being created. + MachinePoolPhasePending = MachinePoolPhase("Pending") + + // MachinePoolPhaseProvisioning is the state when the + // MachinePool infrastructure is being created or updated. + MachinePoolPhaseProvisioning = MachinePoolPhase("Provisioning") + + // MachinePoolPhaseProvisioned is the state when its + // infrastructure has been created and configured. + MachinePoolPhaseProvisioned = MachinePoolPhase("Provisioned") + + // MachinePoolPhaseRunning is the MachinePool state when its instances + // have become Kubernetes Nodes in the Ready state. + MachinePoolPhaseRunning = MachinePoolPhase("Running") + + // MachinePoolPhaseScalingUp is the MachinePool state when the + // MachinePool infrastructure is scaling up. + MachinePoolPhaseScalingUp = MachinePoolPhase("ScalingUp") + + // MachinePoolPhaseScalingDown is the MachinePool state when the + // MachinePool infrastructure is scaling down. + MachinePoolPhaseScalingDown = MachinePoolPhase("ScalingDown") + + // MachinePoolPhaseScaling is the MachinePool state when the + // MachinePool infrastructure is scaling. + // This phase value is appropriate to indicate an active state of scaling by an external autoscaler. + MachinePoolPhaseScaling = MachinePoolPhase("Scaling") + + // MachinePoolPhaseDeleting is the MachinePool state when a delete + // request has been sent to the API Server, + // but its infrastructure has not yet been fully deleted. + MachinePoolPhaseDeleting = MachinePoolPhase("Deleting") + + // MachinePoolPhaseFailed is the MachinePool state when the system + // might require user intervention. + // + // Deprecated: This enum value is deprecated; the Failed phase won't be set anymore by controllers, and it is preserved only + // for conversion from v1beta1 objects; the Failed phase is going to be removed when support for v1beta1 will be dropped. + // Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + MachinePoolPhaseFailed = MachinePoolPhase("Failed") + + // MachinePoolPhaseUnknown is returned if the MachinePool state cannot be determined. + MachinePoolPhaseUnknown = MachinePoolPhase("Unknown") +) + +// SetTypedPhase sets the Phase field to the string representation of MachinePoolPhase. +func (m *MachinePoolStatus) SetTypedPhase(p MachinePoolPhase) { + m.Phase = string(p) +} + +// GetTypedPhase attempts to parse the Phase field and return +// the typed MachinePoolPhase representation as described in `machinepool_phase_types.go`. +func (m *MachinePoolStatus) GetTypedPhase() MachinePoolPhase { + switch phase := MachinePoolPhase(m.Phase); phase { + case + MachinePoolPhasePending, + MachinePoolPhaseProvisioning, + MachinePoolPhaseProvisioned, + MachinePoolPhaseRunning, + MachinePoolPhaseScalingUp, + MachinePoolPhaseScalingDown, + MachinePoolPhaseScaling, + MachinePoolPhaseDeleting, + MachinePoolPhaseFailed: + return phase + default: + return MachinePoolPhaseUnknown + } +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=machinepools,shortName=mp,scope=Namespaced,categories=cluster-api +// +kubebuilder:subresource:status +// +kubebuilder:subresource:scale:specpath=.spec.replicas,statuspath=.status.replicas +// +kubebuilder:storageversion +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" +// +kubebuilder:printcolumn:name="Desired",type=integer,JSONPath=".spec.replicas",description="The desired number of machines" +// +kubebuilder:printcolumn:name="Current",type="integer",JSONPath=".status.replicas",description="The number of machines" +// +kubebuilder:printcolumn:name="Ready",type="integer",JSONPath=".status.readyReplicas",description="The number of machines with Ready condition true" +// +kubebuilder:printcolumn:name="Available",type=integer,JSONPath=".status.availableReplicas",description="The number of machines with Available condition true" +// +kubebuilder:printcolumn:name="Up-to-date",type=integer,JSONPath=".status.upToDateReplicas",description="The number of machines with UpToDate condition true" +// +kubebuilder:printcolumn:name="Paused",type="string",JSONPath=`.status.conditions[?(@.type=="Paused")].status`,description="Reconciliation paused",priority=10 +// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase",description="MachinePool status such as Terminating/Pending/Provisioning/Running/Failed etc" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of MachinePool" +// +kubebuilder:printcolumn:name="Version",type="string",JSONPath=".spec.template.spec.version",description="Kubernetes version associated with this MachinePool" +// +k8s:conversion-gen=false + +// MachinePool is the Schema for the machinepools API. +// NOTE: This CRD can only be used if the MachinePool feature gate is enabled. +type MachinePool struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is the desired state of MachinePool. + // +required + Spec MachinePoolSpec `json:"spec,omitempty,omitzero"` + // status is the observed state of MachinePool. + // +optional + Status MachinePoolStatus `json:"status,omitempty,omitzero"` +} + +// GetV1Beta1Conditions returns the set of conditions for this object. +func (m *MachinePool) GetV1Beta1Conditions() Conditions { + if m.Status.Deprecated == nil || m.Status.Deprecated.V1Beta1 == nil { + return nil + } + return m.Status.Deprecated.V1Beta1.Conditions +} + +// SetV1Beta1Conditions sets the conditions on this object. +func (m *MachinePool) SetV1Beta1Conditions(conditions Conditions) { + if m.Status.Deprecated == nil { + m.Status.Deprecated = &MachinePoolDeprecatedStatus{} + } + if m.Status.Deprecated.V1Beta1 == nil { + m.Status.Deprecated.V1Beta1 = &MachinePoolV1Beta1DeprecatedStatus{} + } + m.Status.Deprecated.V1Beta1.Conditions = conditions +} + +// GetConditions returns the set of conditions for this object. +func (m *MachinePool) GetConditions() []metav1.Condition { + return m.Status.Conditions +} + +// SetConditions sets conditions for an API object. +func (m *MachinePool) SetConditions(conditions []metav1.Condition) { + m.Status.Conditions = conditions +} + +// +kubebuilder:object:root=true + +// MachinePoolList contains a list of MachinePool. +type MachinePoolList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + // items is the list of MachinePools. + Items []MachinePool `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &MachinePool{}, &MachinePoolList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machineset_types.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machineset_types.go new file mode 100644 index 000000000000..8a5a92db7d1b --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/machineset_types.go @@ -0,0 +1,499 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/util/validation/field" + + capierrors "sigs.k8s.io/cluster-api/errors" +) + +const ( + // MachineSetTopologyFinalizer is the finalizer used by the topology MachineDeployment controller to + // clean up referenced template resources if necessary when a MachineSet is being deleted. + MachineSetTopologyFinalizer = "machineset.topology.cluster.x-k8s.io" + + // MachineSetFinalizer is the finalizer used by the MachineSet controller to + // ensure ordered cleanup of corresponding Machines when a Machineset is being deleted. + MachineSetFinalizer = "cluster.x-k8s.io/machineset" +) + +// MachineSetSpec defines the desired state of MachineSet. +type MachineSetSpec struct { + // clusterName is the name of the Cluster this object belongs to. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + ClusterName string `json:"clusterName,omitempty"` + + // replicas is the number of desired replicas. + // This is a pointer to distinguish between explicit zero and unspecified. + // + // Defaults to: + // * if the Kubernetes autoscaler min size and max size annotations are set: + // - if it's a new MachineSet, use min size + // - if the replicas field of the old MachineSet is < min size, use min size + // - if the replicas field of the old MachineSet is > max size, use max size + // - if the replicas field of the old MachineSet is in the (min size, max size) range, keep the value from the oldMS + // * otherwise use 1 + // Note: Defaulting will be run whenever the replicas field is not set: + // * A new MachineSet is created with replicas not set. + // * On an existing MachineSet the replicas field was first set and is now unset. + // Those cases are especially relevant for the following Kubernetes autoscaler use cases: + // * A new MachineSet is created and replicas should be managed by the autoscaler + // * An existing MachineSet which initially wasn't controlled by the autoscaler + // should be later controlled by the autoscaler + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // selector is a label query over machines that should match the replica count. + // Label keys and values that must match in order to be controlled by this MachineSet. + // It must match the machine template's labels. + // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required + Selector metav1.LabelSelector `json:"selector,omitempty,omitzero"` + + // template is the object that describes the machine that will be created if + // insufficient replicas are detected. + // Object references to custom resources are treated as templates. + // +required + Template MachineTemplateSpec `json:"template,omitempty,omitzero"` + + // machineNaming allows changing the naming pattern used when creating Machines. + // Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines. + // +optional + MachineNaming MachineNamingSpec `json:"machineNaming,omitempty,omitzero"` + + // deletion contains configuration options for MachineSet deletion. + // +optional + Deletion MachineSetDeletionSpec `json:"deletion,omitempty,omitzero"` +} + +// MachineSetDeletionSpec contains configuration options for MachineSet deletion. +// +kubebuilder:validation:MinProperties=1 +type MachineSetDeletionSpec struct { + // order defines the order in which Machines are deleted when downscaling. + // Defaults to "Random". Valid values are "Random, "Newest", "Oldest" + // +optional + Order MachineSetDeletionOrder `json:"order,omitempty"` +} + +// MachineSet's ScalingUp condition and corresponding reasons. +const ( + // MachineSetScalingUpCondition is true if actual replicas < desired replicas. + // Note: In case a MachineSet preflight check is preventing scale up, this will surface in the condition message. + MachineSetScalingUpCondition = ScalingUpCondition + + // MachineSetScalingUpReason surfaces when actual replicas < desired replicas. + MachineSetScalingUpReason = ScalingUpReason + + // MachineSetNotScalingUpReason surfaces when actual replicas >= desired replicas. + MachineSetNotScalingUpReason = NotScalingUpReason + + // MachineSetScalingUpInternalErrorReason surfaces unexpected failures when listing machines. + MachineSetScalingUpInternalErrorReason = InternalErrorReason + + // MachineSetScalingUpWaitingForReplicasSetReason surfaces when the .spec.replicas + // field of the MachineSet is not set. + MachineSetScalingUpWaitingForReplicasSetReason = WaitingForReplicasSetReason +) + +// MachineSet's ScalingDown condition and corresponding reasons. +const ( + // MachineSetScalingDownCondition is true if actual replicas > desired replicas. + MachineSetScalingDownCondition = ScalingDownCondition + + // MachineSetScalingDownReason surfaces when actual replicas > desired replicas. + MachineSetScalingDownReason = ScalingDownReason + + // MachineSetNotScalingDownReason surfaces when actual replicas <= desired replicas. + MachineSetNotScalingDownReason = NotScalingDownReason + + // MachineSetScalingDownInternalErrorReason surfaces unexpected failures when listing machines. + MachineSetScalingDownInternalErrorReason = InternalErrorReason + + // MachineSetScalingDownWaitingForReplicasSetReason surfaces when the .spec.replicas + // field of the MachineSet is not set. + MachineSetScalingDownWaitingForReplicasSetReason = WaitingForReplicasSetReason +) + +// MachineSet's MachinesReady condition and corresponding reasons. +// Note: Reason's could also be derived from the aggregation of machine's Ready conditions. +const ( + // MachineSetMachinesReadyCondition surfaces detail of issues on the controlled machines, if any. + MachineSetMachinesReadyCondition = MachinesReadyCondition + + // MachineSetMachinesReadyReason surfaces when all the controlled machine's Ready conditions are true. + MachineSetMachinesReadyReason = ReadyReason + + // MachineSetMachinesNotReadyReason surfaces when at least one of the controlled machine's Ready conditions is false. + MachineSetMachinesNotReadyReason = NotReadyReason + + // MachineSetMachinesReadyUnknownReason surfaces when at least one of the controlled machine's Ready conditions is unknown + // and none of the controlled machine's Ready conditions is false. + MachineSetMachinesReadyUnknownReason = ReadyUnknownReason + + // MachineSetMachinesReadyNoReplicasReason surfaces when no machines exist for the MachineSet. + MachineSetMachinesReadyNoReplicasReason = NoReplicasReason + + // MachineSetMachinesReadyInternalErrorReason surfaces unexpected failures when listing machines + // or aggregating machine's conditions. + MachineSetMachinesReadyInternalErrorReason = InternalErrorReason +) + +// MachineSet's MachinesUpToDate condition and corresponding reasons. +// Note: Reason's could also be derived from the aggregation of machine's MachinesUpToDate conditions. +const ( + // MachineSetMachinesUpToDateCondition surfaces details of controlled machines not up to date, if any. + // Note: New machines are considered 10s after machine creation. This gives time to the machine's owner controller to recognize the new machine and add the UpToDate condition. + MachineSetMachinesUpToDateCondition = MachinesUpToDateCondition + + // MachineSetMachinesUpToDateReason surfaces when all the controlled machine's UpToDate conditions are true. + MachineSetMachinesUpToDateReason = UpToDateReason + + // MachineSetMachinesNotUpToDateReason surfaces when at least one of the controlled machine's UpToDate conditions is false. + MachineSetMachinesNotUpToDateReason = NotUpToDateReason + + // MachineSetMachinesUpToDateUnknownReason surfaces when at least one of the controlled machine's UpToDate conditions is unknown + // and none of the controlled machine's UpToDate conditions is false. + MachineSetMachinesUpToDateUnknownReason = UpToDateUnknownReason + + // MachineSetMachinesUpToDateNoReplicasReason surfaces when no machines exist for the MachineSet. + MachineSetMachinesUpToDateNoReplicasReason = NoReplicasReason + + // MachineSetMachinesUpToDateInternalErrorReason surfaces unexpected failures when listing machines + // or aggregating status. + MachineSetMachinesUpToDateInternalErrorReason = InternalErrorReason +) + +// MachineSet's Remediating condition and corresponding reasons. +const ( + // MachineSetRemediatingCondition surfaces details about ongoing remediation of the controlled machines, if any. + MachineSetRemediatingCondition = RemediatingCondition + + // MachineSetRemediatingReason surfaces when the MachineSet has at least one machine with HealthCheckSucceeded set to false + // and with the OwnerRemediated condition set to false. + MachineSetRemediatingReason = RemediatingReason + + // MachineSetNotRemediatingReason surfaces when the MachineSet does not have any machine with HealthCheckSucceeded set to false + // and with the OwnerRemediated condition set to false. + MachineSetNotRemediatingReason = NotRemediatingReason + + // MachineSetRemediatingInternalErrorReason surfaces unexpected failures when computing the Remediating condition. + MachineSetRemediatingInternalErrorReason = InternalErrorReason +) + +// Reasons that will be used for the OwnerRemediated condition set by MachineHealthCheck on MachineSet controlled machines +// being remediated in v1Beta2 API version. +const ( + // MachineSetMachineCannotBeRemediatedReason surfaces when remediation of a MachineSet machine can't be started. + MachineSetMachineCannotBeRemediatedReason = "CannotBeRemediated" + + // MachineSetMachineRemediationDeferredReason surfaces when remediation of a MachineSet machine must be deferred. + MachineSetMachineRemediationDeferredReason = "RemediationDeferred" + + // MachineSetMachineRemediationMachineDeletingReason surfaces when remediation of a MachineSet machine + // has been completed by deleting the unhealthy machine. + // Note: After an unhealthy machine is deleted, a new one is created by the MachineSet as part of the + // regular reconcile loop that ensures the correct number of replicas exist. + MachineSetMachineRemediationMachineDeletingReason = "MachineDeleting" +) + +// MachineSet's Deleting condition and corresponding reasons. +const ( + // MachineSetDeletingCondition surfaces details about ongoing deletion of the controlled machines. + MachineSetDeletingCondition = DeletingCondition + + // MachineSetNotDeletingReason surfaces when the MachineSet is not deleting because the + // DeletionTimestamp is not set. + MachineSetNotDeletingReason = NotDeletingReason + + // MachineSetDeletingReason surfaces when the MachineSet is deleting because the + // DeletionTimestamp is set. + MachineSetDeletingReason = DeletingReason + + // MachineSetDeletingInternalErrorReason surfaces unexpected failures when deleting a MachineSet. + MachineSetDeletingInternalErrorReason = InternalErrorReason +) + +// MachineTemplateSpec describes the data needed to create a Machine from a template. +type MachineTemplateSpec struct { + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + ObjectMeta `json:"metadata,omitempty,omitzero"` + + // spec is the specification of the desired behavior of the machine. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +required + Spec MachineSpec `json:"spec,omitempty,omitzero"` +} + +// MachineSetDeletionOrder defines how priority is assigned to nodes to delete when +// downscaling a MachineSet. Defaults to "Random". +// +kubebuilder:validation:Enum=Random;Newest;Oldest +type MachineSetDeletionOrder string + +const ( + // RandomMachineSetDeletionOrder prioritizes both Machines that have the annotation + // "cluster.x-k8s.io/delete-machine=yes" and Machines that are unhealthy + // (Status.FailureReason or Status.FailureMessage are set to a non-empty value + // or NodeHealthy type of Status.Conditions is not true). + // Finally, it picks Machines at random to delete. + RandomMachineSetDeletionOrder MachineSetDeletionOrder = "Random" + + // NewestMachineSetDeletionOrder prioritizes both Machines that have the annotation + // "cluster.x-k8s.io/delete-machine=yes" and Machines that are unhealthy + // (Status.FailureReason or Status.FailureMessage are set to a non-empty value + // or NodeHealthy type of Status.Conditions is not true). + // It then prioritizes the newest Machines for deletion based on the Machine's CreationTimestamp. + NewestMachineSetDeletionOrder MachineSetDeletionOrder = "Newest" + + // OldestMachineSetDeletionOrder prioritizes both Machines that have the annotation + // "cluster.x-k8s.io/delete-machine=yes" and Machines that are unhealthy + // (Status.FailureReason or Status.FailureMessage are set to a non-empty value + // or NodeHealthy type of Status.Conditions is not true). + // It then prioritizes the oldest Machines for deletion based on the Machine's CreationTimestamp. + OldestMachineSetDeletionOrder MachineSetDeletionOrder = "Oldest" +) + +// MachineSetStatus defines the observed state of MachineSet. +// +kubebuilder:validation:MinProperties=1 +type MachineSetStatus struct { + // conditions represents the observations of a MachineSet's current state. + // Known condition types are MachinesReady, MachinesUpToDate, ScalingUp, ScalingDown, Remediating, Deleting, Paused. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // selector is the same as the label selector but in the string format to avoid introspection + // by clients. The string will be in the same format as the query-param syntax. + // More info about label selectors: http://kubernetes.io/docs/user-guide/labels#label-selectors + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=4096 + Selector string `json:"selector,omitempty"` + + // replicas is the most recently observed number of replicas. + // +optional + Replicas *int32 `json:"replicas,omitempty"` + + // readyReplicas is the number of ready replicas for this MachineSet. A machine is considered ready when Machine's Ready condition is true. + // +optional + ReadyReplicas *int32 `json:"readyReplicas,omitempty"` + + // availableReplicas is the number of available replicas for this MachineSet. A machine is considered available when Machine's Available condition is true. + // +optional + AvailableReplicas *int32 `json:"availableReplicas,omitempty"` + + // upToDateReplicas is the number of up-to-date replicas for this MachineSet. A machine is considered up-to-date when Machine's UpToDate condition is true. + // +optional + UpToDateReplicas *int32 `json:"upToDateReplicas,omitempty"` + + // observedGeneration reflects the generation of the most recently observed MachineSet. + // +optional + // +kubebuilder:validation:Minimum=1 + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. + // +optional + Deprecated *MachineSetDeprecatedStatus `json:"deprecated,omitempty"` +} + +// MachineSetDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachineSetDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + // +optional + V1Beta1 *MachineSetV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` +} + +// MachineSetV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type MachineSetV1Beta1DeprecatedStatus struct { + // conditions defines current service state of the MachineSet. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + Conditions Conditions `json:"conditions,omitempty"` + + // failureReason will be set in the event that there is a terminal problem + // reconciling the Machine and will contain a succinct value suitable + // for machine interpretation. + // + // In the event that there is a terminal problem reconciling the + // replicas, both FailureReason and FailureMessage will be set. FailureReason + // will be populated with a succinct value suitable for machine + // interpretation, while FailureMessage will contain a more verbose + // string suitable for logging and human consumption. + // + // These fields should not be set for transitive errors that a + // controller faces that are expected to be fixed automatically over + // time (like service outages), but instead indicate that something is + // fundamentally wrong with the MachineTemplate's spec or the configuration of + // the machine controller, and that manual intervention is required. Examples + // of terminal errors would be invalid combinations of settings in the + // spec, values that are unsupported by the machine controller, or the + // responsible machine controller itself being critically misconfigured. + // + // Any transient errors that occur during the reconciliation of Machines + // can be added as events to the MachineSet object and/or logged in the + // controller's output. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + FailureReason *capierrors.MachineSetStatusError `json:"failureReason,omitempty"` + + // failureMessage will be set in the event that there is a terminal problem + // reconciling the Machine and will contain a more verbose string suitable + // for logging and human consumption. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=10240 + FailureMessage *string `json:"failureMessage,omitempty"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // fullyLabeledReplicas is the number of replicas that have labels matching the labels of the machine template of the MachineSet. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + FullyLabeledReplicas int32 `json:"fullyLabeledReplicas"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // readyReplicas is the number of ready replicas for this MachineSet. A machine is considered ready when the node has been created and is "Ready". + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + ReadyReplicas int32 `json:"readyReplicas"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed + + // availableReplicas is the number of available replicas (ready for at least minReadySeconds) for this MachineSet. + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + AvailableReplicas int32 `json:"availableReplicas"` //nolint:kubeapilinter // field will be removed when v1beta1 is removed +} + +// Validate validates the MachineSet fields. +func (m *MachineSet) Validate() field.ErrorList { + errors := field.ErrorList{} + + // validate spec.selector and spec.template.labels + fldPath := field.NewPath("spec") + errors = append(errors, metav1validation.ValidateLabelSelector(&m.Spec.Selector, metav1validation.LabelSelectorValidationOptions{}, fldPath.Child("selector"))...) + if len(m.Spec.Selector.MatchLabels)+len(m.Spec.Selector.MatchExpressions) == 0 { + errors = append(errors, field.Invalid(fldPath.Child("selector"), m.Spec.Selector, "empty selector is not valid for MachineSet.")) + } + selector, err := metav1.LabelSelectorAsSelector(&m.Spec.Selector) + if err != nil { + errors = append(errors, field.Invalid(fldPath.Child("selector"), m.Spec.Selector, "invalid label selector.")) + } else { + labels := labels.Set(m.Spec.Template.Labels) + if !selector.Matches(labels) { + errors = append(errors, field.Invalid(fldPath.Child("template", "metadata", "labels"), m.Spec.Template.Labels, "`selector` does not match template `labels`")) + } + } + + return errors +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=machinesets,shortName=ms,scope=Namespaced,categories=cluster-api +// +kubebuilder:storageversion +// +kubebuilder:subresource:status +// +kubebuilder:subresource:scale:specpath=.spec.replicas,statuspath=.status.replicas,selectorpath=.status.selector +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterName",description="Cluster" +// +kubebuilder:printcolumn:name="Desired",type=integer,JSONPath=".spec.replicas",description="The desired number of machines" +// +kubebuilder:printcolumn:name="Current",type="integer",JSONPath=".status.replicas",description="The number of machines" +// +kubebuilder:printcolumn:name="Ready",type="integer",JSONPath=".status.readyReplicas",description="The number of machines with Ready condition true" +// +kubebuilder:printcolumn:name="Available",type=integer,JSONPath=".status.availableReplicas",description="The number of machines with Available condition true" +// +kubebuilder:printcolumn:name="Up-to-date",type=integer,JSONPath=".status.upToDateReplicas",description="The number of machines with UpToDate condition true" +// +kubebuilder:printcolumn:name="Paused",type="string",JSONPath=`.status.conditions[?(@.type=="Paused")].status`,description="Reconciliation paused",priority=10 +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of MachineSet" +// +kubebuilder:printcolumn:name="Version",type="string",JSONPath=".spec.template.spec.version",description="Kubernetes version associated with this MachineSet" + +// MachineSet is the Schema for the machinesets API. +type MachineSet struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is the desired state of MachineSet. + // +required + Spec MachineSetSpec `json:"spec,omitempty,omitzero"` + // status is the observed state of MachineSet. + // +optional + Status MachineSetStatus `json:"status,omitempty,omitzero"` +} + +// GetV1Beta1Conditions returns the set of conditions for the MachineSet. +func (m *MachineSet) GetV1Beta1Conditions() Conditions { + if m.Status.Deprecated == nil || m.Status.Deprecated.V1Beta1 == nil { + return nil + } + return m.Status.Deprecated.V1Beta1.Conditions +} + +// SetV1Beta1Conditions updates the set of conditions on the MachineSet. +func (m *MachineSet) SetV1Beta1Conditions(conditions Conditions) { + if m.Status.Deprecated == nil { + m.Status.Deprecated = &MachineSetDeprecatedStatus{} + } + if m.Status.Deprecated.V1Beta1 == nil { + m.Status.Deprecated.V1Beta1 = &MachineSetV1Beta1DeprecatedStatus{} + } + m.Status.Deprecated.V1Beta1.Conditions = conditions +} + +// GetConditions returns the set of conditions for this object. +func (m *MachineSet) GetConditions() []metav1.Condition { + return m.Status.Conditions +} + +// SetConditions sets conditions for an API object. +func (m *MachineSet) SetConditions(conditions []metav1.Condition) { + m.Status.Conditions = conditions +} + +// +kubebuilder:object:root=true + +// MachineSetList contains a list of MachineSet. +type MachineSetList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + // items is the list of MachineSets. + Items []MachineSet `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &MachineSet{}, &MachineSetList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/v1beta1_condition_consts.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/v1beta1_condition_consts.go new file mode 100644 index 000000000000..aef565c0aa2f --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/v1beta1_condition_consts.go @@ -0,0 +1,367 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +// Common ConditionTypes used by Cluster API objects. +const ( + // ReadyV1Beta1Condition defines the Ready condition type that summarizes the operational state of a Cluster API object. + ReadyV1Beta1Condition ConditionType = "Ready" +) + +// Common ConditionReason used by Cluster API objects. +const ( + // DeletingV1Beta1Reason (Severity=Info) documents a condition not in Status=True because the underlying object it is currently being deleted. + DeletingV1Beta1Reason = "Deleting" + + // DeletionFailedV1Beta1Reason (Severity=Warning) documents a condition not in Status=True because the underlying object + // encountered problems during deletion. This is a warning because the reconciler will retry deletion. + DeletionFailedV1Beta1Reason = "DeletionFailed" + + // DeletedV1Beta1Reason (Severity=Info) documents a condition not in Status=True because the underlying object was deleted. + DeletedV1Beta1Reason = "Deleted" + + // IncorrectExternalRefV1Beta1Reason (Severity=Error) documents a CAPI object with an incorrect external object reference. + IncorrectExternalRefV1Beta1Reason = "IncorrectExternalRef" +) + +const ( + // InfrastructureReadyV1Beta1Condition reports a summary of current status of the infrastructure object defined for this cluster/machine/machinepool. + // This condition is mirrored from the Ready condition in the infrastructure ref object, and + // the absence of this condition might signal problems in the reconcile external loops or the fact that + // the infrastructure provider does not implement the Ready condition yet. + InfrastructureReadyV1Beta1Condition ConditionType = "InfrastructureReady" + + // WaitingForInfrastructureFallbackV1Beta1Reason (Severity=Info) documents a cluster/machine/machinepool waiting for the underlying infrastructure + // to be available. + // NOTE: This reason is used only as a fallback when the infrastructure object is not reporting its own ready condition. + WaitingForInfrastructureFallbackV1Beta1Reason = "WaitingForInfrastructure" +) + +// Conditions and condition Reasons for the ClusterClass object. +const ( + // ClusterClassVariablesReconciledV1Beta1Condition reports if the ClusterClass variables, including both inline and external + // variables, have been successfully reconciled. + // This signals that the ClusterClass is ready to be used to default and validate variables on Clusters using + // this ClusterClass. + ClusterClassVariablesReconciledV1Beta1Condition ConditionType = "VariablesReconciled" + + // VariableDiscoveryFailedV1Beta1Reason (Severity=Error) documents a ClusterClass with VariableDiscovery extensions that + // failed. + VariableDiscoveryFailedV1Beta1Reason = "VariableDiscoveryFailed" +) + +// Conditions and condition Reasons for the Cluster object. + +const ( + // ControlPlaneInitializedV1Beta1Condition reports if the cluster's control plane has been initialized such that the + // cluster's apiserver is reachable. If no Control Plane provider is in use this condition reports that at least one + // control plane Machine has a node reference. Once this Condition is marked true, its value is never changed. See + // the ControlPlaneReady condition for an indication of the current readiness of the cluster's control plane. + ControlPlaneInitializedV1Beta1Condition ConditionType = "ControlPlaneInitialized" + + // MissingNodeRefV1Beta1Reason (Severity=Info) documents a cluster waiting for at least one control plane Machine to have + // its node reference populated. + MissingNodeRefV1Beta1Reason = "MissingNodeRef" + + // WaitingForControlPlaneProviderInitializedV1Beta1Reason (Severity=Info) documents a cluster waiting for the control plane + // provider to report successful control plane initialization. + WaitingForControlPlaneProviderInitializedV1Beta1Reason = "WaitingForControlPlaneProviderInitialized" + + // ControlPlaneReadyV1Beta1Condition reports the ready condition from the control plane object defined for this cluster. + // This condition is mirrored from the Ready condition in the control plane ref object, and + // the absence of this condition might signal problems in the reconcile external loops or the fact that + // the control plane provider does not implement the Ready condition yet. + ControlPlaneReadyV1Beta1Condition ConditionType = "ControlPlaneReady" + + // WaitingForControlPlaneFallbackV1Beta1Reason (Severity=Info) documents a cluster waiting for the control plane + // to be available. + // NOTE: This reason is used only as a fallback when the control plane object is not reporting its own ready condition. + WaitingForControlPlaneFallbackV1Beta1Reason = "WaitingForControlPlane" + + // WaitingForControlPlaneAvailableV1Beta1Reason (Severity=Info) documents a Cluster API object + // waiting for the control plane machine to be available. + // + // NOTE: Having the control plane machine available is a pre-condition for joining additional control planes + // or workers nodes. + WaitingForControlPlaneAvailableV1Beta1Reason = "WaitingForControlPlaneAvailable" +) + +// Conditions and condition Reasons for the Machine object. + +const ( + // BootstrapReadyV1Beta1Condition reports a summary of current status of the bootstrap object defined for this machine. + // This condition is mirrored from the Ready condition in the bootstrap ref object, and + // the absence of this condition might signal problems in the reconcile external loops or the fact that + // the bootstrap provider does not implement the Ready condition yet. + BootstrapReadyV1Beta1Condition ConditionType = "BootstrapReady" + + // WaitingForDataSecretFallbackV1Beta1Reason (Severity=Info) documents a machine waiting for the bootstrap data secret + // to be available. + // NOTE: This reason is used only as a fallback when the bootstrap object is not reporting its own ready condition. + WaitingForDataSecretFallbackV1Beta1Reason = "WaitingForDataSecret" + + // DrainingSucceededV1Beta1Condition provide evidence of the status of the node drain operation which happens during the machine + // deletion process. + DrainingSucceededV1Beta1Condition ConditionType = "DrainingSucceeded" + + // DrainingV1Beta1Reason (Severity=Info) documents a machine node being drained. + DrainingV1Beta1Reason = "Draining" + + // DrainingFailedV1Beta1Reason (Severity=Warning) documents a machine node drain operation failed. + DrainingFailedV1Beta1Reason = "DrainingFailed" + + // PreDrainDeleteHookSucceededV1Beta1Condition reports a machine waiting for a PreDrainDeleteHook before being delete. + PreDrainDeleteHookSucceededV1Beta1Condition ConditionType = "PreDrainDeleteHookSucceeded" + + // PreTerminateDeleteHookSucceededV1Beta1Condition reports a machine waiting for a PreDrainDeleteHook before being delete. + PreTerminateDeleteHookSucceededV1Beta1Condition ConditionType = "PreTerminateDeleteHookSucceeded" + + // WaitingExternalHookV1Beta1Reason (Severity=Info) provide evidence that we are waiting for an external hook to complete. + WaitingExternalHookV1Beta1Reason = "WaitingExternalHook" + + // VolumeDetachSucceededV1Beta1Condition reports a machine waiting for volumes to be detached. + VolumeDetachSucceededV1Beta1Condition ConditionType = "VolumeDetachSucceeded" + + // WaitingForVolumeDetachV1Beta1Reason (Severity=Info) provide evidence that a machine node waiting for volumes to be attached. + WaitingForVolumeDetachV1Beta1Reason = "WaitingForVolumeDetach" +) + +const ( + // MachineHealthCheckSucceededV1Beta1Condition is set on machines that have passed a healthcheck by the MachineHealthCheck controller. + // In the event that the health check fails it will be set to False. + MachineHealthCheckSucceededV1Beta1Condition ConditionType = "HealthCheckSucceeded" + + // MachineHasFailureV1Beta1Reason is the reason used when a machine has either a FailureReason or a FailureMessage set on its status. + MachineHasFailureV1Beta1Reason = "MachineHasFailure" + + // HasRemediateMachineAnnotationV1Beta1Reason is the reason that get's set at the MachineHealthCheckSucceededCondition when a machine + // has the RemediateMachineAnnotation set. + HasRemediateMachineAnnotationV1Beta1Reason = "HasRemediateMachineAnnotation" + + // NodeStartupTimeoutV1Beta1Reason is the reason used when a machine's node does not appear within the specified timeout. + NodeStartupTimeoutV1Beta1Reason = "NodeStartupTimeout" + + // UnhealthyNodeConditionV1Beta1Reason is the reason used when a machine's node has one of the MachineHealthCheck's unhealthy conditions. + UnhealthyNodeConditionV1Beta1Reason = "UnhealthyNode" +) + +const ( + // MachineOwnerRemediatedV1Beta1Condition is set on machines that have failed a healthcheck by the MachineHealthCheck controller. + // MachineOwnerRemediatedV1Beta1Condition is set to False after a health check fails, but should be changed to True by the owning controller after remediation succeeds. + MachineOwnerRemediatedV1Beta1Condition ConditionType = "OwnerRemediated" + + // WaitingForRemediationV1Beta1Reason is the reason used when a machine fails a health check and remediation is needed. + WaitingForRemediationV1Beta1Reason = "WaitingForRemediation" + + // RemediationFailedV1Beta1Reason is the reason used when a remediation owner fails to remediate an unhealthy machine. + RemediationFailedV1Beta1Reason = "RemediationFailed" + + // RemediationInProgressV1Beta1Reason is the reason used when an unhealthy machine is being remediated by the remediation owner. + RemediationInProgressV1Beta1Reason = "RemediationInProgress" + + // ExternalRemediationTemplateAvailableV1Beta1Condition is set on machinehealthchecks when MachineHealthCheck controller uses external remediation. + // ExternalRemediationTemplateAvailableV1Beta1Condition is set to false if external remediation template is not found. + ExternalRemediationTemplateAvailableV1Beta1Condition ConditionType = "ExternalRemediationTemplateAvailable" + + // ExternalRemediationTemplateNotFoundV1Beta1Reason is the reason used when a machine health check fails to find external remediation template. + ExternalRemediationTemplateNotFoundV1Beta1Reason = "ExternalRemediationTemplateNotFound" + + // ExternalRemediationRequestAvailableV1Beta1Condition is set on machinehealthchecks when MachineHealthCheck controller uses external remediation. + // ExternalRemediationRequestAvailableV1Beta1Condition is set to false if creating external remediation request fails. + ExternalRemediationRequestAvailableV1Beta1Condition ConditionType = "ExternalRemediationRequestAvailable" + + // ExternalRemediationRequestCreationFailedV1Beta1Reason is the reason used when a machine health check fails to create external remediation request. + ExternalRemediationRequestCreationFailedV1Beta1Reason = "ExternalRemediationRequestCreationFailed" +) + +// Conditions and condition Reasons for the Machine's Node object. +const ( + // MachineNodeHealthyV1Beta1Condition provides info about the operational state of the Kubernetes node hosted on the machine by summarizing node conditions. + // If the conditions defined in a Kubernetes node (i.e., NodeReady, NodeMemoryPressure, NodeDiskPressure and NodePIDPressure) are in a healthy state, it will be set to True. + MachineNodeHealthyV1Beta1Condition ConditionType = "NodeHealthy" + + // WaitingForNodeRefV1Beta1Reason (Severity=Info) documents a machine.spec.providerId is not assigned yet. + WaitingForNodeRefV1Beta1Reason = "WaitingForNodeRef" + + // NodeProvisioningV1Beta1Reason (Severity=Info) documents machine in the process of provisioning a node. + // NB. provisioning --> NodeRef == "". + NodeProvisioningV1Beta1Reason = "NodeProvisioning" + + // NodeNotFoundV1Beta1Reason (Severity=Error) documents a machine's node has previously been observed but is now gone. + // NB. provisioned --> NodeRef != "". + NodeNotFoundV1Beta1Reason = "NodeNotFound" + + // NodeConditionsFailedV1Beta1Reason (Severity=Warning) documents a node is not in a healthy state due to the failed state of at least 1 Kubelet condition. + NodeConditionsFailedV1Beta1Reason = "NodeConditionsFailed" + + // NodeInspectionFailedV1Beta1Reason documents a failure in inspecting the node. + // This reason is used when the Machine controller is unable to list Nodes to find + // the corresponding Node for a Machine by ProviderID. + NodeInspectionFailedV1Beta1Reason = "NodeInspectionFailed" +) + +// Conditions and condition Reasons for the MachineHealthCheck object. + +const ( + // RemediationAllowedV1Beta1Condition is set on MachineHealthChecks to show the status of whether the MachineHealthCheck is + // allowed to remediate any Machines or whether it is blocked from remediating any further. + RemediationAllowedV1Beta1Condition ConditionType = "RemediationAllowed" + + // TooManyUnhealthyV1Beta1Reason is the reason used when too many Machines are unhealthy and the MachineHealthCheck is blocked + // from making any further remediations. + TooManyUnhealthyV1Beta1Reason = "TooManyUnhealthy" +) + +// Conditions and condition Reasons for MachineDeployments. + +const ( + // MachineDeploymentAvailableV1Beta1Condition means the MachineDeployment is available, that is, at least the minimum available + // machines required (i.e. Spec.Replicas-MaxUnavailable when spec.rollout.strategy.type = RollingUpdate) are up and running for at least minReadySeconds. + MachineDeploymentAvailableV1Beta1Condition ConditionType = "Available" + + // MachineSetReadyV1Beta1Condition reports a summary of current status of the MachineSet owned by the MachineDeployment. + MachineSetReadyV1Beta1Condition ConditionType = "MachineSetReady" + + // WaitingForMachineSetFallbackV1Beta1Reason (Severity=Info) documents a MachineDeployment waiting for the underlying MachineSet + // to be available. + // NOTE: This reason is used only as a fallback when the MachineSet object is not reporting its own ready condition. + WaitingForMachineSetFallbackV1Beta1Reason = "WaitingForMachineSet" + + // WaitingForAvailableMachinesV1Beta1Reason (Severity=Warning) reflects the fact that the required minimum number of machines for a machinedeployment are not available. + WaitingForAvailableMachinesV1Beta1Reason = "WaitingForAvailableMachines" +) + +// Conditions and condition Reasons for MachineSets. + +const ( + // MachinesCreatedV1Beta1Condition documents that the machines controlled by the MachineSet are created. + // When this condition is false, it indicates that there was an error when cloning the infrastructure/bootstrap template or + // when generating the machine object. + MachinesCreatedV1Beta1Condition ConditionType = "MachinesCreated" + + // MachinesReadyV1Beta1Condition reports an aggregate of current status of the machines controlled by the MachineSet. + MachinesReadyV1Beta1Condition ConditionType = "MachinesReady" + + // PreflightCheckFailedV1Beta1Reason (Severity=Error) documents a MachineSet failing preflight checks + // to create machine(s). + PreflightCheckFailedV1Beta1Reason = "PreflightCheckFailed" + + // BootstrapTemplateCloningFailedV1Beta1Reason (Severity=Error) documents a MachineSet failing to + // clone the bootstrap template. + BootstrapTemplateCloningFailedV1Beta1Reason = "BootstrapTemplateCloningFailed" + + // InfrastructureTemplateCloningFailedV1Beta1Reason (Severity=Error) documents a MachineSet failing to + // clone the infrastructure template. + InfrastructureTemplateCloningFailedV1Beta1Reason = "InfrastructureTemplateCloningFailed" + + // MachineCreationFailedV1Beta1Reason (Severity=Error) documents a MachineSet failing to + // generate a machine object. + MachineCreationFailedV1Beta1Reason = "MachineCreationFailed" + + // ResizedV1Beta1Condition documents a MachineSet is resizing the set of controlled machines. + ResizedV1Beta1Condition ConditionType = "Resized" + + // ScalingUpV1Beta1Reason (Severity=Info) documents a MachineSet is increasing the number of replicas. + ScalingUpV1Beta1Reason = "ScalingUp" + + // ScalingDownV1Beta1Reason (Severity=Info) documents a MachineSet is decreasing the number of replicas. + ScalingDownV1Beta1Reason = "ScalingDown" +) + +// Conditions and condition reasons for Clusters with a managed Topology. +const ( + // TopologyReconciledV1Beta1Condition provides evidence about the reconciliation of a Cluster topology into + // the managed objects of the Cluster. + // Status false means that for any reason, the values defined in Cluster.spec.topology are not yet applied to + // managed objects on the Cluster; status true means that Cluster.spec.topology have been applied to + // the objects in the Cluster (but this does not imply those objects are already reconciled to the spec provided). + TopologyReconciledV1Beta1Condition ConditionType = "TopologyReconciled" + + // TopologyReconcileFailedV1Beta1Reason (Severity=Error) documents the reconciliation of a Cluster topology + // failing due to an error. + TopologyReconcileFailedV1Beta1Reason = "TopologyReconcileFailed" + + // TopologyReconciledControlPlaneUpgradePendingV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology + // not yet completed because Control Plane is not yet updated to match the desired topology spec. + TopologyReconciledControlPlaneUpgradePendingV1Beta1Reason = "ControlPlaneUpgradePending" + + // TopologyReconciledMachineDeploymentsCreatePendingV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology + // not yet completed because at least one of the MachineDeployments is yet to be created. + // This generally happens because new MachineDeployment creations are held off while the ControlPlane is not stable. + TopologyReconciledMachineDeploymentsCreatePendingV1Beta1Reason = "MachineDeploymentsCreatePending" + + // TopologyReconciledMachineDeploymentsUpgradePendingV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology + // not yet completed because at least one of the MachineDeployments is not yet updated to match the desired topology spec. + TopologyReconciledMachineDeploymentsUpgradePendingV1Beta1Reason = "MachineDeploymentsUpgradePending" + + // TopologyReconciledMachineDeploymentsUpgradeDeferredV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology + // not yet completed because the upgrade for at least one of the MachineDeployments has been deferred. + TopologyReconciledMachineDeploymentsUpgradeDeferredV1Beta1Reason = "MachineDeploymentsUpgradeDeferred" + + // TopologyReconciledMachinePoolsUpgradePendingV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology + // not yet completed because at least one of the MachinePools is not yet updated to match the desired topology spec. + TopologyReconciledMachinePoolsUpgradePendingV1Beta1Reason = "MachinePoolsUpgradePending" + + // TopologyReconciledMachinePoolsCreatePendingV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology + // not yet completed because at least one of the MachinePools is yet to be created. + // This generally happens because new MachinePool creations are held off while the ControlPlane is not stable. + TopologyReconciledMachinePoolsCreatePendingV1Beta1Reason = "MachinePoolsCreatePending" + + // TopologyReconciledMachinePoolsUpgradeDeferredV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology + // not yet completed because the upgrade for at least one of the MachinePools has been deferred. + TopologyReconciledMachinePoolsUpgradeDeferredV1Beta1Reason = "MachinePoolsUpgradeDeferred" + + // TopologyReconciledHookBlockingV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology + // not yet completed because at least one of the lifecycle hooks is blocking. + TopologyReconciledHookBlockingV1Beta1Reason = "LifecycleHookBlocking" + + // TopologyReconciledClusterClassNotReconciledV1Beta1Reason (Severity=Info) documents reconciliation of a Cluster topology not + // yet completed because the ClusterClass has not reconciled yet. If this condition persists there may be an issue + // with the ClusterClass surfaced in the ClusterClass status or controller logs. + TopologyReconciledClusterClassNotReconciledV1Beta1Reason = "ClusterClassNotReconciled" + + // TopologyReconciledPausedV1Beta1Reason (Severity=Info) surfaces when the Cluster is paused. + TopologyReconciledPausedV1Beta1Reason = "Paused" +) + +// Conditions and condition reasons for ClusterClass. +const ( + // ClusterClassRefVersionsUpToDateV1Beta1Condition documents if the references in the ClusterClass are + // up-to-date (i.e. they are using the latest apiVersion of the current Cluster API contract from + // the corresponding CRD). + ClusterClassRefVersionsUpToDateV1Beta1Condition ConditionType = "RefVersionsUpToDate" + + // ClusterClassOutdatedRefVersionsV1Beta1Reason (Severity=Warning) that the references in the ClusterClass are not + // up-to-date (i.e. they are not using the latest apiVersion of the current Cluster API contract from + // the corresponding CRD). + ClusterClassOutdatedRefVersionsV1Beta1Reason = "OutdatedRefVersions" + + // ClusterClassRefVersionsUpToDateInternalErrorV1Beta1Reason (Severity=Warning) surfaces that an unexpected error occurred when validating + // if the references are up-to-date. + ClusterClassRefVersionsUpToDateInternalErrorV1Beta1Reason = "InternalError" +) + +// Conditions and condition Reasons for the MachinePool object. + +const ( + // ReplicasReadyV1Beta1Condition reports an aggregate of current status of the replicas controlled by the MachinePool. + ReplicasReadyV1Beta1Condition ConditionType = "ReplicasReady" + + // WaitingForReplicasReadyV1Beta1Reason (Severity=Info) documents a machinepool waiting for the required replicas + // to be ready. + WaitingForReplicasReadyV1Beta1Reason = "WaitingForReplicasReady" +) diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/zz_generated.deepcopy.go new file mode 100644 index 000000000000..49d1f6655253 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/zz_generated.deepcopy.go @@ -0,0 +1,3843 @@ +//go:build !ignore_autogenerated + +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by controller-gen. DO NOT EDIT. + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/intstr" + "sigs.k8s.io/cluster-api/errors" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIEndpoint) DeepCopyInto(out *APIEndpoint) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIEndpoint. +func (in *APIEndpoint) DeepCopy() *APIEndpoint { + if in == nil { + return nil + } + out := new(APIEndpoint) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Bootstrap) DeepCopyInto(out *Bootstrap) { + *out = *in + out.ConfigRef = in.ConfigRef + if in.DataSecretName != nil { + in, out := &in.DataSecretName, &out.DataSecretName + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Bootstrap. +func (in *Bootstrap) DeepCopy() *Bootstrap { + if in == nil { + return nil + } + out := new(Bootstrap) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Cluster) DeepCopyInto(out *Cluster) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Cluster. +func (in *Cluster) DeepCopy() *Cluster { + if in == nil { + return nil + } + out := new(Cluster) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Cluster) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterAvailabilityGate) DeepCopyInto(out *ClusterAvailabilityGate) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterAvailabilityGate. +func (in *ClusterAvailabilityGate) DeepCopy() *ClusterAvailabilityGate { + if in == nil { + return nil + } + out := new(ClusterAvailabilityGate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClass) DeepCopyInto(out *ClusterClass) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClass. +func (in *ClusterClass) DeepCopy() *ClusterClass { + if in == nil { + return nil + } + out := new(ClusterClass) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterClass) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassDeprecatedStatus) DeepCopyInto(out *ClusterClassDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(ClusterClassV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassDeprecatedStatus. +func (in *ClusterClassDeprecatedStatus) DeepCopy() *ClusterClassDeprecatedStatus { + if in == nil { + return nil + } + out := new(ClusterClassDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassList) DeepCopyInto(out *ClusterClassList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterClass, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassList. +func (in *ClusterClassList) DeepCopy() *ClusterClassList { + if in == nil { + return nil + } + out := new(ClusterClassList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterClassList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassPatch) DeepCopyInto(out *ClusterClassPatch) { + *out = *in + if in.Definitions != nil { + in, out := &in.Definitions, &out.Definitions + *out = make([]PatchDefinition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.External != nil { + in, out := &in.External, &out.External + *out = new(ExternalPatchDefinition) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassPatch. +func (in *ClusterClassPatch) DeepCopy() *ClusterClassPatch { + if in == nil { + return nil + } + out := new(ClusterClassPatch) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassRef) DeepCopyInto(out *ClusterClassRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassRef. +func (in *ClusterClassRef) DeepCopy() *ClusterClassRef { + if in == nil { + return nil + } + out := new(ClusterClassRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassSpec) DeepCopyInto(out *ClusterClassSpec) { + *out = *in + if in.AvailabilityGates != nil { + in, out := &in.AvailabilityGates, &out.AvailabilityGates + *out = make([]ClusterAvailabilityGate, len(*in)) + copy(*out, *in) + } + out.Infrastructure = in.Infrastructure + in.ControlPlane.DeepCopyInto(&out.ControlPlane) + in.Workers.DeepCopyInto(&out.Workers) + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]ClusterClassVariable, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Patches != nil { + in, out := &in.Patches, &out.Patches + *out = make([]ClusterClassPatch, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassSpec. +func (in *ClusterClassSpec) DeepCopy() *ClusterClassSpec { + if in == nil { + return nil + } + out := new(ClusterClassSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassStatus) DeepCopyInto(out *ClusterClassStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]ClusterClassStatusVariable, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(ClusterClassDeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassStatus. +func (in *ClusterClassStatus) DeepCopy() *ClusterClassStatus { + if in == nil { + return nil + } + out := new(ClusterClassStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassStatusVariable) DeepCopyInto(out *ClusterClassStatusVariable) { + *out = *in + if in.DefinitionsConflict != nil { + in, out := &in.DefinitionsConflict, &out.DefinitionsConflict + *out = new(bool) + **out = **in + } + if in.Definitions != nil { + in, out := &in.Definitions, &out.Definitions + *out = make([]ClusterClassStatusVariableDefinition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassStatusVariable. +func (in *ClusterClassStatusVariable) DeepCopy() *ClusterClassStatusVariable { + if in == nil { + return nil + } + out := new(ClusterClassStatusVariable) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassStatusVariableDefinition) DeepCopyInto(out *ClusterClassStatusVariableDefinition) { + *out = *in + if in.Required != nil { + in, out := &in.Required, &out.Required + *out = new(bool) + **out = **in + } + in.DeprecatedV1Beta1Metadata.DeepCopyInto(&out.DeprecatedV1Beta1Metadata) + in.Schema.DeepCopyInto(&out.Schema) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassStatusVariableDefinition. +func (in *ClusterClassStatusVariableDefinition) DeepCopy() *ClusterClassStatusVariableDefinition { + if in == nil { + return nil + } + out := new(ClusterClassStatusVariableDefinition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassTemplateReference) DeepCopyInto(out *ClusterClassTemplateReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassTemplateReference. +func (in *ClusterClassTemplateReference) DeepCopy() *ClusterClassTemplateReference { + if in == nil { + return nil + } + out := new(ClusterClassTemplateReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassV1Beta1DeprecatedStatus) DeepCopyInto(out *ClusterClassV1Beta1DeprecatedStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassV1Beta1DeprecatedStatus. +func (in *ClusterClassV1Beta1DeprecatedStatus) DeepCopy() *ClusterClassV1Beta1DeprecatedStatus { + if in == nil { + return nil + } + out := new(ClusterClassV1Beta1DeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassVariable) DeepCopyInto(out *ClusterClassVariable) { + *out = *in + if in.Required != nil { + in, out := &in.Required, &out.Required + *out = new(bool) + **out = **in + } + in.DeprecatedV1Beta1Metadata.DeepCopyInto(&out.DeprecatedV1Beta1Metadata) + in.Schema.DeepCopyInto(&out.Schema) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassVariable. +func (in *ClusterClassVariable) DeepCopy() *ClusterClassVariable { + if in == nil { + return nil + } + out := new(ClusterClassVariable) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterClassVariableMetadata) DeepCopyInto(out *ClusterClassVariableMetadata) { + *out = *in + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Annotations != nil { + in, out := &in.Annotations, &out.Annotations + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterClassVariableMetadata. +func (in *ClusterClassVariableMetadata) DeepCopy() *ClusterClassVariableMetadata { + if in == nil { + return nil + } + out := new(ClusterClassVariableMetadata) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterControlPlaneStatus) DeepCopyInto(out *ClusterControlPlaneStatus) { + *out = *in + if in.DesiredReplicas != nil { + in, out := &in.DesiredReplicas, &out.DesiredReplicas + *out = new(int32) + **out = **in + } + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + if in.UpToDateReplicas != nil { + in, out := &in.UpToDateReplicas, &out.UpToDateReplicas + *out = new(int32) + **out = **in + } + if in.ReadyReplicas != nil { + in, out := &in.ReadyReplicas, &out.ReadyReplicas + *out = new(int32) + **out = **in + } + if in.AvailableReplicas != nil { + in, out := &in.AvailableReplicas, &out.AvailableReplicas + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterControlPlaneStatus. +func (in *ClusterControlPlaneStatus) DeepCopy() *ClusterControlPlaneStatus { + if in == nil { + return nil + } + out := new(ClusterControlPlaneStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterDeprecatedStatus) DeepCopyInto(out *ClusterDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(ClusterV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterDeprecatedStatus. +func (in *ClusterDeprecatedStatus) DeepCopy() *ClusterDeprecatedStatus { + if in == nil { + return nil + } + out := new(ClusterDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterInitializationStatus) DeepCopyInto(out *ClusterInitializationStatus) { + *out = *in + if in.InfrastructureProvisioned != nil { + in, out := &in.InfrastructureProvisioned, &out.InfrastructureProvisioned + *out = new(bool) + **out = **in + } + if in.ControlPlaneInitialized != nil { + in, out := &in.ControlPlaneInitialized, &out.ControlPlaneInitialized + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterInitializationStatus. +func (in *ClusterInitializationStatus) DeepCopy() *ClusterInitializationStatus { + if in == nil { + return nil + } + out := new(ClusterInitializationStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterList) DeepCopyInto(out *ClusterList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Cluster, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterList. +func (in *ClusterList) DeepCopy() *ClusterList { + if in == nil { + return nil + } + out := new(ClusterList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterNetwork) DeepCopyInto(out *ClusterNetwork) { + *out = *in + in.Services.DeepCopyInto(&out.Services) + in.Pods.DeepCopyInto(&out.Pods) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterNetwork. +func (in *ClusterNetwork) DeepCopy() *ClusterNetwork { + if in == nil { + return nil + } + out := new(ClusterNetwork) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterSpec) DeepCopyInto(out *ClusterSpec) { + *out = *in + if in.Paused != nil { + in, out := &in.Paused, &out.Paused + *out = new(bool) + **out = **in + } + in.ClusterNetwork.DeepCopyInto(&out.ClusterNetwork) + out.ControlPlaneEndpoint = in.ControlPlaneEndpoint + out.ControlPlaneRef = in.ControlPlaneRef + out.InfrastructureRef = in.InfrastructureRef + in.Topology.DeepCopyInto(&out.Topology) + if in.AvailabilityGates != nil { + in, out := &in.AvailabilityGates, &out.AvailabilityGates + *out = make([]ClusterAvailabilityGate, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterSpec. +func (in *ClusterSpec) DeepCopy() *ClusterSpec { + if in == nil { + return nil + } + out := new(ClusterSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterStatus) DeepCopyInto(out *ClusterStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + in.Initialization.DeepCopyInto(&out.Initialization) + if in.ControlPlane != nil { + in, out := &in.ControlPlane, &out.ControlPlane + *out = new(ClusterControlPlaneStatus) + (*in).DeepCopyInto(*out) + } + if in.Workers != nil { + in, out := &in.Workers, &out.Workers + *out = new(WorkersStatus) + (*in).DeepCopyInto(*out) + } + if in.FailureDomains != nil { + in, out := &in.FailureDomains, &out.FailureDomains + *out = make([]FailureDomain, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(ClusterDeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterStatus. +func (in *ClusterStatus) DeepCopy() *ClusterStatus { + if in == nil { + return nil + } + out := new(ClusterStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterV1Beta1DeprecatedStatus) DeepCopyInto(out *ClusterV1Beta1DeprecatedStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.FailureReason != nil { + in, out := &in.FailureReason, &out.FailureReason + *out = new(errors.ClusterStatusError) + **out = **in + } + if in.FailureMessage != nil { + in, out := &in.FailureMessage, &out.FailureMessage + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterV1Beta1DeprecatedStatus. +func (in *ClusterV1Beta1DeprecatedStatus) DeepCopy() *ClusterV1Beta1DeprecatedStatus { + if in == nil { + return nil + } + out := new(ClusterV1Beta1DeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterVariable) DeepCopyInto(out *ClusterVariable) { + *out = *in + in.Value.DeepCopyInto(&out.Value) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterVariable. +func (in *ClusterVariable) DeepCopy() *ClusterVariable { + if in == nil { + return nil + } + out := new(ClusterVariable) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Condition) DeepCopyInto(out *Condition) { + *out = *in + in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Condition. +func (in *Condition) DeepCopy() *Condition { + if in == nil { + return nil + } + out := new(Condition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in Conditions) DeepCopyInto(out *Conditions) { + { + in := &in + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Conditions. +func (in Conditions) DeepCopy() Conditions { + if in == nil { + return nil + } + out := new(Conditions) + in.DeepCopyInto(out) + return *out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContractVersionedObjectReference) DeepCopyInto(out *ContractVersionedObjectReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContractVersionedObjectReference. +func (in *ContractVersionedObjectReference) DeepCopy() *ContractVersionedObjectReference { + if in == nil { + return nil + } + out := new(ContractVersionedObjectReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneClass) DeepCopyInto(out *ControlPlaneClass) { + *out = *in + in.Metadata.DeepCopyInto(&out.Metadata) + out.TemplateRef = in.TemplateRef + out.MachineInfrastructure = in.MachineInfrastructure + in.HealthCheck.DeepCopyInto(&out.HealthCheck) + out.Naming = in.Naming + in.Deletion.DeepCopyInto(&out.Deletion) + if in.ReadinessGates != nil { + in, out := &in.ReadinessGates, &out.ReadinessGates + *out = make([]MachineReadinessGate, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneClass. +func (in *ControlPlaneClass) DeepCopy() *ControlPlaneClass { + if in == nil { + return nil + } + out := new(ControlPlaneClass) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneClassHealthCheck) DeepCopyInto(out *ControlPlaneClassHealthCheck) { + *out = *in + in.Checks.DeepCopyInto(&out.Checks) + in.Remediation.DeepCopyInto(&out.Remediation) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneClassHealthCheck. +func (in *ControlPlaneClassHealthCheck) DeepCopy() *ControlPlaneClassHealthCheck { + if in == nil { + return nil + } + out := new(ControlPlaneClassHealthCheck) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneClassHealthCheckChecks) DeepCopyInto(out *ControlPlaneClassHealthCheckChecks) { + *out = *in + if in.NodeStartupTimeoutSeconds != nil { + in, out := &in.NodeStartupTimeoutSeconds, &out.NodeStartupTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.UnhealthyNodeConditions != nil { + in, out := &in.UnhealthyNodeConditions, &out.UnhealthyNodeConditions + *out = make([]UnhealthyNodeCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneClassHealthCheckChecks. +func (in *ControlPlaneClassHealthCheckChecks) DeepCopy() *ControlPlaneClassHealthCheckChecks { + if in == nil { + return nil + } + out := new(ControlPlaneClassHealthCheckChecks) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneClassHealthCheckRemediation) DeepCopyInto(out *ControlPlaneClassHealthCheckRemediation) { + *out = *in + in.TriggerIf.DeepCopyInto(&out.TriggerIf) + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneClassHealthCheckRemediation. +func (in *ControlPlaneClassHealthCheckRemediation) DeepCopy() *ControlPlaneClassHealthCheckRemediation { + if in == nil { + return nil + } + out := new(ControlPlaneClassHealthCheckRemediation) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneClassHealthCheckRemediationTriggerIf) DeepCopyInto(out *ControlPlaneClassHealthCheckRemediationTriggerIf) { + *out = *in + if in.UnhealthyLessThanOrEqualTo != nil { + in, out := &in.UnhealthyLessThanOrEqualTo, &out.UnhealthyLessThanOrEqualTo + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneClassHealthCheckRemediationTriggerIf. +func (in *ControlPlaneClassHealthCheckRemediationTriggerIf) DeepCopy() *ControlPlaneClassHealthCheckRemediationTriggerIf { + if in == nil { + return nil + } + out := new(ControlPlaneClassHealthCheckRemediationTriggerIf) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneClassMachineDeletionSpec) DeepCopyInto(out *ControlPlaneClassMachineDeletionSpec) { + *out = *in + if in.NodeDrainTimeoutSeconds != nil { + in, out := &in.NodeDrainTimeoutSeconds, &out.NodeDrainTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeVolumeDetachTimeoutSeconds != nil { + in, out := &in.NodeVolumeDetachTimeoutSeconds, &out.NodeVolumeDetachTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeDeletionTimeoutSeconds != nil { + in, out := &in.NodeDeletionTimeoutSeconds, &out.NodeDeletionTimeoutSeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneClassMachineDeletionSpec. +func (in *ControlPlaneClassMachineDeletionSpec) DeepCopy() *ControlPlaneClassMachineDeletionSpec { + if in == nil { + return nil + } + out := new(ControlPlaneClassMachineDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneClassMachineInfrastructureTemplate) DeepCopyInto(out *ControlPlaneClassMachineInfrastructureTemplate) { + *out = *in + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneClassMachineInfrastructureTemplate. +func (in *ControlPlaneClassMachineInfrastructureTemplate) DeepCopy() *ControlPlaneClassMachineInfrastructureTemplate { + if in == nil { + return nil + } + out := new(ControlPlaneClassMachineInfrastructureTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneClassNamingSpec) DeepCopyInto(out *ControlPlaneClassNamingSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneClassNamingSpec. +func (in *ControlPlaneClassNamingSpec) DeepCopy() *ControlPlaneClassNamingSpec { + if in == nil { + return nil + } + out := new(ControlPlaneClassNamingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneTopology) DeepCopyInto(out *ControlPlaneTopology) { + *out = *in + in.Metadata.DeepCopyInto(&out.Metadata) + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + in.HealthCheck.DeepCopyInto(&out.HealthCheck) + in.Deletion.DeepCopyInto(&out.Deletion) + if in.ReadinessGates != nil { + in, out := &in.ReadinessGates, &out.ReadinessGates + *out = make([]MachineReadinessGate, len(*in)) + copy(*out, *in) + } + in.Variables.DeepCopyInto(&out.Variables) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneTopology. +func (in *ControlPlaneTopology) DeepCopy() *ControlPlaneTopology { + if in == nil { + return nil + } + out := new(ControlPlaneTopology) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneTopologyHealthCheck) DeepCopyInto(out *ControlPlaneTopologyHealthCheck) { + *out = *in + if in.Enabled != nil { + in, out := &in.Enabled, &out.Enabled + *out = new(bool) + **out = **in + } + in.Checks.DeepCopyInto(&out.Checks) + in.Remediation.DeepCopyInto(&out.Remediation) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneTopologyHealthCheck. +func (in *ControlPlaneTopologyHealthCheck) DeepCopy() *ControlPlaneTopologyHealthCheck { + if in == nil { + return nil + } + out := new(ControlPlaneTopologyHealthCheck) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneTopologyHealthCheckChecks) DeepCopyInto(out *ControlPlaneTopologyHealthCheckChecks) { + *out = *in + if in.NodeStartupTimeoutSeconds != nil { + in, out := &in.NodeStartupTimeoutSeconds, &out.NodeStartupTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.UnhealthyNodeConditions != nil { + in, out := &in.UnhealthyNodeConditions, &out.UnhealthyNodeConditions + *out = make([]UnhealthyNodeCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneTopologyHealthCheckChecks. +func (in *ControlPlaneTopologyHealthCheckChecks) DeepCopy() *ControlPlaneTopologyHealthCheckChecks { + if in == nil { + return nil + } + out := new(ControlPlaneTopologyHealthCheckChecks) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneTopologyHealthCheckRemediation) DeepCopyInto(out *ControlPlaneTopologyHealthCheckRemediation) { + *out = *in + in.TriggerIf.DeepCopyInto(&out.TriggerIf) + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneTopologyHealthCheckRemediation. +func (in *ControlPlaneTopologyHealthCheckRemediation) DeepCopy() *ControlPlaneTopologyHealthCheckRemediation { + if in == nil { + return nil + } + out := new(ControlPlaneTopologyHealthCheckRemediation) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneTopologyHealthCheckRemediationTriggerIf) DeepCopyInto(out *ControlPlaneTopologyHealthCheckRemediationTriggerIf) { + *out = *in + if in.UnhealthyLessThanOrEqualTo != nil { + in, out := &in.UnhealthyLessThanOrEqualTo, &out.UnhealthyLessThanOrEqualTo + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneTopologyHealthCheckRemediationTriggerIf. +func (in *ControlPlaneTopologyHealthCheckRemediationTriggerIf) DeepCopy() *ControlPlaneTopologyHealthCheckRemediationTriggerIf { + if in == nil { + return nil + } + out := new(ControlPlaneTopologyHealthCheckRemediationTriggerIf) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneTopologyMachineDeletionSpec) DeepCopyInto(out *ControlPlaneTopologyMachineDeletionSpec) { + *out = *in + if in.NodeDrainTimeoutSeconds != nil { + in, out := &in.NodeDrainTimeoutSeconds, &out.NodeDrainTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeVolumeDetachTimeoutSeconds != nil { + in, out := &in.NodeVolumeDetachTimeoutSeconds, &out.NodeVolumeDetachTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeDeletionTimeoutSeconds != nil { + in, out := &in.NodeDeletionTimeoutSeconds, &out.NodeDeletionTimeoutSeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneTopologyMachineDeletionSpec. +func (in *ControlPlaneTopologyMachineDeletionSpec) DeepCopy() *ControlPlaneTopologyMachineDeletionSpec { + if in == nil { + return nil + } + out := new(ControlPlaneTopologyMachineDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ControlPlaneVariables) DeepCopyInto(out *ControlPlaneVariables) { + *out = *in + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]ClusterVariable, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneVariables. +func (in *ControlPlaneVariables) DeepCopy() *ControlPlaneVariables { + if in == nil { + return nil + } + out := new(ControlPlaneVariables) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExternalPatchDefinition) DeepCopyInto(out *ExternalPatchDefinition) { + *out = *in + if in.Settings != nil { + in, out := &in.Settings, &out.Settings + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalPatchDefinition. +func (in *ExternalPatchDefinition) DeepCopy() *ExternalPatchDefinition { + if in == nil { + return nil + } + out := new(ExternalPatchDefinition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *FailureDomain) DeepCopyInto(out *FailureDomain) { + *out = *in + if in.ControlPlane != nil { + in, out := &in.ControlPlane, &out.ControlPlane + *out = new(bool) + **out = **in + } + if in.Attributes != nil { + in, out := &in.Attributes, &out.Attributes + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FailureDomain. +func (in *FailureDomain) DeepCopy() *FailureDomain { + if in == nil { + return nil + } + out := new(FailureDomain) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *InfrastructureClass) DeepCopyInto(out *InfrastructureClass) { + *out = *in + out.TemplateRef = in.TemplateRef + out.Naming = in.Naming +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InfrastructureClass. +func (in *InfrastructureClass) DeepCopy() *InfrastructureClass { + if in == nil { + return nil + } + out := new(InfrastructureClass) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *InfrastructureClassNamingSpec) DeepCopyInto(out *InfrastructureClassNamingSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InfrastructureClassNamingSpec. +func (in *InfrastructureClassNamingSpec) DeepCopy() *InfrastructureClassNamingSpec { + if in == nil { + return nil + } + out := new(InfrastructureClassNamingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *JSONPatch) DeepCopyInto(out *JSONPatch) { + *out = *in + if in.Value != nil { + in, out := &in.Value, &out.Value + *out = new(apiextensionsv1.JSON) + (*in).DeepCopyInto(*out) + } + if in.ValueFrom != nil { + in, out := &in.ValueFrom, &out.ValueFrom + *out = new(JSONPatchValue) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONPatch. +func (in *JSONPatch) DeepCopy() *JSONPatch { + if in == nil { + return nil + } + out := new(JSONPatch) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *JSONPatchValue) DeepCopyInto(out *JSONPatchValue) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONPatchValue. +func (in *JSONPatchValue) DeepCopy() *JSONPatchValue { + if in == nil { + return nil + } + out := new(JSONPatchValue) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *JSONSchemaProps) DeepCopyInto(out *JSONSchemaProps) { + *out = *in + if in.Example != nil { + in, out := &in.Example, &out.Example + *out = new(apiextensionsv1.JSON) + (*in).DeepCopyInto(*out) + } + if in.Properties != nil { + in, out := &in.Properties, &out.Properties + *out = make(map[string]JSONSchemaProps, len(*in)) + for key, val := range *in { + (*out)[key] = *val.DeepCopy() + } + } + if in.AdditionalProperties != nil { + in, out := &in.AdditionalProperties, &out.AdditionalProperties + *out = new(JSONSchemaProps) + (*in).DeepCopyInto(*out) + } + if in.MaxProperties != nil { + in, out := &in.MaxProperties, &out.MaxProperties + *out = new(int64) + **out = **in + } + if in.MinProperties != nil { + in, out := &in.MinProperties, &out.MinProperties + *out = new(int64) + **out = **in + } + if in.Required != nil { + in, out := &in.Required, &out.Required + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = new(JSONSchemaProps) + (*in).DeepCopyInto(*out) + } + if in.MaxItems != nil { + in, out := &in.MaxItems, &out.MaxItems + *out = new(int64) + **out = **in + } + if in.MinItems != nil { + in, out := &in.MinItems, &out.MinItems + *out = new(int64) + **out = **in + } + if in.UniqueItems != nil { + in, out := &in.UniqueItems, &out.UniqueItems + *out = new(bool) + **out = **in + } + if in.MaxLength != nil { + in, out := &in.MaxLength, &out.MaxLength + *out = new(int64) + **out = **in + } + if in.MinLength != nil { + in, out := &in.MinLength, &out.MinLength + *out = new(int64) + **out = **in + } + if in.Maximum != nil { + in, out := &in.Maximum, &out.Maximum + *out = new(int64) + **out = **in + } + if in.ExclusiveMaximum != nil { + in, out := &in.ExclusiveMaximum, &out.ExclusiveMaximum + *out = new(bool) + **out = **in + } + if in.Minimum != nil { + in, out := &in.Minimum, &out.Minimum + *out = new(int64) + **out = **in + } + if in.ExclusiveMinimum != nil { + in, out := &in.ExclusiveMinimum, &out.ExclusiveMinimum + *out = new(bool) + **out = **in + } + if in.XPreserveUnknownFields != nil { + in, out := &in.XPreserveUnknownFields, &out.XPreserveUnknownFields + *out = new(bool) + **out = **in + } + if in.Enum != nil { + in, out := &in.Enum, &out.Enum + *out = make([]apiextensionsv1.JSON, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Default != nil { + in, out := &in.Default, &out.Default + *out = new(apiextensionsv1.JSON) + (*in).DeepCopyInto(*out) + } + if in.XValidations != nil { + in, out := &in.XValidations, &out.XValidations + *out = make([]ValidationRule, len(*in)) + copy(*out, *in) + } + in.XMetadata.DeepCopyInto(&out.XMetadata) + if in.XIntOrString != nil { + in, out := &in.XIntOrString, &out.XIntOrString + *out = new(bool) + **out = **in + } + if in.AllOf != nil { + in, out := &in.AllOf, &out.AllOf + *out = make([]JSONSchemaProps, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.OneOf != nil { + in, out := &in.OneOf, &out.OneOf + *out = make([]JSONSchemaProps, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.AnyOf != nil { + in, out := &in.AnyOf, &out.AnyOf + *out = make([]JSONSchemaProps, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Not != nil { + in, out := &in.Not, &out.Not + *out = new(JSONSchemaProps) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaProps. +func (in *JSONSchemaProps) DeepCopy() *JSONSchemaProps { + if in == nil { + return nil + } + out := new(JSONSchemaProps) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Machine) DeepCopyInto(out *Machine) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Machine. +func (in *Machine) DeepCopy() *Machine { + if in == nil { + return nil + } + out := new(Machine) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Machine) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineAddress) DeepCopyInto(out *MachineAddress) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineAddress. +func (in *MachineAddress) DeepCopy() *MachineAddress { + if in == nil { + return nil + } + out := new(MachineAddress) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in MachineAddresses) DeepCopyInto(out *MachineAddresses) { + { + in := &in + *out = make(MachineAddresses, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineAddresses. +func (in MachineAddresses) DeepCopy() MachineAddresses { + if in == nil { + return nil + } + out := new(MachineAddresses) + in.DeepCopyInto(out) + return *out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeletionSpec) DeepCopyInto(out *MachineDeletionSpec) { + *out = *in + if in.NodeDrainTimeoutSeconds != nil { + in, out := &in.NodeDrainTimeoutSeconds, &out.NodeDrainTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeVolumeDetachTimeoutSeconds != nil { + in, out := &in.NodeVolumeDetachTimeoutSeconds, &out.NodeVolumeDetachTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeDeletionTimeoutSeconds != nil { + in, out := &in.NodeDeletionTimeoutSeconds, &out.NodeDeletionTimeoutSeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeletionSpec. +func (in *MachineDeletionSpec) DeepCopy() *MachineDeletionSpec { + if in == nil { + return nil + } + out := new(MachineDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeletionStatus) DeepCopyInto(out *MachineDeletionStatus) { + *out = *in + in.NodeDrainStartTime.DeepCopyInto(&out.NodeDrainStartTime) + in.WaitForNodeVolumeDetachStartTime.DeepCopyInto(&out.WaitForNodeVolumeDetachStartTime) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeletionStatus. +func (in *MachineDeletionStatus) DeepCopy() *MachineDeletionStatus { + if in == nil { + return nil + } + out := new(MachineDeletionStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeployment) DeepCopyInto(out *MachineDeployment) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeployment. +func (in *MachineDeployment) DeepCopy() *MachineDeployment { + if in == nil { + return nil + } + out := new(MachineDeployment) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineDeployment) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClass) DeepCopyInto(out *MachineDeploymentClass) { + *out = *in + in.Metadata.DeepCopyInto(&out.Metadata) + out.Bootstrap = in.Bootstrap + out.Infrastructure = in.Infrastructure + in.HealthCheck.DeepCopyInto(&out.HealthCheck) + out.Naming = in.Naming + in.Deletion.DeepCopyInto(&out.Deletion) + if in.MinReadySeconds != nil { + in, out := &in.MinReadySeconds, &out.MinReadySeconds + *out = new(int32) + **out = **in + } + if in.ReadinessGates != nil { + in, out := &in.ReadinessGates, &out.ReadinessGates + *out = make([]MachineReadinessGate, len(*in)) + copy(*out, *in) + } + in.Rollout.DeepCopyInto(&out.Rollout) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClass. +func (in *MachineDeploymentClass) DeepCopy() *MachineDeploymentClass { + if in == nil { + return nil + } + out := new(MachineDeploymentClass) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassBootstrapTemplate) DeepCopyInto(out *MachineDeploymentClassBootstrapTemplate) { + *out = *in + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassBootstrapTemplate. +func (in *MachineDeploymentClassBootstrapTemplate) DeepCopy() *MachineDeploymentClassBootstrapTemplate { + if in == nil { + return nil + } + out := new(MachineDeploymentClassBootstrapTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassHealthCheck) DeepCopyInto(out *MachineDeploymentClassHealthCheck) { + *out = *in + in.Checks.DeepCopyInto(&out.Checks) + in.Remediation.DeepCopyInto(&out.Remediation) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassHealthCheck. +func (in *MachineDeploymentClassHealthCheck) DeepCopy() *MachineDeploymentClassHealthCheck { + if in == nil { + return nil + } + out := new(MachineDeploymentClassHealthCheck) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassHealthCheckChecks) DeepCopyInto(out *MachineDeploymentClassHealthCheckChecks) { + *out = *in + if in.NodeStartupTimeoutSeconds != nil { + in, out := &in.NodeStartupTimeoutSeconds, &out.NodeStartupTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.UnhealthyNodeConditions != nil { + in, out := &in.UnhealthyNodeConditions, &out.UnhealthyNodeConditions + *out = make([]UnhealthyNodeCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassHealthCheckChecks. +func (in *MachineDeploymentClassHealthCheckChecks) DeepCopy() *MachineDeploymentClassHealthCheckChecks { + if in == nil { + return nil + } + out := new(MachineDeploymentClassHealthCheckChecks) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassHealthCheckRemediation) DeepCopyInto(out *MachineDeploymentClassHealthCheckRemediation) { + *out = *in + if in.MaxInFlight != nil { + in, out := &in.MaxInFlight, &out.MaxInFlight + *out = new(intstr.IntOrString) + **out = **in + } + in.TriggerIf.DeepCopyInto(&out.TriggerIf) + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassHealthCheckRemediation. +func (in *MachineDeploymentClassHealthCheckRemediation) DeepCopy() *MachineDeploymentClassHealthCheckRemediation { + if in == nil { + return nil + } + out := new(MachineDeploymentClassHealthCheckRemediation) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassHealthCheckRemediationTriggerIf) DeepCopyInto(out *MachineDeploymentClassHealthCheckRemediationTriggerIf) { + *out = *in + if in.UnhealthyLessThanOrEqualTo != nil { + in, out := &in.UnhealthyLessThanOrEqualTo, &out.UnhealthyLessThanOrEqualTo + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassHealthCheckRemediationTriggerIf. +func (in *MachineDeploymentClassHealthCheckRemediationTriggerIf) DeepCopy() *MachineDeploymentClassHealthCheckRemediationTriggerIf { + if in == nil { + return nil + } + out := new(MachineDeploymentClassHealthCheckRemediationTriggerIf) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassInfrastructureTemplate) DeepCopyInto(out *MachineDeploymentClassInfrastructureTemplate) { + *out = *in + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassInfrastructureTemplate. +func (in *MachineDeploymentClassInfrastructureTemplate) DeepCopy() *MachineDeploymentClassInfrastructureTemplate { + if in == nil { + return nil + } + out := new(MachineDeploymentClassInfrastructureTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassMachineDeletionSpec) DeepCopyInto(out *MachineDeploymentClassMachineDeletionSpec) { + *out = *in + if in.NodeDrainTimeoutSeconds != nil { + in, out := &in.NodeDrainTimeoutSeconds, &out.NodeDrainTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeVolumeDetachTimeoutSeconds != nil { + in, out := &in.NodeVolumeDetachTimeoutSeconds, &out.NodeVolumeDetachTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeDeletionTimeoutSeconds != nil { + in, out := &in.NodeDeletionTimeoutSeconds, &out.NodeDeletionTimeoutSeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassMachineDeletionSpec. +func (in *MachineDeploymentClassMachineDeletionSpec) DeepCopy() *MachineDeploymentClassMachineDeletionSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentClassMachineDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassNamingSpec) DeepCopyInto(out *MachineDeploymentClassNamingSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassNamingSpec. +func (in *MachineDeploymentClassNamingSpec) DeepCopy() *MachineDeploymentClassNamingSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentClassNamingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassRolloutSpec) DeepCopyInto(out *MachineDeploymentClassRolloutSpec) { + *out = *in + in.Strategy.DeepCopyInto(&out.Strategy) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassRolloutSpec. +func (in *MachineDeploymentClassRolloutSpec) DeepCopy() *MachineDeploymentClassRolloutSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentClassRolloutSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassRolloutStrategy) DeepCopyInto(out *MachineDeploymentClassRolloutStrategy) { + *out = *in + in.RollingUpdate.DeepCopyInto(&out.RollingUpdate) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassRolloutStrategy. +func (in *MachineDeploymentClassRolloutStrategy) DeepCopy() *MachineDeploymentClassRolloutStrategy { + if in == nil { + return nil + } + out := new(MachineDeploymentClassRolloutStrategy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentClassRolloutStrategyRollingUpdate) DeepCopyInto(out *MachineDeploymentClassRolloutStrategyRollingUpdate) { + *out = *in + if in.MaxUnavailable != nil { + in, out := &in.MaxUnavailable, &out.MaxUnavailable + *out = new(intstr.IntOrString) + **out = **in + } + if in.MaxSurge != nil { + in, out := &in.MaxSurge, &out.MaxSurge + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentClassRolloutStrategyRollingUpdate. +func (in *MachineDeploymentClassRolloutStrategyRollingUpdate) DeepCopy() *MachineDeploymentClassRolloutStrategyRollingUpdate { + if in == nil { + return nil + } + out := new(MachineDeploymentClassRolloutStrategyRollingUpdate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentDeletionSpec) DeepCopyInto(out *MachineDeploymentDeletionSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentDeletionSpec. +func (in *MachineDeploymentDeletionSpec) DeepCopy() *MachineDeploymentDeletionSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentDeprecatedStatus) DeepCopyInto(out *MachineDeploymentDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(MachineDeploymentV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentDeprecatedStatus. +func (in *MachineDeploymentDeprecatedStatus) DeepCopy() *MachineDeploymentDeprecatedStatus { + if in == nil { + return nil + } + out := new(MachineDeploymentDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentList) DeepCopyInto(out *MachineDeploymentList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachineDeployment, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentList. +func (in *MachineDeploymentList) DeepCopy() *MachineDeploymentList { + if in == nil { + return nil + } + out := new(MachineDeploymentList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineDeploymentList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentRemediationSpec) DeepCopyInto(out *MachineDeploymentRemediationSpec) { + *out = *in + if in.MaxInFlight != nil { + in, out := &in.MaxInFlight, &out.MaxInFlight + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentRemediationSpec. +func (in *MachineDeploymentRemediationSpec) DeepCopy() *MachineDeploymentRemediationSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentRemediationSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentRolloutSpec) DeepCopyInto(out *MachineDeploymentRolloutSpec) { + *out = *in + in.After.DeepCopyInto(&out.After) + in.Strategy.DeepCopyInto(&out.Strategy) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentRolloutSpec. +func (in *MachineDeploymentRolloutSpec) DeepCopy() *MachineDeploymentRolloutSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentRolloutSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentRolloutStrategy) DeepCopyInto(out *MachineDeploymentRolloutStrategy) { + *out = *in + in.RollingUpdate.DeepCopyInto(&out.RollingUpdate) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentRolloutStrategy. +func (in *MachineDeploymentRolloutStrategy) DeepCopy() *MachineDeploymentRolloutStrategy { + if in == nil { + return nil + } + out := new(MachineDeploymentRolloutStrategy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentRolloutStrategyRollingUpdate) DeepCopyInto(out *MachineDeploymentRolloutStrategyRollingUpdate) { + *out = *in + if in.MaxUnavailable != nil { + in, out := &in.MaxUnavailable, &out.MaxUnavailable + *out = new(intstr.IntOrString) + **out = **in + } + if in.MaxSurge != nil { + in, out := &in.MaxSurge, &out.MaxSurge + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentRolloutStrategyRollingUpdate. +func (in *MachineDeploymentRolloutStrategyRollingUpdate) DeepCopy() *MachineDeploymentRolloutStrategyRollingUpdate { + if in == nil { + return nil + } + out := new(MachineDeploymentRolloutStrategyRollingUpdate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentSpec) DeepCopyInto(out *MachineDeploymentSpec) { + *out = *in + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + in.Rollout.DeepCopyInto(&out.Rollout) + in.Selector.DeepCopyInto(&out.Selector) + in.Template.DeepCopyInto(&out.Template) + out.MachineNaming = in.MachineNaming + in.Remediation.DeepCopyInto(&out.Remediation) + out.Deletion = in.Deletion + if in.Paused != nil { + in, out := &in.Paused, &out.Paused + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentSpec. +func (in *MachineDeploymentSpec) DeepCopy() *MachineDeploymentSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentStatus) DeepCopyInto(out *MachineDeploymentStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + if in.ReadyReplicas != nil { + in, out := &in.ReadyReplicas, &out.ReadyReplicas + *out = new(int32) + **out = **in + } + if in.AvailableReplicas != nil { + in, out := &in.AvailableReplicas, &out.AvailableReplicas + *out = new(int32) + **out = **in + } + if in.UpToDateReplicas != nil { + in, out := &in.UpToDateReplicas, &out.UpToDateReplicas + *out = new(int32) + **out = **in + } + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(MachineDeploymentDeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentStatus. +func (in *MachineDeploymentStatus) DeepCopy() *MachineDeploymentStatus { + if in == nil { + return nil + } + out := new(MachineDeploymentStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopology) DeepCopyInto(out *MachineDeploymentTopology) { + *out = *in + in.Metadata.DeepCopyInto(&out.Metadata) + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + in.HealthCheck.DeepCopyInto(&out.HealthCheck) + in.Deletion.DeepCopyInto(&out.Deletion) + if in.MinReadySeconds != nil { + in, out := &in.MinReadySeconds, &out.MinReadySeconds + *out = new(int32) + **out = **in + } + if in.ReadinessGates != nil { + in, out := &in.ReadinessGates, &out.ReadinessGates + *out = make([]MachineReadinessGate, len(*in)) + copy(*out, *in) + } + in.Rollout.DeepCopyInto(&out.Rollout) + in.Variables.DeepCopyInto(&out.Variables) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopology. +func (in *MachineDeploymentTopology) DeepCopy() *MachineDeploymentTopology { + if in == nil { + return nil + } + out := new(MachineDeploymentTopology) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopologyHealthCheck) DeepCopyInto(out *MachineDeploymentTopologyHealthCheck) { + *out = *in + if in.Enabled != nil { + in, out := &in.Enabled, &out.Enabled + *out = new(bool) + **out = **in + } + in.Checks.DeepCopyInto(&out.Checks) + in.Remediation.DeepCopyInto(&out.Remediation) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopologyHealthCheck. +func (in *MachineDeploymentTopologyHealthCheck) DeepCopy() *MachineDeploymentTopologyHealthCheck { + if in == nil { + return nil + } + out := new(MachineDeploymentTopologyHealthCheck) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopologyHealthCheckChecks) DeepCopyInto(out *MachineDeploymentTopologyHealthCheckChecks) { + *out = *in + if in.NodeStartupTimeoutSeconds != nil { + in, out := &in.NodeStartupTimeoutSeconds, &out.NodeStartupTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.UnhealthyNodeConditions != nil { + in, out := &in.UnhealthyNodeConditions, &out.UnhealthyNodeConditions + *out = make([]UnhealthyNodeCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopologyHealthCheckChecks. +func (in *MachineDeploymentTopologyHealthCheckChecks) DeepCopy() *MachineDeploymentTopologyHealthCheckChecks { + if in == nil { + return nil + } + out := new(MachineDeploymentTopologyHealthCheckChecks) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopologyHealthCheckRemediation) DeepCopyInto(out *MachineDeploymentTopologyHealthCheckRemediation) { + *out = *in + if in.MaxInFlight != nil { + in, out := &in.MaxInFlight, &out.MaxInFlight + *out = new(intstr.IntOrString) + **out = **in + } + in.TriggerIf.DeepCopyInto(&out.TriggerIf) + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopologyHealthCheckRemediation. +func (in *MachineDeploymentTopologyHealthCheckRemediation) DeepCopy() *MachineDeploymentTopologyHealthCheckRemediation { + if in == nil { + return nil + } + out := new(MachineDeploymentTopologyHealthCheckRemediation) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopologyHealthCheckRemediationTriggerIf) DeepCopyInto(out *MachineDeploymentTopologyHealthCheckRemediationTriggerIf) { + *out = *in + if in.UnhealthyLessThanOrEqualTo != nil { + in, out := &in.UnhealthyLessThanOrEqualTo, &out.UnhealthyLessThanOrEqualTo + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopologyHealthCheckRemediationTriggerIf. +func (in *MachineDeploymentTopologyHealthCheckRemediationTriggerIf) DeepCopy() *MachineDeploymentTopologyHealthCheckRemediationTriggerIf { + if in == nil { + return nil + } + out := new(MachineDeploymentTopologyHealthCheckRemediationTriggerIf) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopologyMachineDeletionSpec) DeepCopyInto(out *MachineDeploymentTopologyMachineDeletionSpec) { + *out = *in + if in.NodeDrainTimeoutSeconds != nil { + in, out := &in.NodeDrainTimeoutSeconds, &out.NodeDrainTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeVolumeDetachTimeoutSeconds != nil { + in, out := &in.NodeVolumeDetachTimeoutSeconds, &out.NodeVolumeDetachTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeDeletionTimeoutSeconds != nil { + in, out := &in.NodeDeletionTimeoutSeconds, &out.NodeDeletionTimeoutSeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopologyMachineDeletionSpec. +func (in *MachineDeploymentTopologyMachineDeletionSpec) DeepCopy() *MachineDeploymentTopologyMachineDeletionSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentTopologyMachineDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopologyRolloutSpec) DeepCopyInto(out *MachineDeploymentTopologyRolloutSpec) { + *out = *in + in.Strategy.DeepCopyInto(&out.Strategy) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopologyRolloutSpec. +func (in *MachineDeploymentTopologyRolloutSpec) DeepCopy() *MachineDeploymentTopologyRolloutSpec { + if in == nil { + return nil + } + out := new(MachineDeploymentTopologyRolloutSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopologyRolloutStrategy) DeepCopyInto(out *MachineDeploymentTopologyRolloutStrategy) { + *out = *in + in.RollingUpdate.DeepCopyInto(&out.RollingUpdate) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopologyRolloutStrategy. +func (in *MachineDeploymentTopologyRolloutStrategy) DeepCopy() *MachineDeploymentTopologyRolloutStrategy { + if in == nil { + return nil + } + out := new(MachineDeploymentTopologyRolloutStrategy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentTopologyRolloutStrategyRollingUpdate) DeepCopyInto(out *MachineDeploymentTopologyRolloutStrategyRollingUpdate) { + *out = *in + if in.MaxUnavailable != nil { + in, out := &in.MaxUnavailable, &out.MaxUnavailable + *out = new(intstr.IntOrString) + **out = **in + } + if in.MaxSurge != nil { + in, out := &in.MaxSurge, &out.MaxSurge + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentTopologyRolloutStrategyRollingUpdate. +func (in *MachineDeploymentTopologyRolloutStrategyRollingUpdate) DeepCopy() *MachineDeploymentTopologyRolloutStrategyRollingUpdate { + if in == nil { + return nil + } + out := new(MachineDeploymentTopologyRolloutStrategyRollingUpdate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentV1Beta1DeprecatedStatus) DeepCopyInto(out *MachineDeploymentV1Beta1DeprecatedStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentV1Beta1DeprecatedStatus. +func (in *MachineDeploymentV1Beta1DeprecatedStatus) DeepCopy() *MachineDeploymentV1Beta1DeprecatedStatus { + if in == nil { + return nil + } + out := new(MachineDeploymentV1Beta1DeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeploymentVariables) DeepCopyInto(out *MachineDeploymentVariables) { + *out = *in + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]ClusterVariable, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeploymentVariables. +func (in *MachineDeploymentVariables) DeepCopy() *MachineDeploymentVariables { + if in == nil { + return nil + } + out := new(MachineDeploymentVariables) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDeprecatedStatus) DeepCopyInto(out *MachineDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(MachineV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDeprecatedStatus. +func (in *MachineDeprecatedStatus) DeepCopy() *MachineDeprecatedStatus { + if in == nil { + return nil + } + out := new(MachineDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDrainRule) DeepCopyInto(out *MachineDrainRule) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDrainRule. +func (in *MachineDrainRule) DeepCopy() *MachineDrainRule { + if in == nil { + return nil + } + out := new(MachineDrainRule) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineDrainRule) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDrainRuleDrainConfig) DeepCopyInto(out *MachineDrainRuleDrainConfig) { + *out = *in + if in.Order != nil { + in, out := &in.Order, &out.Order + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDrainRuleDrainConfig. +func (in *MachineDrainRuleDrainConfig) DeepCopy() *MachineDrainRuleDrainConfig { + if in == nil { + return nil + } + out := new(MachineDrainRuleDrainConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDrainRuleList) DeepCopyInto(out *MachineDrainRuleList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachineDrainRule, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDrainRuleList. +func (in *MachineDrainRuleList) DeepCopy() *MachineDrainRuleList { + if in == nil { + return nil + } + out := new(MachineDrainRuleList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineDrainRuleList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDrainRuleMachineSelector) DeepCopyInto(out *MachineDrainRuleMachineSelector) { + *out = *in + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } + if in.ClusterSelector != nil { + in, out := &in.ClusterSelector, &out.ClusterSelector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDrainRuleMachineSelector. +func (in *MachineDrainRuleMachineSelector) DeepCopy() *MachineDrainRuleMachineSelector { + if in == nil { + return nil + } + out := new(MachineDrainRuleMachineSelector) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDrainRulePodSelector) DeepCopyInto(out *MachineDrainRulePodSelector) { + *out = *in + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } + if in.NamespaceSelector != nil { + in, out := &in.NamespaceSelector, &out.NamespaceSelector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDrainRulePodSelector. +func (in *MachineDrainRulePodSelector) DeepCopy() *MachineDrainRulePodSelector { + if in == nil { + return nil + } + out := new(MachineDrainRulePodSelector) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineDrainRuleSpec) DeepCopyInto(out *MachineDrainRuleSpec) { + *out = *in + in.Drain.DeepCopyInto(&out.Drain) + if in.Machines != nil { + in, out := &in.Machines, &out.Machines + *out = make([]MachineDrainRuleMachineSelector, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Pods != nil { + in, out := &in.Pods, &out.Pods + *out = make([]MachineDrainRulePodSelector, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineDrainRuleSpec. +func (in *MachineDrainRuleSpec) DeepCopy() *MachineDrainRuleSpec { + if in == nil { + return nil + } + out := new(MachineDrainRuleSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheck) DeepCopyInto(out *MachineHealthCheck) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheck. +func (in *MachineHealthCheck) DeepCopy() *MachineHealthCheck { + if in == nil { + return nil + } + out := new(MachineHealthCheck) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineHealthCheck) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckChecks) DeepCopyInto(out *MachineHealthCheckChecks) { + *out = *in + if in.NodeStartupTimeoutSeconds != nil { + in, out := &in.NodeStartupTimeoutSeconds, &out.NodeStartupTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.UnhealthyNodeConditions != nil { + in, out := &in.UnhealthyNodeConditions, &out.UnhealthyNodeConditions + *out = make([]UnhealthyNodeCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckChecks. +func (in *MachineHealthCheckChecks) DeepCopy() *MachineHealthCheckChecks { + if in == nil { + return nil + } + out := new(MachineHealthCheckChecks) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckDeprecatedStatus) DeepCopyInto(out *MachineHealthCheckDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(MachineHealthCheckV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckDeprecatedStatus. +func (in *MachineHealthCheckDeprecatedStatus) DeepCopy() *MachineHealthCheckDeprecatedStatus { + if in == nil { + return nil + } + out := new(MachineHealthCheckDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckList) DeepCopyInto(out *MachineHealthCheckList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachineHealthCheck, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckList. +func (in *MachineHealthCheckList) DeepCopy() *MachineHealthCheckList { + if in == nil { + return nil + } + out := new(MachineHealthCheckList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineHealthCheckList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckRemediation) DeepCopyInto(out *MachineHealthCheckRemediation) { + *out = *in + in.TriggerIf.DeepCopyInto(&out.TriggerIf) + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckRemediation. +func (in *MachineHealthCheckRemediation) DeepCopy() *MachineHealthCheckRemediation { + if in == nil { + return nil + } + out := new(MachineHealthCheckRemediation) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckRemediationTemplateReference) DeepCopyInto(out *MachineHealthCheckRemediationTemplateReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckRemediationTemplateReference. +func (in *MachineHealthCheckRemediationTemplateReference) DeepCopy() *MachineHealthCheckRemediationTemplateReference { + if in == nil { + return nil + } + out := new(MachineHealthCheckRemediationTemplateReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckRemediationTriggerIf) DeepCopyInto(out *MachineHealthCheckRemediationTriggerIf) { + *out = *in + if in.UnhealthyLessThanOrEqualTo != nil { + in, out := &in.UnhealthyLessThanOrEqualTo, &out.UnhealthyLessThanOrEqualTo + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckRemediationTriggerIf. +func (in *MachineHealthCheckRemediationTriggerIf) DeepCopy() *MachineHealthCheckRemediationTriggerIf { + if in == nil { + return nil + } + out := new(MachineHealthCheckRemediationTriggerIf) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckSpec) DeepCopyInto(out *MachineHealthCheckSpec) { + *out = *in + in.Selector.DeepCopyInto(&out.Selector) + in.Checks.DeepCopyInto(&out.Checks) + in.Remediation.DeepCopyInto(&out.Remediation) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckSpec. +func (in *MachineHealthCheckSpec) DeepCopy() *MachineHealthCheckSpec { + if in == nil { + return nil + } + out := new(MachineHealthCheckSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckStatus) DeepCopyInto(out *MachineHealthCheckStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.ExpectedMachines != nil { + in, out := &in.ExpectedMachines, &out.ExpectedMachines + *out = new(int32) + **out = **in + } + if in.CurrentHealthy != nil { + in, out := &in.CurrentHealthy, &out.CurrentHealthy + *out = new(int32) + **out = **in + } + if in.RemediationsAllowed != nil { + in, out := &in.RemediationsAllowed, &out.RemediationsAllowed + *out = new(int32) + **out = **in + } + if in.Targets != nil { + in, out := &in.Targets, &out.Targets + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(MachineHealthCheckDeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckStatus. +func (in *MachineHealthCheckStatus) DeepCopy() *MachineHealthCheckStatus { + if in == nil { + return nil + } + out := new(MachineHealthCheckStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineHealthCheckV1Beta1DeprecatedStatus) DeepCopyInto(out *MachineHealthCheckV1Beta1DeprecatedStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckV1Beta1DeprecatedStatus. +func (in *MachineHealthCheckV1Beta1DeprecatedStatus) DeepCopy() *MachineHealthCheckV1Beta1DeprecatedStatus { + if in == nil { + return nil + } + out := new(MachineHealthCheckV1Beta1DeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineInitializationStatus) DeepCopyInto(out *MachineInitializationStatus) { + *out = *in + if in.InfrastructureProvisioned != nil { + in, out := &in.InfrastructureProvisioned, &out.InfrastructureProvisioned + *out = new(bool) + **out = **in + } + if in.BootstrapDataSecretCreated != nil { + in, out := &in.BootstrapDataSecretCreated, &out.BootstrapDataSecretCreated + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineInitializationStatus. +func (in *MachineInitializationStatus) DeepCopy() *MachineInitializationStatus { + if in == nil { + return nil + } + out := new(MachineInitializationStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineList) DeepCopyInto(out *MachineList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Machine, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineList. +func (in *MachineList) DeepCopy() *MachineList { + if in == nil { + return nil + } + out := new(MachineList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineNamingSpec) DeepCopyInto(out *MachineNamingSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineNamingSpec. +func (in *MachineNamingSpec) DeepCopy() *MachineNamingSpec { + if in == nil { + return nil + } + out := new(MachineNamingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineNodeReference) DeepCopyInto(out *MachineNodeReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineNodeReference. +func (in *MachineNodeReference) DeepCopy() *MachineNodeReference { + if in == nil { + return nil + } + out := new(MachineNodeReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePool) DeepCopyInto(out *MachinePool) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePool. +func (in *MachinePool) DeepCopy() *MachinePool { + if in == nil { + return nil + } + out := new(MachinePool) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachinePool) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolClass) DeepCopyInto(out *MachinePoolClass) { + *out = *in + in.Metadata.DeepCopyInto(&out.Metadata) + out.Bootstrap = in.Bootstrap + out.Infrastructure = in.Infrastructure + if in.FailureDomains != nil { + in, out := &in.FailureDomains, &out.FailureDomains + *out = make([]string, len(*in)) + copy(*out, *in) + } + out.Naming = in.Naming + in.Deletion.DeepCopyInto(&out.Deletion) + if in.MinReadySeconds != nil { + in, out := &in.MinReadySeconds, &out.MinReadySeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolClass. +func (in *MachinePoolClass) DeepCopy() *MachinePoolClass { + if in == nil { + return nil + } + out := new(MachinePoolClass) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolClassBootstrapTemplate) DeepCopyInto(out *MachinePoolClassBootstrapTemplate) { + *out = *in + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolClassBootstrapTemplate. +func (in *MachinePoolClassBootstrapTemplate) DeepCopy() *MachinePoolClassBootstrapTemplate { + if in == nil { + return nil + } + out := new(MachinePoolClassBootstrapTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolClassInfrastructureTemplate) DeepCopyInto(out *MachinePoolClassInfrastructureTemplate) { + *out = *in + out.TemplateRef = in.TemplateRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolClassInfrastructureTemplate. +func (in *MachinePoolClassInfrastructureTemplate) DeepCopy() *MachinePoolClassInfrastructureTemplate { + if in == nil { + return nil + } + out := new(MachinePoolClassInfrastructureTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolClassMachineDeletionSpec) DeepCopyInto(out *MachinePoolClassMachineDeletionSpec) { + *out = *in + if in.NodeDrainTimeoutSeconds != nil { + in, out := &in.NodeDrainTimeoutSeconds, &out.NodeDrainTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeVolumeDetachTimeoutSeconds != nil { + in, out := &in.NodeVolumeDetachTimeoutSeconds, &out.NodeVolumeDetachTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeDeletionTimeoutSeconds != nil { + in, out := &in.NodeDeletionTimeoutSeconds, &out.NodeDeletionTimeoutSeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolClassMachineDeletionSpec. +func (in *MachinePoolClassMachineDeletionSpec) DeepCopy() *MachinePoolClassMachineDeletionSpec { + if in == nil { + return nil + } + out := new(MachinePoolClassMachineDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolClassNamingSpec) DeepCopyInto(out *MachinePoolClassNamingSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolClassNamingSpec. +func (in *MachinePoolClassNamingSpec) DeepCopy() *MachinePoolClassNamingSpec { + if in == nil { + return nil + } + out := new(MachinePoolClassNamingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolDeprecatedStatus) DeepCopyInto(out *MachinePoolDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(MachinePoolV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolDeprecatedStatus. +func (in *MachinePoolDeprecatedStatus) DeepCopy() *MachinePoolDeprecatedStatus { + if in == nil { + return nil + } + out := new(MachinePoolDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolInitializationStatus) DeepCopyInto(out *MachinePoolInitializationStatus) { + *out = *in + if in.InfrastructureProvisioned != nil { + in, out := &in.InfrastructureProvisioned, &out.InfrastructureProvisioned + *out = new(bool) + **out = **in + } + if in.BootstrapDataSecretCreated != nil { + in, out := &in.BootstrapDataSecretCreated, &out.BootstrapDataSecretCreated + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolInitializationStatus. +func (in *MachinePoolInitializationStatus) DeepCopy() *MachinePoolInitializationStatus { + if in == nil { + return nil + } + out := new(MachinePoolInitializationStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolList) DeepCopyInto(out *MachinePoolList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachinePool, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolList. +func (in *MachinePoolList) DeepCopy() *MachinePoolList { + if in == nil { + return nil + } + out := new(MachinePoolList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachinePoolList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolSpec) DeepCopyInto(out *MachinePoolSpec) { + *out = *in + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + in.Template.DeepCopyInto(&out.Template) + if in.ProviderIDList != nil { + in, out := &in.ProviderIDList, &out.ProviderIDList + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.FailureDomains != nil { + in, out := &in.FailureDomains, &out.FailureDomains + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolSpec. +func (in *MachinePoolSpec) DeepCopy() *MachinePoolSpec { + if in == nil { + return nil + } + out := new(MachinePoolSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolStatus) DeepCopyInto(out *MachinePoolStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + in.Initialization.DeepCopyInto(&out.Initialization) + if in.NodeRefs != nil { + in, out := &in.NodeRefs, &out.NodeRefs + *out = make([]corev1.ObjectReference, len(*in)) + copy(*out, *in) + } + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + if in.ReadyReplicas != nil { + in, out := &in.ReadyReplicas, &out.ReadyReplicas + *out = new(int32) + **out = **in + } + if in.AvailableReplicas != nil { + in, out := &in.AvailableReplicas, &out.AvailableReplicas + *out = new(int32) + **out = **in + } + if in.UpToDateReplicas != nil { + in, out := &in.UpToDateReplicas, &out.UpToDateReplicas + *out = new(int32) + **out = **in + } + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(MachinePoolDeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolStatus. +func (in *MachinePoolStatus) DeepCopy() *MachinePoolStatus { + if in == nil { + return nil + } + out := new(MachinePoolStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolTopology) DeepCopyInto(out *MachinePoolTopology) { + *out = *in + in.Metadata.DeepCopyInto(&out.Metadata) + if in.FailureDomains != nil { + in, out := &in.FailureDomains, &out.FailureDomains + *out = make([]string, len(*in)) + copy(*out, *in) + } + in.Deletion.DeepCopyInto(&out.Deletion) + if in.MinReadySeconds != nil { + in, out := &in.MinReadySeconds, &out.MinReadySeconds + *out = new(int32) + **out = **in + } + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + in.Variables.DeepCopyInto(&out.Variables) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolTopology. +func (in *MachinePoolTopology) DeepCopy() *MachinePoolTopology { + if in == nil { + return nil + } + out := new(MachinePoolTopology) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolTopologyMachineDeletionSpec) DeepCopyInto(out *MachinePoolTopologyMachineDeletionSpec) { + *out = *in + if in.NodeDrainTimeoutSeconds != nil { + in, out := &in.NodeDrainTimeoutSeconds, &out.NodeDrainTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeVolumeDetachTimeoutSeconds != nil { + in, out := &in.NodeVolumeDetachTimeoutSeconds, &out.NodeVolumeDetachTimeoutSeconds + *out = new(int32) + **out = **in + } + if in.NodeDeletionTimeoutSeconds != nil { + in, out := &in.NodeDeletionTimeoutSeconds, &out.NodeDeletionTimeoutSeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolTopologyMachineDeletionSpec. +func (in *MachinePoolTopologyMachineDeletionSpec) DeepCopy() *MachinePoolTopologyMachineDeletionSpec { + if in == nil { + return nil + } + out := new(MachinePoolTopologyMachineDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolV1Beta1DeprecatedStatus) DeepCopyInto(out *MachinePoolV1Beta1DeprecatedStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.FailureReason != nil { + in, out := &in.FailureReason, &out.FailureReason + *out = new(errors.MachinePoolStatusFailure) + **out = **in + } + if in.FailureMessage != nil { + in, out := &in.FailureMessage, &out.FailureMessage + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolV1Beta1DeprecatedStatus. +func (in *MachinePoolV1Beta1DeprecatedStatus) DeepCopy() *MachinePoolV1Beta1DeprecatedStatus { + if in == nil { + return nil + } + out := new(MachinePoolV1Beta1DeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachinePoolVariables) DeepCopyInto(out *MachinePoolVariables) { + *out = *in + if in.Overrides != nil { + in, out := &in.Overrides, &out.Overrides + *out = make([]ClusterVariable, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolVariables. +func (in *MachinePoolVariables) DeepCopy() *MachinePoolVariables { + if in == nil { + return nil + } + out := new(MachinePoolVariables) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineReadinessGate) DeepCopyInto(out *MachineReadinessGate) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineReadinessGate. +func (in *MachineReadinessGate) DeepCopy() *MachineReadinessGate { + if in == nil { + return nil + } + out := new(MachineReadinessGate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineSet) DeepCopyInto(out *MachineSet) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSet. +func (in *MachineSet) DeepCopy() *MachineSet { + if in == nil { + return nil + } + out := new(MachineSet) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineSet) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineSetDeletionSpec) DeepCopyInto(out *MachineSetDeletionSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetDeletionSpec. +func (in *MachineSetDeletionSpec) DeepCopy() *MachineSetDeletionSpec { + if in == nil { + return nil + } + out := new(MachineSetDeletionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineSetDeprecatedStatus) DeepCopyInto(out *MachineSetDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(MachineSetV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetDeprecatedStatus. +func (in *MachineSetDeprecatedStatus) DeepCopy() *MachineSetDeprecatedStatus { + if in == nil { + return nil + } + out := new(MachineSetDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineSetList) DeepCopyInto(out *MachineSetList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MachineSet, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetList. +func (in *MachineSetList) DeepCopy() *MachineSetList { + if in == nil { + return nil + } + out := new(MachineSetList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MachineSetList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineSetSpec) DeepCopyInto(out *MachineSetSpec) { + *out = *in + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + in.Selector.DeepCopyInto(&out.Selector) + in.Template.DeepCopyInto(&out.Template) + out.MachineNaming = in.MachineNaming + out.Deletion = in.Deletion +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetSpec. +func (in *MachineSetSpec) DeepCopy() *MachineSetSpec { + if in == nil { + return nil + } + out := new(MachineSetSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineSetStatus) DeepCopyInto(out *MachineSetStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + if in.ReadyReplicas != nil { + in, out := &in.ReadyReplicas, &out.ReadyReplicas + *out = new(int32) + **out = **in + } + if in.AvailableReplicas != nil { + in, out := &in.AvailableReplicas, &out.AvailableReplicas + *out = new(int32) + **out = **in + } + if in.UpToDateReplicas != nil { + in, out := &in.UpToDateReplicas, &out.UpToDateReplicas + *out = new(int32) + **out = **in + } + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(MachineSetDeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetStatus. +func (in *MachineSetStatus) DeepCopy() *MachineSetStatus { + if in == nil { + return nil + } + out := new(MachineSetStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineSetV1Beta1DeprecatedStatus) DeepCopyInto(out *MachineSetV1Beta1DeprecatedStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.FailureReason != nil { + in, out := &in.FailureReason, &out.FailureReason + *out = new(errors.MachineSetStatusError) + **out = **in + } + if in.FailureMessage != nil { + in, out := &in.FailureMessage, &out.FailureMessage + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetV1Beta1DeprecatedStatus. +func (in *MachineSetV1Beta1DeprecatedStatus) DeepCopy() *MachineSetV1Beta1DeprecatedStatus { + if in == nil { + return nil + } + out := new(MachineSetV1Beta1DeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineSpec) DeepCopyInto(out *MachineSpec) { + *out = *in + in.Bootstrap.DeepCopyInto(&out.Bootstrap) + out.InfrastructureRef = in.InfrastructureRef + if in.MinReadySeconds != nil { + in, out := &in.MinReadySeconds, &out.MinReadySeconds + *out = new(int32) + **out = **in + } + if in.ReadinessGates != nil { + in, out := &in.ReadinessGates, &out.ReadinessGates + *out = make([]MachineReadinessGate, len(*in)) + copy(*out, *in) + } + in.Deletion.DeepCopyInto(&out.Deletion) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSpec. +func (in *MachineSpec) DeepCopy() *MachineSpec { + if in == nil { + return nil + } + out := new(MachineSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineStatus) DeepCopyInto(out *MachineStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + in.Initialization.DeepCopyInto(&out.Initialization) + out.NodeRef = in.NodeRef + if in.NodeInfo != nil { + in, out := &in.NodeInfo, &out.NodeInfo + *out = new(corev1.NodeSystemInfo) + (*in).DeepCopyInto(*out) + } + in.LastUpdated.DeepCopyInto(&out.LastUpdated) + if in.Addresses != nil { + in, out := &in.Addresses, &out.Addresses + *out = make(MachineAddresses, len(*in)) + copy(*out, *in) + } + in.CertificatesExpiryDate.DeepCopyInto(&out.CertificatesExpiryDate) + if in.Deletion != nil { + in, out := &in.Deletion, &out.Deletion + *out = new(MachineDeletionStatus) + (*in).DeepCopyInto(*out) + } + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(MachineDeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineStatus. +func (in *MachineStatus) DeepCopy() *MachineStatus { + if in == nil { + return nil + } + out := new(MachineStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineTemplateSpec) DeepCopyInto(out *MachineTemplateSpec) { + *out = *in + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineTemplateSpec. +func (in *MachineTemplateSpec) DeepCopy() *MachineTemplateSpec { + if in == nil { + return nil + } + out := new(MachineTemplateSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MachineV1Beta1DeprecatedStatus) DeepCopyInto(out *MachineV1Beta1DeprecatedStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.FailureReason != nil { + in, out := &in.FailureReason, &out.FailureReason + *out = new(errors.MachineStatusError) + **out = **in + } + if in.FailureMessage != nil { + in, out := &in.FailureMessage, &out.FailureMessage + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineV1Beta1DeprecatedStatus. +func (in *MachineV1Beta1DeprecatedStatus) DeepCopy() *MachineV1Beta1DeprecatedStatus { + if in == nil { + return nil + } + out := new(MachineV1Beta1DeprecatedStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NetworkRanges) DeepCopyInto(out *NetworkRanges) { + *out = *in + if in.CIDRBlocks != nil { + in, out := &in.CIDRBlocks, &out.CIDRBlocks + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkRanges. +func (in *NetworkRanges) DeepCopy() *NetworkRanges { + if in == nil { + return nil + } + out := new(NetworkRanges) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ObjectMeta) DeepCopyInto(out *ObjectMeta) { + *out = *in + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Annotations != nil { + in, out := &in.Annotations, &out.Annotations + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectMeta. +func (in *ObjectMeta) DeepCopy() *ObjectMeta { + if in == nil { + return nil + } + out := new(ObjectMeta) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PatchDefinition) DeepCopyInto(out *PatchDefinition) { + *out = *in + in.Selector.DeepCopyInto(&out.Selector) + if in.JSONPatches != nil { + in, out := &in.JSONPatches, &out.JSONPatches + *out = make([]JSONPatch, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PatchDefinition. +func (in *PatchDefinition) DeepCopy() *PatchDefinition { + if in == nil { + return nil + } + out := new(PatchDefinition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PatchSelector) DeepCopyInto(out *PatchSelector) { + *out = *in + in.MatchResources.DeepCopyInto(&out.MatchResources) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PatchSelector. +func (in *PatchSelector) DeepCopy() *PatchSelector { + if in == nil { + return nil + } + out := new(PatchSelector) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PatchSelectorMatch) DeepCopyInto(out *PatchSelectorMatch) { + *out = *in + if in.ControlPlane != nil { + in, out := &in.ControlPlane, &out.ControlPlane + *out = new(bool) + **out = **in + } + if in.InfrastructureCluster != nil { + in, out := &in.InfrastructureCluster, &out.InfrastructureCluster + *out = new(bool) + **out = **in + } + if in.MachineDeploymentClass != nil { + in, out := &in.MachineDeploymentClass, &out.MachineDeploymentClass + *out = new(PatchSelectorMatchMachineDeploymentClass) + (*in).DeepCopyInto(*out) + } + if in.MachinePoolClass != nil { + in, out := &in.MachinePoolClass, &out.MachinePoolClass + *out = new(PatchSelectorMatchMachinePoolClass) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PatchSelectorMatch. +func (in *PatchSelectorMatch) DeepCopy() *PatchSelectorMatch { + if in == nil { + return nil + } + out := new(PatchSelectorMatch) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PatchSelectorMatchMachineDeploymentClass) DeepCopyInto(out *PatchSelectorMatchMachineDeploymentClass) { + *out = *in + if in.Names != nil { + in, out := &in.Names, &out.Names + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PatchSelectorMatchMachineDeploymentClass. +func (in *PatchSelectorMatchMachineDeploymentClass) DeepCopy() *PatchSelectorMatchMachineDeploymentClass { + if in == nil { + return nil + } + out := new(PatchSelectorMatchMachineDeploymentClass) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PatchSelectorMatchMachinePoolClass) DeepCopyInto(out *PatchSelectorMatchMachinePoolClass) { + *out = *in + if in.Names != nil { + in, out := &in.Names, &out.Names + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PatchSelectorMatchMachinePoolClass. +func (in *PatchSelectorMatchMachinePoolClass) DeepCopy() *PatchSelectorMatchMachinePoolClass { + if in == nil { + return nil + } + out := new(PatchSelectorMatchMachinePoolClass) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Topology) DeepCopyInto(out *Topology) { + *out = *in + out.ClassRef = in.ClassRef + in.ControlPlane.DeepCopyInto(&out.ControlPlane) + in.Workers.DeepCopyInto(&out.Workers) + if in.Variables != nil { + in, out := &in.Variables, &out.Variables + *out = make([]ClusterVariable, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Topology. +func (in *Topology) DeepCopy() *Topology { + if in == nil { + return nil + } + out := new(Topology) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *UnhealthyNodeCondition) DeepCopyInto(out *UnhealthyNodeCondition) { + *out = *in + if in.TimeoutSeconds != nil { + in, out := &in.TimeoutSeconds, &out.TimeoutSeconds + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UnhealthyNodeCondition. +func (in *UnhealthyNodeCondition) DeepCopy() *UnhealthyNodeCondition { + if in == nil { + return nil + } + out := new(UnhealthyNodeCondition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ValidationRule) DeepCopyInto(out *ValidationRule) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidationRule. +func (in *ValidationRule) DeepCopy() *ValidationRule { + if in == nil { + return nil + } + out := new(ValidationRule) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *VariableSchema) DeepCopyInto(out *VariableSchema) { + *out = *in + in.OpenAPIV3Schema.DeepCopyInto(&out.OpenAPIV3Schema) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VariableSchema. +func (in *VariableSchema) DeepCopy() *VariableSchema { + if in == nil { + return nil + } + out := new(VariableSchema) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *VariableSchemaMetadata) DeepCopyInto(out *VariableSchemaMetadata) { + *out = *in + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Annotations != nil { + in, out := &in.Annotations, &out.Annotations + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VariableSchemaMetadata. +func (in *VariableSchemaMetadata) DeepCopy() *VariableSchemaMetadata { + if in == nil { + return nil + } + out := new(VariableSchemaMetadata) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkersClass) DeepCopyInto(out *WorkersClass) { + *out = *in + if in.MachineDeployments != nil { + in, out := &in.MachineDeployments, &out.MachineDeployments + *out = make([]MachineDeploymentClass, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.MachinePools != nil { + in, out := &in.MachinePools, &out.MachinePools + *out = make([]MachinePoolClass, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkersClass. +func (in *WorkersClass) DeepCopy() *WorkersClass { + if in == nil { + return nil + } + out := new(WorkersClass) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkersStatus) DeepCopyInto(out *WorkersStatus) { + *out = *in + if in.DesiredReplicas != nil { + in, out := &in.DesiredReplicas, &out.DesiredReplicas + *out = new(int32) + **out = **in + } + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } + if in.UpToDateReplicas != nil { + in, out := &in.UpToDateReplicas, &out.UpToDateReplicas + *out = new(int32) + **out = **in + } + if in.ReadyReplicas != nil { + in, out := &in.ReadyReplicas, &out.ReadyReplicas + *out = new(int32) + **out = **in + } + if in.AvailableReplicas != nil { + in, out := &in.AvailableReplicas, &out.AvailableReplicas + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkersStatus. +func (in *WorkersStatus) DeepCopy() *WorkersStatus { + if in == nil { + return nil + } + out := new(WorkersStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkersTopology) DeepCopyInto(out *WorkersTopology) { + *out = *in + if in.MachineDeployments != nil { + in, out := &in.MachineDeployments, &out.MachineDeployments + *out = make([]MachineDeploymentTopology, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.MachinePools != nil { + in, out := &in.MachinePools, &out.MachinePools + *out = make([]MachinePoolTopology, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkersTopology. +func (in *WorkersTopology) DeepCopy() *WorkersTopology { + if in == nil { + return nil + } + out := new(WorkersTopology) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/zz_generated.openapi.go b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/zz_generated.openapi.go new file mode 100644 index 000000000000..6ada26c78cd5 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/core/v1beta2/zz_generated.openapi.go @@ -0,0 +1,6838 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by openapi-gen. DO NOT EDIT. + +package v1beta2 + +import ( + common "k8s.io/kube-openapi/pkg/common" + spec "k8s.io/kube-openapi/pkg/validation/spec" +) + +func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { + return map[string]common.OpenAPIDefinition{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.APIEndpoint": schema_cluster_api_api_core_v1beta2_APIEndpoint(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.Bootstrap": schema_cluster_api_api_core_v1beta2_Bootstrap(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.Cluster": schema_cluster_api_api_core_v1beta2_Cluster(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterAvailabilityGate": schema_cluster_api_api_core_v1beta2_ClusterAvailabilityGate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClass": schema_cluster_api_api_core_v1beta2_ClusterClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassDeprecatedStatus": schema_cluster_api_api_core_v1beta2_ClusterClassDeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassList": schema_cluster_api_api_core_v1beta2_ClusterClassList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassPatch": schema_cluster_api_api_core_v1beta2_ClusterClassPatch(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassRef": schema_cluster_api_api_core_v1beta2_ClusterClassRef(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassSpec": schema_cluster_api_api_core_v1beta2_ClusterClassSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatus": schema_cluster_api_api_core_v1beta2_ClusterClassStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatusVariable": schema_cluster_api_api_core_v1beta2_ClusterClassStatusVariable(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatusVariableDefinition": schema_cluster_api_api_core_v1beta2_ClusterClassStatusVariableDefinition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference": schema_cluster_api_api_core_v1beta2_ClusterClassTemplateReference(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassV1Beta1DeprecatedStatus": schema_cluster_api_api_core_v1beta2_ClusterClassV1Beta1DeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassVariable": schema_cluster_api_api_core_v1beta2_ClusterClassVariable(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassVariableMetadata": schema_cluster_api_api_core_v1beta2_ClusterClassVariableMetadata(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterControlPlaneStatus": schema_cluster_api_api_core_v1beta2_ClusterControlPlaneStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterDeprecatedStatus": schema_cluster_api_api_core_v1beta2_ClusterDeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterInitializationStatus": schema_cluster_api_api_core_v1beta2_ClusterInitializationStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterList": schema_cluster_api_api_core_v1beta2_ClusterList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterNetwork": schema_cluster_api_api_core_v1beta2_ClusterNetwork(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterSpec": schema_cluster_api_api_core_v1beta2_ClusterSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterStatus": schema_cluster_api_api_core_v1beta2_ClusterStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterV1Beta1DeprecatedStatus": schema_cluster_api_api_core_v1beta2_ClusterV1Beta1DeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable": schema_cluster_api_api_core_v1beta2_ClusterVariable(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.Condition": schema_cluster_api_api_core_v1beta2_Condition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference": schema_cluster_api_api_core_v1beta2_ContractVersionedObjectReference(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClass": schema_cluster_api_api_core_v1beta2_ControlPlaneClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheck": schema_cluster_api_api_core_v1beta2_ControlPlaneClassHealthCheck(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckChecks": schema_cluster_api_api_core_v1beta2_ControlPlaneClassHealthCheckChecks(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckRemediation": schema_cluster_api_api_core_v1beta2_ControlPlaneClassHealthCheckRemediation(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckRemediationTriggerIf": schema_cluster_api_api_core_v1beta2_ControlPlaneClassHealthCheckRemediationTriggerIf(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassMachineDeletionSpec": schema_cluster_api_api_core_v1beta2_ControlPlaneClassMachineDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassMachineInfrastructureTemplate": schema_cluster_api_api_core_v1beta2_ControlPlaneClassMachineInfrastructureTemplate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassNamingSpec": schema_cluster_api_api_core_v1beta2_ControlPlaneClassNamingSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopology": schema_cluster_api_api_core_v1beta2_ControlPlaneTopology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheck": schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyHealthCheck(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckChecks": schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyHealthCheckChecks(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckRemediation": schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyHealthCheckRemediation(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckRemediationTriggerIf": schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyHealthCheckRemediationTriggerIf(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyMachineDeletionSpec": schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyMachineDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneVariables": schema_cluster_api_api_core_v1beta2_ControlPlaneVariables(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ExternalPatchDefinition": schema_cluster_api_api_core_v1beta2_ExternalPatchDefinition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.FailureDomain": schema_cluster_api_api_core_v1beta2_FailureDomain(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.InfrastructureClass": schema_cluster_api_api_core_v1beta2_InfrastructureClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.InfrastructureClassNamingSpec": schema_cluster_api_api_core_v1beta2_InfrastructureClassNamingSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.JSONPatch": schema_cluster_api_api_core_v1beta2_JSONPatch(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.JSONPatchValue": schema_cluster_api_api_core_v1beta2_JSONPatchValue(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps": schema_cluster_api_api_core_v1beta2_JSONSchemaProps(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.Machine": schema_cluster_api_api_core_v1beta2_Machine(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineAddress": schema_cluster_api_api_core_v1beta2_MachineAddress(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeletionSpec": schema_cluster_api_api_core_v1beta2_MachineDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeletionStatus": schema_cluster_api_api_core_v1beta2_MachineDeletionStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeployment": schema_cluster_api_api_core_v1beta2_MachineDeployment(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClass": schema_cluster_api_api_core_v1beta2_MachineDeploymentClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassBootstrapTemplate": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassBootstrapTemplate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheck": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassHealthCheck(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckChecks": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassHealthCheckChecks(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckRemediation": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassHealthCheckRemediation(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckRemediationTriggerIf": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassHealthCheckRemediationTriggerIf(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassInfrastructureTemplate": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassInfrastructureTemplate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassMachineDeletionSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassMachineDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassNamingSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassNamingSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassRolloutSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutStrategy": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassRolloutStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutStrategyRollingUpdate": schema_cluster_api_api_core_v1beta2_MachineDeploymentClassRolloutStrategyRollingUpdate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentDeletionSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentDeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachineDeploymentDeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentList": schema_cluster_api_api_core_v1beta2_MachineDeploymentList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRemediationSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentRemediationSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentRolloutSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutStrategy": schema_cluster_api_api_core_v1beta2_MachineDeploymentRolloutStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutStrategyRollingUpdate": schema_cluster_api_api_core_v1beta2_MachineDeploymentRolloutStrategyRollingUpdate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentStatus": schema_cluster_api_api_core_v1beta2_MachineDeploymentStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopology": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheck": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyHealthCheck(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckChecks": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyHealthCheckChecks(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckRemediation": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyHealthCheckRemediation(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckRemediationTriggerIf": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyHealthCheckRemediationTriggerIf(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyMachineDeletionSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyMachineDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutSpec": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyRolloutSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutStrategy": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyRolloutStrategy(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutStrategyRollingUpdate": schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyRolloutStrategyRollingUpdate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentV1Beta1DeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachineDeploymentV1Beta1DeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentVariables": schema_cluster_api_api_core_v1beta2_MachineDeploymentVariables(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachineDeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRule": schema_cluster_api_api_core_v1beta2_MachineDrainRule(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleDrainConfig": schema_cluster_api_api_core_v1beta2_MachineDrainRuleDrainConfig(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleList": schema_cluster_api_api_core_v1beta2_MachineDrainRuleList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleMachineSelector": schema_cluster_api_api_core_v1beta2_MachineDrainRuleMachineSelector(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRulePodSelector": schema_cluster_api_api_core_v1beta2_MachineDrainRulePodSelector(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleSpec": schema_cluster_api_api_core_v1beta2_MachineDrainRuleSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheck": schema_cluster_api_api_core_v1beta2_MachineHealthCheck(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckChecks": schema_cluster_api_api_core_v1beta2_MachineHealthCheckChecks(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckDeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachineHealthCheckDeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckList": schema_cluster_api_api_core_v1beta2_MachineHealthCheckList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediation": schema_cluster_api_api_core_v1beta2_MachineHealthCheckRemediation(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference": schema_cluster_api_api_core_v1beta2_MachineHealthCheckRemediationTemplateReference(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTriggerIf": schema_cluster_api_api_core_v1beta2_MachineHealthCheckRemediationTriggerIf(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckSpec": schema_cluster_api_api_core_v1beta2_MachineHealthCheckSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckStatus": schema_cluster_api_api_core_v1beta2_MachineHealthCheckStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckV1Beta1DeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachineHealthCheckV1Beta1DeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineInitializationStatus": schema_cluster_api_api_core_v1beta2_MachineInitializationStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineList": schema_cluster_api_api_core_v1beta2_MachineList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNamingSpec": schema_cluster_api_api_core_v1beta2_MachineNamingSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNodeReference": schema_cluster_api_api_core_v1beta2_MachineNodeReference(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePool": schema_cluster_api_api_core_v1beta2_MachinePool(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClass": schema_cluster_api_api_core_v1beta2_MachinePoolClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassBootstrapTemplate": schema_cluster_api_api_core_v1beta2_MachinePoolClassBootstrapTemplate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassInfrastructureTemplate": schema_cluster_api_api_core_v1beta2_MachinePoolClassInfrastructureTemplate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassMachineDeletionSpec": schema_cluster_api_api_core_v1beta2_MachinePoolClassMachineDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassNamingSpec": schema_cluster_api_api_core_v1beta2_MachinePoolClassNamingSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolDeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachinePoolDeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolInitializationStatus": schema_cluster_api_api_core_v1beta2_MachinePoolInitializationStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolList": schema_cluster_api_api_core_v1beta2_MachinePoolList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolSpec": schema_cluster_api_api_core_v1beta2_MachinePoolSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolStatus": schema_cluster_api_api_core_v1beta2_MachinePoolStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolTopology": schema_cluster_api_api_core_v1beta2_MachinePoolTopology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolTopologyMachineDeletionSpec": schema_cluster_api_api_core_v1beta2_MachinePoolTopologyMachineDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolV1Beta1DeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachinePoolV1Beta1DeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolVariables": schema_cluster_api_api_core_v1beta2_MachinePoolVariables(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate": schema_cluster_api_api_core_v1beta2_MachineReadinessGate(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSet": schema_cluster_api_api_core_v1beta2_MachineSet(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetDeletionSpec": schema_cluster_api_api_core_v1beta2_MachineSetDeletionSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetDeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachineSetDeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetList": schema_cluster_api_api_core_v1beta2_MachineSetList(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetSpec": schema_cluster_api_api_core_v1beta2_MachineSetSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetStatus": schema_cluster_api_api_core_v1beta2_MachineSetStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetV1Beta1DeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachineSetV1Beta1DeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSpec": schema_cluster_api_api_core_v1beta2_MachineSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineStatus": schema_cluster_api_api_core_v1beta2_MachineStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineTemplateSpec": schema_cluster_api_api_core_v1beta2_MachineTemplateSpec(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineV1Beta1DeprecatedStatus": schema_cluster_api_api_core_v1beta2_MachineV1Beta1DeprecatedStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.NetworkRanges": schema_cluster_api_api_core_v1beta2_NetworkRanges(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta": schema_cluster_api_api_core_v1beta2_ObjectMeta(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchDefinition": schema_cluster_api_api_core_v1beta2_PatchDefinition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelector": schema_cluster_api_api_core_v1beta2_PatchSelector(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatch": schema_cluster_api_api_core_v1beta2_PatchSelectorMatch(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatchMachineDeploymentClass": schema_cluster_api_api_core_v1beta2_PatchSelectorMatchMachineDeploymentClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatchMachinePoolClass": schema_cluster_api_api_core_v1beta2_PatchSelectorMatchMachinePoolClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.Topology": schema_cluster_api_api_core_v1beta2_Topology(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition": schema_cluster_api_api_core_v1beta2_UnhealthyNodeCondition(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.ValidationRule": schema_cluster_api_api_core_v1beta2_ValidationRule(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchema": schema_cluster_api_api_core_v1beta2_VariableSchema(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchemaMetadata": schema_cluster_api_api_core_v1beta2_VariableSchemaMetadata(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersClass": schema_cluster_api_api_core_v1beta2_WorkersClass(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersStatus": schema_cluster_api_api_core_v1beta2_WorkersStatus(ref), + "sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersTopology": schema_cluster_api_api_core_v1beta2_WorkersTopology(ref), + } +} + +func schema_cluster_api_api_core_v1beta2_APIEndpoint(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "APIEndpoint represents a reachable Kubernetes API endpoint.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "host": { + SchemaProps: spec.SchemaProps{ + Description: "host is the hostname on which the API server is serving.", + Type: []string{"string"}, + Format: "", + }, + }, + "port": { + SchemaProps: spec.SchemaProps{ + Description: "port is the port on which the API server is serving.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_Bootstrap(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Bootstrap encapsulates fields to configure the Machine’s bootstrapping mechanism.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "configRef": { + SchemaProps: spec.SchemaProps{ + Description: "configRef is a reference to a bootstrap provider-specific resource that holds configuration details. The reference is optional to allow users/operators to specify Bootstrap.DataSecretName without the need of a controller.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference"), + }, + }, + "dataSecretName": { + SchemaProps: spec.SchemaProps{ + Description: "dataSecretName is the name of the secret that stores the bootstrap data script. If nil, the Machine should remain in the Pending state.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_Cluster(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Cluster is the Schema for the clusters API.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the desired state of Cluster.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status is the observed state of Cluster.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterAvailabilityGate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterAvailabilityGate contains the type of a Cluster condition to be used as availability gate.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditionType": { + SchemaProps: spec.SchemaProps{ + Description: "conditionType refers to a condition with matching type in the Cluster's condition list. If the conditions doesn't exist, it will be treated as unknown. Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as availability gates.", + Type: []string{"string"}, + Format: "", + }, + }, + "polarity": { + SchemaProps: spec.SchemaProps{ + Description: "polarity of the conditionType specified in this availabilityGate. Valid values are Positive, Negative and omitted. When omitted, the default behaviour will be Positive. A positive polarity means that the condition should report a true status under normal conditions. A negative polarity means that the condition should report a false status under normal conditions.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"conditionType"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClass(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClass is a template which can be used to create managed topologies. NOTE: This CRD can only be used if the ClusterTopology feature gate is enabled.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the desired state of ClusterClass.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status is the observed state of ClusterClass.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassDeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "v1beta1": { + SchemaProps: spec.SchemaProps{ + Description: "v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassV1Beta1DeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassV1Beta1DeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassList contains a list of Cluster.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items is the list of ClusterClasses.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClass"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClass"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassPatch(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassPatch defines a patch which is applied to customize the referenced templates.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name of the patch.", + Type: []string{"string"}, + Format: "", + }, + }, + "description": { + SchemaProps: spec.SchemaProps{ + Description: "description is a human-readable description of this patch.", + Type: []string{"string"}, + Format: "", + }, + }, + "enabledIf": { + SchemaProps: spec.SchemaProps{ + Description: "enabledIf is a Go template to be used to calculate if a patch should be enabled. It can reference variables defined in .spec.variables and builtin variables. The patch will be enabled if the template evaluates to `true`, otherwise it will be disabled. If EnabledIf is not set, the patch will be enabled per default.", + Type: []string{"string"}, + Format: "", + }, + }, + "definitions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "definitions define inline patches. Note: Patches will be applied in the order of the array. Note: Exactly one of Definitions or External must be set.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.PatchDefinition"), + }, + }, + }, + }, + }, + "external": { + SchemaProps: spec.SchemaProps{ + Description: "external defines an external patch. Note: Exactly one of Definitions or External must be set.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ExternalPatchDefinition"), + }, + }, + }, + Required: []string{"name"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ExternalPatchDefinition", "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchDefinition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassRef(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassRef is the ref to the ClusterClass that should be used for the topology.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name is the name of the ClusterClass that should be used for the topology. name must be a valid ClusterClass name and because of that be at most 253 characters in length and it must consist only of lower case alphanumeric characters, hyphens (-) and periods (.), and must start and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + "namespace": { + SchemaProps: spec.SchemaProps{ + Description: "namespace is the namespace of the ClusterClass that should be used for the topology. If namespace is empty or not set, it is defaulted to the namespace of the Cluster object. namespace must be a valid namespace name and because of that be at most 63 characters in length and it must consist only of lower case alphanumeric characters or hyphens (-), and must start and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"name"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassSpec describes the desired state of the ClusterClass.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "availabilityGates": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "conditionType", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "availabilityGates specifies additional conditions to include when evaluating Cluster Available condition.\n\nNOTE: If a Cluster is using this ClusterClass, and this Cluster defines a custom list of availabilityGates, such list overrides availabilityGates defined in this field.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterAvailabilityGate"), + }, + }, + }, + }, + }, + "infrastructure": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructure is a reference to a local struct that holds the details for provisioning the infrastructure cluster for the Cluster.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.InfrastructureClass"), + }, + }, + "controlPlane": { + SchemaProps: spec.SchemaProps{ + Description: "controlPlane is a reference to a local struct that holds the details for provisioning the Control Plane for the Cluster.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClass"), + }, + }, + "workers": { + SchemaProps: spec.SchemaProps{ + Description: "workers describes the worker nodes for the cluster. It is a collection of node types which can be used to create the worker nodes of the cluster.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersClass"), + }, + }, + "variables": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "variables defines the variables which can be configured in the Cluster topology and are then used in patches.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassVariable"), + }, + }, + }, + }, + }, + "patches": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "patches defines the patches which are applied to customize referenced templates of a ClusterClass. Note: Patches will be applied in the order of the array.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassPatch"), + }, + }, + }, + }, + }, + }, + Required: []string{"infrastructure", "controlPlane"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterAvailabilityGate", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassPatch", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassVariable", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClass", "sigs.k8s.io/cluster-api/api/core/v1beta2.InfrastructureClass", "sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersClass"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassStatus defines the observed state of the ClusterClass.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observations of a ClusterClass's current state. Known condition types are VariablesReady, RefVersionsUpToDate, Paused.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "variables": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "variables is a list of ClusterClassStatusVariable that are defined for the ClusterClass.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatusVariable"), + }, + }, + }, + }, + }, + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "observedGeneration is the latest generation observed by the controller.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "deprecated": { + SchemaProps: spec.SchemaProps{ + Description: "deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassDeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassDeprecatedStatus", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatusVariable"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassStatusVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassStatusVariable defines a variable which appears in the status of a ClusterClass.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name is the name of the variable.", + Type: []string{"string"}, + Format: "", + }, + }, + "definitionsConflict": { + SchemaProps: spec.SchemaProps{ + Description: "definitionsConflict specifies whether or not there are conflicting definitions for a single variable name.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "definitions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "definitions is a list of definitions for a variable.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatusVariableDefinition"), + }, + }, + }, + }, + }, + }, + Required: []string{"name", "definitions"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassStatusVariableDefinition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassStatusVariableDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassStatusVariableDefinition defines a variable which appears in the status of a ClusterClass.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "from": { + SchemaProps: spec.SchemaProps{ + Description: "from specifies the origin of the variable definition. This will be `inline` for variables defined in the ClusterClass or the name of a patch defined in the ClusterClass for variables discovered from a DiscoverVariables runtime extensions.", + Type: []string{"string"}, + Format: "", + }, + }, + "required": { + SchemaProps: spec.SchemaProps{ + Description: "required specifies if the variable is required. Note: this applies to the variable as a whole and thus the top-level object defined in the schema. If nested fields are required, this will be specified inside the schema.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "deprecatedV1Beta1Metadata": { + SchemaProps: spec.SchemaProps{ + Description: "deprecatedV1Beta1Metadata is the metadata of a variable. It can be used to add additional data for higher level tools to a ClusterClassVariable.\n\nDeprecated: This field is deprecated and will be removed when support for v1beta1 will be dropped. Please use XMetadata in JSONSchemaProps instead.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassVariableMetadata"), + }, + }, + "schema": { + SchemaProps: spec.SchemaProps{ + Description: "schema defines the schema of the variable.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchema"), + }, + }, + }, + Required: []string{"from", "required", "schema"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassVariableMetadata", "sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchema"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassTemplateReference(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassTemplateReference is a reference to a ClusterClass template.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "kind of the template. kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name of the template. name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "apiVersion of the template. apiVersion must be fully qualified domain name followed by / and a version.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"kind", "name", "apiVersion"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassV1Beta1DeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + SchemaProps: spec.SchemaProps{ + Description: "conditions defines current observed state of the ClusterClass.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassVariable defines a variable which can be configured in the Cluster topology and used in patches.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name of the variable.", + Type: []string{"string"}, + Format: "", + }, + }, + "required": { + SchemaProps: spec.SchemaProps{ + Description: "required specifies if the variable is required. Note: this applies to the variable as a whole and thus the top-level object defined in the schema. If nested fields are required, this will be specified inside the schema.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "deprecatedV1Beta1Metadata": { + SchemaProps: spec.SchemaProps{ + Description: "deprecatedV1Beta1Metadata is the metadata of a variable. It can be used to add additional data for higher level tools to a ClusterClassVariable.\n\nDeprecated: This field is deprecated and will be removed when support for v1beta1 will be dropped. Please use XMetadata in JSONSchemaProps instead.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassVariableMetadata"), + }, + }, + "schema": { + SchemaProps: spec.SchemaProps{ + Description: "schema defines the schema of the variable.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchema"), + }, + }, + }, + Required: []string{"name", "required", "schema"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassVariableMetadata", "sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchema"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterClassVariableMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterClassVariableMetadata is the metadata of a variable. It can be used to add additional data for higher level tools to a ClusterClassVariable.\n\nDeprecated: This struct is deprecated and is going to be removed in the next apiVersion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "labels": { + SchemaProps: spec.SchemaProps{ + Description: "labels is a map of string keys and values that can be used to organize and categorize (scope and select) variables.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "annotations": { + SchemaProps: spec.SchemaProps{ + Description: "annotations is an unstructured key value map that can be used to store and retrieve arbitrary metadata. They are not queryable.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterControlPlaneStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterControlPlaneStatus groups all the observations about control plane current state.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "desiredReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "desiredReplicas is the total number of desired control plane machines in this cluster.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the total number of control plane machines in this cluster. NOTE: replicas also includes machines still being provisioned or being deleted.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "upToDateReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "upToDateReplicas is the number of up-to-date control plane machines in this cluster. A machine is considered up-to-date when Machine's UpToDate condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the total number of ready control plane machines in this cluster. A machine is considered ready when Machine's Ready condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the total number of available control plane machines in this cluster. A machine is considered available when Machine's Available condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterDeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "v1beta1": { + SchemaProps: spec.SchemaProps{ + Description: "v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterV1Beta1DeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterV1Beta1DeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterInitializationStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterInitializationStatus provides observations of the Cluster initialization process. NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Cluster provisioning.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "infrastructureProvisioned": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructureProvisioned is true when the infrastructure provider reports that Cluster's infrastructure is fully provisioned. NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. The value of this field is never updated after provisioning is completed.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "controlPlaneInitialized": { + SchemaProps: spec.SchemaProps{ + Description: "controlPlaneInitialized denotes when the control plane is functional enough to accept requests. This information is usually used as a signal for starting all the provisioning operations that depends on a functional API server, but do not require a full HA control plane to exists, like e.g. join worker Machines, install core addons like CNI, CPI, CSI etc. NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. The value of this field is never updated after initialization is completed.", + Type: []string{"boolean"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterList contains a list of Cluster.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items is the list of Clusters.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Cluster"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.Cluster"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterNetwork(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterNetwork specifies the different networking parameters for a cluster.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "apiServerPort": { + SchemaProps: spec.SchemaProps{ + Description: "apiServerPort specifies the port the API Server should bind to. Defaults to 6443.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "services": { + SchemaProps: spec.SchemaProps{ + Description: "services is the network ranges from which service VIPs are allocated.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.NetworkRanges"), + }, + }, + "pods": { + SchemaProps: spec.SchemaProps{ + Description: "pods is the network ranges from which Pod networks are allocated.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.NetworkRanges"), + }, + }, + "serviceDomain": { + SchemaProps: spec.SchemaProps{ + Description: "serviceDomain is the domain name for services.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.NetworkRanges"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterSpec defines the desired state of Cluster.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "paused": { + SchemaProps: spec.SchemaProps{ + Description: "paused can be used to prevent controllers from processing the Cluster and all its associated objects.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "clusterNetwork": { + SchemaProps: spec.SchemaProps{ + Description: "clusterNetwork represents the cluster network configuration.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterNetwork"), + }, + }, + "controlPlaneEndpoint": { + SchemaProps: spec.SchemaProps{ + Description: "controlPlaneEndpoint represents the endpoint used to communicate with the control plane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.APIEndpoint"), + }, + }, + "controlPlaneRef": { + SchemaProps: spec.SchemaProps{ + Description: "controlPlaneRef is an optional reference to a provider-specific resource that holds the details for provisioning the Control Plane for a Cluster.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference"), + }, + }, + "infrastructureRef": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructureRef is a reference to a provider-specific resource that holds the details for provisioning infrastructure for a cluster in said provider.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference"), + }, + }, + "topology": { + SchemaProps: spec.SchemaProps{ + Description: "topology encapsulates the topology for the cluster. NOTE: It is required to enable the ClusterTopology feature gate flag to activate managed topologies support; this feature is highly experimental, and parts of it might still be not implemented.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Topology"), + }, + }, + "availabilityGates": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "conditionType", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "availabilityGates specifies additional conditions to include when evaluating Cluster Available condition.\n\nIf this field is not defined and the Cluster implements a managed topology, availabilityGates from the corresponding ClusterClass will be used, if any.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterAvailabilityGate"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.APIEndpoint", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterAvailabilityGate", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterNetwork", "sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference", "sigs.k8s.io/cluster-api/api/core/v1beta2.Topology"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterStatus defines the observed state of Cluster.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observations of a Cluster's current state. Known condition types are Available, InfrastructureReady, ControlPlaneInitialized, ControlPlaneAvailable, WorkersAvailable, MachinesReady MachinesUpToDate, RemoteConnectionProbe, ScalingUp, ScalingDown, Remediating, Deleting, Paused. Additionally, a TopologyReconciled condition will be added in case the Cluster is referencing a ClusterClass / defining a managed Topology.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "initialization": { + SchemaProps: spec.SchemaProps{ + Description: "initialization provides observations of the Cluster initialization process. NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Cluster provisioning.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterInitializationStatus"), + }, + }, + "controlPlane": { + SchemaProps: spec.SchemaProps{ + Description: "controlPlane groups all the observations about Cluster's ControlPlane current state.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterControlPlaneStatus"), + }, + }, + "workers": { + SchemaProps: spec.SchemaProps{ + Description: "workers groups all the observations about Cluster's Workers current state.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersStatus"), + }, + }, + "failureDomains": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "name", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "failureDomains is a slice of failure domain objects synced from the infrastructure provider.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.FailureDomain"), + }, + }, + }, + }, + }, + "phase": { + SchemaProps: spec.SchemaProps{ + Description: "phase represents the current phase of cluster actuation.", + Type: []string{"string"}, + Format: "", + }, + }, + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "observedGeneration is the latest generation observed by the controller.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "deprecated": { + SchemaProps: spec.SchemaProps{ + Description: "deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterDeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterControlPlaneStatus", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterDeprecatedStatus", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterInitializationStatus", "sigs.k8s.io/cluster-api/api/core/v1beta2.FailureDomain", "sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterV1Beta1DeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + SchemaProps: spec.SchemaProps{ + Description: "conditions defines current service state of the cluster.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"), + }, + }, + }, + }, + }, + "failureReason": { + SchemaProps: spec.SchemaProps{ + Description: "failureReason indicates that there is a fatal problem reconciling the state, and will be set to a token value suitable for programmatic interpretation.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + "failureMessage": { + SchemaProps: spec.SchemaProps{ + Description: "failureMessage indicates that there is a fatal problem reconciling the state, and will be set to a descriptive error message.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ClusterVariable(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ClusterVariable can be used to customize the Cluster through patches. Each ClusterVariable is associated with a Variable definition in the ClusterClass `status` variables.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name of the variable.", + Type: []string{"string"}, + Format: "", + }, + }, + "value": { + SchemaProps: spec.SchemaProps{ + Description: "value of the variable. Note: the value will be validated against the schema of the corresponding ClusterClassVariable from the ClusterClass. Note: We have to use apiextensionsv1.JSON instead of a custom JSON type, because controller-tools has a hard-coded schema for apiextensionsv1.JSON which cannot be produced by another type via controller-tools, i.e. it is not possible to have no type field. Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111", + Ref: ref("k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON"), + }, + }, + }, + Required: []string{"name", "value"}, + }, + }, + Dependencies: []string{ + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON"}, + } +} + +func schema_cluster_api_api_core_v1beta2_Condition(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Condition defines an observation of a Cluster API resource operational state.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "type": { + SchemaProps: spec.SchemaProps{ + Description: "type of condition in CamelCase or in foo.example.com/CamelCase. Many .condition.type values are consistent across resources like Available, but because arbitrary conditions can be useful (see .node.status.conditions), the ability to deconflict is important.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status of the condition, one of True, False, Unknown.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "severity": { + SchemaProps: spec.SchemaProps{ + Description: "severity provides an explicit classification of Reason code, so the users or machines can immediately understand the current situation and act accordingly. The Severity field MUST be set only when Status=False.", + Type: []string{"string"}, + Format: "", + }, + }, + "lastTransitionTime": { + SchemaProps: spec.SchemaProps{ + Description: "lastTransitionTime is the last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), + }, + }, + "reason": { + SchemaProps: spec.SchemaProps{ + Description: "reason is the reason for the condition's last transition in CamelCase. The specific API may choose whether or not this field is considered a guaranteed API. This field may be empty.", + Type: []string{"string"}, + Format: "", + }, + }, + "message": { + SchemaProps: spec.SchemaProps{ + Description: "message is a human readable message indicating details about the transition. This field may be empty.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"type", "status", "lastTransitionTime"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ContractVersionedObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ContractVersionedObjectReference is a reference to a resource for which the version is inferred from contract labels.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "kind of the resource being referenced. kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name of the resource being referenced. name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + "apiGroup": { + SchemaProps: spec.SchemaProps{ + Description: "apiGroup is the group of the resource being referenced. apiGroup must be fully qualified domain name. The corresponding version for this reference will be looked up from the contract labels of the corresponding CRD of the resource being referenced.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"kind", "name", "apiGroup"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneClass(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneClass defines the class for the control plane.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the metadata applied to the ControlPlane and the Machines of the ControlPlane if the ControlPlaneTemplate referenced is machine based. If not, it is applied only to the ControlPlane. At runtime this metadata is merged with the corresponding metadata from the topology.\n\nThis field is supported if and only if the control plane provider template referenced is Machine based.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"), + }, + }, + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef contains the reference to a provider-specific control plane template.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"), + }, + }, + "machineInfrastructure": { + SchemaProps: spec.SchemaProps{ + Description: "machineInfrastructure defines the metadata and infrastructure information for control plane machines.\n\nThis field is supported if and only if the control plane provider template referenced above is Machine based and supports setting replicas.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassMachineInfrastructureTemplate"), + }, + }, + "healthCheck": { + SchemaProps: spec.SchemaProps{ + Description: "healthCheck defines a MachineHealthCheck for this ControlPlaneClass. This field is supported if and only if the ControlPlane provider template referenced above is Machine based and supports setting replicas.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheck"), + }, + }, + "naming": { + SchemaProps: spec.SchemaProps{ + Description: "naming allows changing the naming pattern used when creating the control plane provider object.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassNamingSpec"), + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for Machine deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassMachineDeletionSpec"), + }, + }, + "readinessGates": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "conditionType", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "readinessGates specifies additional conditions to include when evaluating Machine Ready condition.\n\nThis field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine.\n\nNOTE: If a Cluster defines a custom list of readinessGates for the control plane, such list overrides readinessGates defined in this field. NOTE: Specific control plane provider implementations might automatically extend the list of readinessGates; e.g. the kubeadm control provider adds ReadinessGates for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate"), + }, + }, + }, + }, + }, + }, + Required: []string{"templateRef"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheck", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassMachineDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassMachineInfrastructureTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassNamingSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneClassHealthCheck(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneClassHealthCheck defines a MachineHealthCheck for control plane machines.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "checks": { + SchemaProps: spec.SchemaProps{ + Description: "checks are the checks that are used to evaluate if a Machine is healthy.\n\nIndependent of this configuration the MachineHealthCheck controller will always flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and Machines with deleted Nodes as unhealthy.\n\nFurthermore, if checks.nodeStartupTimeoutSeconds is not set it is defaulted to 10 minutes and evaluated accordingly.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckChecks"), + }, + }, + "remediation": { + SchemaProps: spec.SchemaProps{ + Description: "remediation configures if and how remediations are triggered if a Machine is unhealthy.\n\nIf remediation or remediation.triggerIf is not set, remediation will always be triggered for unhealthy Machines.\n\nIf remediation or remediation.templateRef is not set, the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via the owner of the Machines, for example a MachineSet or a KubeadmControlPlane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckRemediation"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckChecks", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckRemediation"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneClassHealthCheckChecks(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneClassHealthCheckChecks are the checks that are used to evaluate if a control plane Machine is healthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeStartupTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck to consider a Machine unhealthy if a corresponding Node isn't associated through a `Spec.ProviderID` field.\n\nThe duration set in this field is compared to the greatest of: - Cluster's infrastructure ready condition timestamp (if and when available) - Control Plane's initialized condition timestamp (if and when available) - Machine's infrastructure ready condition timestamp (if and when available) - Machine's metadata creation timestamp\n\nDefaults to 10 minutes. If you wish to disable this feature, set the value explicitly to 0.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "unhealthyNodeConditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "unhealthyNodeConditions contains a list of conditions that determine whether a node is considered unhealthy. The conditions are combined in a logical OR, i.e. if any of the conditions is met, the node is unhealthy.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneClassHealthCheckRemediation(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneClassHealthCheckRemediation configures if and how remediations are triggered if a control plane Machine is unhealthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "triggerIf": { + SchemaProps: spec.SchemaProps{ + Description: "triggerIf configures if remediations are triggered. If this field is not set, remediations are always triggered.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckRemediationTriggerIf"), + }, + }, + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a reference to a remediation template provided by an infrastructure provider.\n\nThis field is completely optional, when filled, the MachineHealthCheck controller creates a new object from the template referenced and hands off remediation of the machine to a controller that lives outside of Cluster API.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneClassHealthCheckRemediationTriggerIf", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneClassHealthCheckRemediationTriggerIf(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneClassHealthCheckRemediationTriggerIf configures if remediations are triggered.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "unhealthyLessThanOrEqualTo": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of unhealthy Machines is less than or equal to the configured value. unhealthyInRange takes precedence if set.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "unhealthyInRange": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyInRange specifies that remediations are only triggered if the number of unhealthy Machines is in the configured range. Takes precedence over unhealthyLessThanOrEqualTo. Eg. \"[3-5]\" - This means that remediation will be allowed only when: (a) there are at least 3 unhealthy Machines (and) (b) there are at most 5 unhealthy Machines", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneClassMachineDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneClassMachineDeletionSpec contains configuration options for Machine deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeDrainTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. The default value is 0, meaning that the node can be drained without any time limitations. NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` NOTE: This value can be overridden while defining a Cluster.Topology.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeVolumeDetachTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. NOTE: This value can be overridden while defining a Cluster.Topology.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeDeletionTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. Defaults to 10 seconds. NOTE: This value can be overridden while defining a Cluster.Topology.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneClassMachineInfrastructureTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneClassMachineInfrastructureTemplate defines the template for a MachineInfrastructure of a ControlPlane.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a required reference to the template for a MachineInfrastructure of a ControlPlane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"), + }, + }, + }, + Required: []string{"templateRef"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneClassNamingSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneClassNamingSpec defines the naming strategy for control plane objects.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template defines the template to use for generating the name of the ControlPlane object. If not defined, it will fallback to `{{ .cluster.name }}-{{ .random }}`. If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will get concatenated with a random suffix of length 5. The templating mechanism provides the following arguments: * `.cluster.name`: The name of the cluster object. * `.random`: A random alphanumeric string, without vowels, of length 5.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneTopology specifies the parameters for the control plane nodes in the cluster.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the metadata applied to the ControlPlane and the Machines of the ControlPlane if the ControlPlaneTemplate referenced by the ClusterClass is machine based. If not, it is applied only to the ControlPlane. At runtime this metadata is merged with the corresponding metadata from the ClusterClass.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"), + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the number of control plane nodes. If the value is not set, the ControlPlane object is created without the number of Replicas and it's assumed that the control plane controller does not implement support for this field. When specified against a control plane provider that lacks support for this field, this value will be ignored.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "healthCheck": { + SchemaProps: spec.SchemaProps{ + Description: "healthCheck allows to enable, disable and override control plane health check configuration from the ClusterClass for this control plane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheck"), + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for Machine deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyMachineDeletionSpec"), + }, + }, + "readinessGates": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "conditionType", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "readinessGates specifies additional conditions to include when evaluating Machine Ready condition.\n\nThis field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine.\n\nIf this field is not defined, readinessGates from the corresponding ControlPlaneClass will be used, if any.\n\nNOTE: Specific control plane provider implementations might automatically extend the list of readinessGates; e.g. the kubeadm control provider adds ReadinessGates for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate"), + }, + }, + }, + }, + }, + "variables": { + SchemaProps: spec.SchemaProps{ + Description: "variables can be used to customize the ControlPlane through patches.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneVariables"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheck", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyMachineDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneVariables", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyHealthCheck(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneTopologyHealthCheck defines a MachineHealthCheck for control plane machines.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "enabled": { + SchemaProps: spec.SchemaProps{ + Description: "enabled controls if a MachineHealthCheck should be created for the target machines.\n\nIf false: No MachineHealthCheck will be created.\n\nIf not set(default): A MachineHealthCheck will be created if it is defined here or\n in the associated ClusterClass. If no MachineHealthCheck is defined then none will be created.\n\nIf true: A MachineHealthCheck is guaranteed to be created. Cluster validation will block if `enable` is true and no MachineHealthCheck definition is available.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "checks": { + SchemaProps: spec.SchemaProps{ + Description: "checks are the checks that are used to evaluate if a Machine is healthy.\n\nIf one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, and as a consequence the checks and remediation fields from Cluster will be used instead of the corresponding fields in ClusterClass.\n\nIndependent of this configuration the MachineHealthCheck controller will always flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and Machines with deleted Nodes as unhealthy.\n\nFurthermore, if checks.nodeStartupTimeoutSeconds is not set it is defaulted to 10 minutes and evaluated accordingly.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckChecks"), + }, + }, + "remediation": { + SchemaProps: spec.SchemaProps{ + Description: "remediation configures if and how remediations are triggered if a Machine is unhealthy.\n\nIf one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, and as a consequence the checks and remediation fields from cluster will be used instead of the corresponding fields in ClusterClass.\n\nIf an health check override is defined and remediation or remediation.triggerIf is not set, remediation will always be triggered for unhealthy Machines.\n\nIf an health check override is defined and remediation or remediation.templateRef is not set, the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via the owner of the Machines, for example a MachineSet or a KubeadmControlPlane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckRemediation"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckChecks", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckRemediation"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyHealthCheckChecks(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneTopologyHealthCheckChecks are the checks that are used to evaluate if a control plane Machine is healthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeStartupTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck to consider a Machine unhealthy if a corresponding Node isn't associated through a `Spec.ProviderID` field.\n\nThe duration set in this field is compared to the greatest of: - Cluster's infrastructure ready condition timestamp (if and when available) - Control Plane's initialized condition timestamp (if and when available) - Machine's infrastructure ready condition timestamp (if and when available) - Machine's metadata creation timestamp\n\nDefaults to 10 minutes. If you wish to disable this feature, set the value explicitly to 0.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "unhealthyNodeConditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "unhealthyNodeConditions contains a list of conditions that determine whether a node is considered unhealthy. The conditions are combined in a logical OR, i.e. if any of the conditions is met, the node is unhealthy.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyHealthCheckRemediation(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneTopologyHealthCheckRemediation configures if and how remediations are triggered if a control plane Machine is unhealthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "triggerIf": { + SchemaProps: spec.SchemaProps{ + Description: "triggerIf configures if remediations are triggered. If this field is not set, remediations are always triggered.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckRemediationTriggerIf"), + }, + }, + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a reference to a remediation template provided by an infrastructure provider.\n\nThis field is completely optional, when filled, the MachineHealthCheck controller creates a new object from the template referenced and hands off remediation of the machine to a controller that lives outside of Cluster API.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopologyHealthCheckRemediationTriggerIf", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyHealthCheckRemediationTriggerIf(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneTopologyHealthCheckRemediationTriggerIf configures if remediations are triggered.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "unhealthyLessThanOrEqualTo": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of unhealthy Machines is less than or equal to the configured value. unhealthyInRange takes precedence if set.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "unhealthyInRange": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyInRange specifies that remediations are only triggered if the number of unhealthy Machines is in the configured range. Takes precedence over unhealthyLessThanOrEqualTo. Eg. \"[3-5]\" - This means that remediation will be allowed only when: (a) there are at least 3 unhealthy Machines (and) (b) there are at most 5 unhealthy Machines", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneTopologyMachineDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneTopologyMachineDeletionSpec contains configuration options for Machine deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeDrainTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. The default value is 0, meaning that the node can be drained without any time limitations. NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout`", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeVolumeDetachTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeDeletionTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. Defaults to 10 seconds.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ControlPlaneVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ControlPlaneVariables can be used to provide variables for the ControlPlane.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "overrides": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "name", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "overrides can be used to override Cluster level variables.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable"}, + } +} + +func schema_cluster_api_api_core_v1beta2_ExternalPatchDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ExternalPatchDefinition defines an external patch. Note: At least one of GeneratePatchesExtension or ValidateTopologyExtension must be set.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "generatePatchesExtension": { + SchemaProps: spec.SchemaProps{ + Description: "generatePatchesExtension references an extension which is called to generate patches.", + Type: []string{"string"}, + Format: "", + }, + }, + "validateTopologyExtension": { + SchemaProps: spec.SchemaProps{ + Description: "validateTopologyExtension references an extension which is called to validate the topology.", + Type: []string{"string"}, + Format: "", + }, + }, + "discoverVariablesExtension": { + SchemaProps: spec.SchemaProps{ + Description: "discoverVariablesExtension references an extension which is called to discover variables.", + Type: []string{"string"}, + Format: "", + }, + }, + "settings": { + SchemaProps: spec.SchemaProps{ + Description: "settings defines key value pairs to be passed to the extensions. Values defined here take precedence over the values defined in the corresponding ExtensionConfig.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_FailureDomain(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "FailureDomain is the Schema for Cluster API failure domains. It allows controllers to understand how many failure domains a cluster can optionally span across.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name is the name of the failure domain.", + Type: []string{"string"}, + Format: "", + }, + }, + "controlPlane": { + SchemaProps: spec.SchemaProps{ + Description: "controlPlane determines if this failure domain is suitable for use by control plane machines.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "attributes": { + SchemaProps: spec.SchemaProps{ + Description: "attributes is a free form map of attributes an infrastructure provider might use or require.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + Required: []string{"name"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_InfrastructureClass(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "InfrastructureClass defines the class for the infrastructure cluster.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef contains the reference to a provider-specific infrastructure cluster template.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"), + }, + }, + "naming": { + SchemaProps: spec.SchemaProps{ + Description: "naming allows changing the naming pattern used when creating the infrastructure cluster object.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.InfrastructureClassNamingSpec"), + }, + }, + }, + Required: []string{"templateRef"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference", "sigs.k8s.io/cluster-api/api/core/v1beta2.InfrastructureClassNamingSpec"}, + } +} + +func schema_cluster_api_api_core_v1beta2_InfrastructureClassNamingSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "InfrastructureClassNamingSpec defines the naming strategy for infrastructure objects.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template defines the template to use for generating the name of the Infrastructure object. If not defined, it will fallback to `{{ .cluster.name }}-{{ .random }}`. If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will get concatenated with a random suffix of length 5. The templating mechanism provides the following arguments: * `.cluster.name`: The name of the cluster object. * `.random`: A random alphanumeric string, without vowels, of length 5.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_JSONPatch(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "JSONPatch defines a JSON patch.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "op": { + SchemaProps: spec.SchemaProps{ + Description: "op defines the operation of the patch. Note: Only `add`, `replace` and `remove` are supported.", + Type: []string{"string"}, + Format: "", + }, + }, + "path": { + SchemaProps: spec.SchemaProps{ + Description: "path defines the path of the patch. Note: Only the spec of a template can be patched, thus the path has to start with /spec/. Note: For now the only allowed array modifications are `append` and `prepend`, i.e.: * for op: `add`: only index 0 (prepend) and - (append) are allowed * for op: `replace` or `remove`: no indexes are allowed", + Type: []string{"string"}, + Format: "", + }, + }, + "value": { + SchemaProps: spec.SchemaProps{ + Description: "value defines the value of the patch. Note: Either Value or ValueFrom is required for add and replace operations. Only one of them is allowed to be set at the same time. Note: We have to use apiextensionsv1.JSON instead of our JSON type, because controller-tools has a hard-coded schema for apiextensionsv1.JSON which cannot be produced by another type (unset type field). Ref: https://github.com/kubernetes-sigs/controller-tools/blob/d0e03a142d0ecdd5491593e941ee1d6b5d91dba6/pkg/crd/known_types.go#L106-L111", + Ref: ref("k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON"), + }, + }, + "valueFrom": { + SchemaProps: spec.SchemaProps{ + Description: "valueFrom defines the value of the patch. Note: Either Value or ValueFrom is required for add and replace operations. Only one of them is allowed to be set at the same time.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONPatchValue"), + }, + }, + }, + Required: []string{"op", "path"}, + }, + }, + Dependencies: []string{ + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON", "sigs.k8s.io/cluster-api/api/core/v1beta2.JSONPatchValue"}, + } +} + +func schema_cluster_api_api_core_v1beta2_JSONPatchValue(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "JSONPatchValue defines the value of a patch. Note: Only one of the fields is allowed to be set at the same time.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "variable": { + SchemaProps: spec.SchemaProps{ + Description: "variable is the variable to be used as value. Variable can be one of the variables defined in .spec.variables or a builtin variable.", + Type: []string{"string"}, + Format: "", + }, + }, + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template is the Go template to be used to calculate the value. A template can reference variables defined in .spec.variables and builtin variables. Note: The template must evaluate to a valid YAML or JSON value.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_JSONSchemaProps(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/). This struct has been initially copied from apiextensionsv1.JSONSchemaProps, but all fields which are not supported in CAPI have been removed.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "description": { + SchemaProps: spec.SchemaProps{ + Description: "description is a human-readable description of this variable.", + Type: []string{"string"}, + Format: "", + }, + }, + "example": { + SchemaProps: spec.SchemaProps{ + Description: "example is an example for this variable.", + Ref: ref("k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON"), + }, + }, + "type": { + SchemaProps: spec.SchemaProps{ + Description: "type is the type of the variable. Valid values are: object, array, string, integer, number or boolean.", + Type: []string{"string"}, + Format: "", + }, + }, + "properties": { + SchemaProps: spec.SchemaProps{ + Description: "properties specifies fields of an object. NOTE: Can only be set if type is object. NOTE: Properties is mutually exclusive with AdditionalProperties. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"), + }, + }, + }, + }, + }, + "additionalProperties": { + SchemaProps: spec.SchemaProps{ + Description: "additionalProperties specifies the schema of values in a map (keys are always strings). NOTE: Can only be set if type is object. NOTE: AdditionalProperties is mutually exclusive with Properties. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"), + }, + }, + "maxProperties": { + SchemaProps: spec.SchemaProps{ + Description: "maxProperties is the maximum amount of entries in a map or properties in an object. NOTE: Can only be set if type is object.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "minProperties": { + SchemaProps: spec.SchemaProps{ + Description: "minProperties is the minimum amount of entries in a map or properties in an object. NOTE: Can only be set if type is object.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "required": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "required specifies which fields of an object are required. NOTE: Can only be set if type is object.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items specifies fields of an array. NOTE: Can only be set if type is array. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"), + }, + }, + "maxItems": { + SchemaProps: spec.SchemaProps{ + Description: "maxItems is the max length of an array variable. NOTE: Can only be set if type is array.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "minItems": { + SchemaProps: spec.SchemaProps{ + Description: "minItems is the min length of an array variable. NOTE: Can only be set if type is array.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "uniqueItems": { + SchemaProps: spec.SchemaProps{ + Description: "uniqueItems specifies if items in an array must be unique. NOTE: Can only be set if type is array.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "format": { + SchemaProps: spec.SchemaProps{ + Description: "format is an OpenAPI v3 format string. Unknown formats are ignored. For a list of supported formats please see: (of the k8s.io/apiextensions-apiserver version we're currently using) https://github.com/kubernetes/apiextensions-apiserver/blob/master/pkg/apiserver/validation/formats.go NOTE: Can only be set if type is string.", + Type: []string{"string"}, + Format: "", + }, + }, + "maxLength": { + SchemaProps: spec.SchemaProps{ + Description: "maxLength is the max length of a string variable. NOTE: Can only be set if type is string.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "minLength": { + SchemaProps: spec.SchemaProps{ + Description: "minLength is the min length of a string variable. NOTE: Can only be set if type is string.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "pattern": { + SchemaProps: spec.SchemaProps{ + Description: "pattern is the regex which a string variable must match. NOTE: Can only be set if type is string.", + Type: []string{"string"}, + Format: "", + }, + }, + "maximum": { + SchemaProps: spec.SchemaProps{ + Description: "maximum is the maximum of an integer or number variable. If ExclusiveMaximum is false, the variable is valid if it is lower than, or equal to, the value of Maximum. If ExclusiveMaximum is true, the variable is valid if it is strictly lower than the value of Maximum. NOTE: Can only be set if type is integer or number.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "exclusiveMaximum": { + SchemaProps: spec.SchemaProps{ + Description: "exclusiveMaximum specifies if the Maximum is exclusive. NOTE: Can only be set if type is integer or number.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "minimum": { + SchemaProps: spec.SchemaProps{ + Description: "minimum is the minimum of an integer or number variable. If ExclusiveMinimum is false, the variable is valid if it is greater than, or equal to, the value of Minimum. If ExclusiveMinimum is true, the variable is valid if it is strictly greater than the value of Minimum. NOTE: Can only be set if type is integer or number.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "exclusiveMinimum": { + SchemaProps: spec.SchemaProps{ + Description: "exclusiveMinimum specifies if the Minimum is exclusive. NOTE: Can only be set if type is integer or number.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "x-kubernetes-preserve-unknown-fields": { + SchemaProps: spec.SchemaProps{ + Description: "x-kubernetes-preserve-unknown-fields allows setting fields in a variable object which are not defined in the variable schema. This affects fields recursively, except if nested properties or additionalProperties are specified in the schema.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "enum": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "enum is the list of valid values of the variable. NOTE: Can be set for all types.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Ref: ref("k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON"), + }, + }, + }, + }, + }, + "default": { + SchemaProps: spec.SchemaProps{ + Description: "default is the default value of the variable. NOTE: Can be set for all types.", + Ref: ref("k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON"), + }, + }, + "x-kubernetes-validations": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "rule", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "x-kubernetes-validations describes a list of validation rules written in the CEL expression language.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ValidationRule"), + }, + }, + }, + }, + }, + "x-metadata": { + SchemaProps: spec.SchemaProps{ + Description: "x-metadata is the metadata of a variable or a nested field within a variable. It can be used to add additional data for higher level tools.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchemaMetadata"), + }, + }, + "x-kubernetes-int-or-string": { + SchemaProps: spec.SchemaProps{ + Description: "x-kubernetes-int-or-string specifies that this value is either an integer or a string. If this is true, an empty type is allowed and type as child of anyOf is permitted if following one of the following patterns:\n\n1) anyOf:\n - type: integer\n - type: string\n2) allOf:\n - anyOf:\n - type: integer\n - type: string\n - ... zero or more", + Type: []string{"boolean"}, + Format: "", + }, + }, + "allOf": { + SchemaProps: spec.SchemaProps{ + Description: "allOf specifies that the variable must validate against all of the subschemas in the array. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"), + }, + }, + }, + }, + }, + "oneOf": { + SchemaProps: spec.SchemaProps{ + Description: "oneOf specifies that the variable must validate against exactly one of the subschemas in the array. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"), + }, + }, + }, + }, + }, + "anyOf": { + SchemaProps: spec.SchemaProps{ + Description: "anyOf specifies that the variable must validate against one or more of the subschemas in the array. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"), + }, + }, + }, + }, + }, + "not": { + SchemaProps: spec.SchemaProps{ + Description: "not specifies that the variable must not validate against the subschema. NOTE: This field uses PreserveUnknownFields and Schemaless, because recursive validation is not possible.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.JSON", "sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps", "sigs.k8s.io/cluster-api/api/core/v1beta2.ValidationRule", "sigs.k8s.io/cluster-api/api/core/v1beta2.VariableSchemaMetadata"}, + } +} + +func schema_cluster_api_api_core_v1beta2_Machine(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Machine is the Schema for the machines API.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the desired state of Machine.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status is the observed state of Machine.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineAddress(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineAddress contains information for the node's address.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "type": { + SchemaProps: spec.SchemaProps{ + Description: "type is the machine address type, one of Hostname, ExternalIP, InternalIP, ExternalDNS or InternalDNS.", + Type: []string{"string"}, + Format: "", + }, + }, + "address": { + SchemaProps: spec.SchemaProps{ + Description: "address is the machine address.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"type", "address"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeletionSpec contains configuration options for Machine deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeDrainTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. The default value is 0, meaning that the node can be drained without any time limitations. NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout`", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeVolumeDetachTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeDeletionTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. Defaults to 10 seconds.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeletionStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeletionStatus is the deletion state of the Machine.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeDrainStartTime": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDrainStartTime is the time when the drain of the node started and is used to determine if the nodeDrainTimeoutSeconds is exceeded. Only present when the Machine has a deletionTimestamp and draining the node had been started.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), + }, + }, + "waitForNodeVolumeDetachStartTime": { + SchemaProps: spec.SchemaProps{ + Description: "waitForNodeVolumeDetachStartTime is the time when waiting for volume detachment started and is used to determine if the nodeVolumeDetachTimeoutSeconds is exceeded. Detaching volumes from nodes is usually done by CSI implementations and the current state is observed from the node's `.Status.VolumesAttached` field. Only present when the Machine has a deletionTimestamp and waiting for volume detachments had been started.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeployment(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeployment is the Schema for the machinedeployments API.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the desired state of MachineDeployment.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status is the observed state of MachineDeployment.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClass(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClass serves as a template to define a set of worker nodes of the cluster provisioned using the `ClusterClass`.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the metadata applied to the MachineDeployment and the machines of the MachineDeployment. At runtime this metadata is merged with the corresponding metadata from the topology.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"), + }, + }, + "class": { + SchemaProps: spec.SchemaProps{ + Description: "class denotes a type of worker node present in the cluster, this name MUST be unique within a ClusterClass and can be referenced in the Cluster to create a managed MachineDeployment.", + Type: []string{"string"}, + Format: "", + }, + }, + "bootstrap": { + SchemaProps: spec.SchemaProps{ + Description: "bootstrap contains the bootstrap template reference to be used for the creation of worker Machines.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassBootstrapTemplate"), + }, + }, + "infrastructure": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructure contains the infrastructure template reference to be used for the creation of worker Machines.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassInfrastructureTemplate"), + }, + }, + "healthCheck": { + SchemaProps: spec.SchemaProps{ + Description: "healthCheck defines a MachineHealthCheck for this MachineDeploymentClass.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheck"), + }, + }, + "failureDomain": { + SchemaProps: spec.SchemaProps{ + Description: "failureDomain is the failure domain the machines will be created in. Must match the name of a FailureDomain from the Cluster status. NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass.", + Type: []string{"string"}, + Format: "", + }, + }, + "naming": { + SchemaProps: spec.SchemaProps{ + Description: "naming allows changing the naming pattern used when creating the MachineDeployment.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassNamingSpec"), + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for Machine deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassMachineDeletionSpec"), + }, + }, + "minReadySeconds": { + SchemaProps: spec.SchemaProps{ + Description: "minReadySeconds is the minimum number of seconds for which a newly created machine should be ready. Defaults to 0 (machine will be considered available as soon as it is ready) NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readinessGates": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "conditionType", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "readinessGates specifies additional conditions to include when evaluating Machine Ready condition.\n\nThis field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine.\n\nNOTE: If a Cluster defines a custom list of readinessGates for a MachineDeployment using this MachineDeploymentClass, such list overrides readinessGates defined in this field.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate"), + }, + }, + }, + }, + }, + "rollout": { + SchemaProps: spec.SchemaProps{ + Description: "rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. It allows you to define the strategy used during rolling replacements.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutSpec"), + }, + }, + }, + Required: []string{"class", "bootstrap", "infrastructure"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassBootstrapTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheck", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassInfrastructureTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassMachineDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassNamingSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassBootstrapTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassBootstrapTemplate defines the BootstrapTemplate for a MachineDeployment.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a required reference to the BootstrapTemplate for a MachineDeployment.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"), + }, + }, + }, + Required: []string{"templateRef"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassHealthCheck(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassHealthCheck defines a MachineHealthCheck for MachineDeployment machines.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "checks": { + SchemaProps: spec.SchemaProps{ + Description: "checks are the checks that are used to evaluate if a Machine is healthy.\n\nIndependent of this configuration the MachineHealthCheck controller will always flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and Machines with deleted Nodes as unhealthy.\n\nFurthermore, if checks.nodeStartupTimeoutSeconds is not set it is defaulted to 10 minutes and evaluated accordingly.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckChecks"), + }, + }, + "remediation": { + SchemaProps: spec.SchemaProps{ + Description: "remediation configures if and how remediations are triggered if a Machine is unhealthy.\n\nIf remediation or remediation.triggerIf is not set, remediation will always be triggered for unhealthy Machines.\n\nIf remediation or remediation.templateRef is not set, the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via the owner of the Machines, for example a MachineSet or a KubeadmControlPlane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckRemediation"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckChecks", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckRemediation"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassHealthCheckChecks(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassHealthCheckChecks are the checks that are used to evaluate if a MachineDeployment Machine is healthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeStartupTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck to consider a Machine unhealthy if a corresponding Node isn't associated through a `Spec.ProviderID` field.\n\nThe duration set in this field is compared to the greatest of: - Cluster's infrastructure ready condition timestamp (if and when available) - Control Plane's initialized condition timestamp (if and when available) - Machine's infrastructure ready condition timestamp (if and when available) - Machine's metadata creation timestamp\n\nDefaults to 10 minutes. If you wish to disable this feature, set the value explicitly to 0.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "unhealthyNodeConditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "unhealthyNodeConditions contains a list of conditions that determine whether a node is considered unhealthy. The conditions are combined in a logical OR, i.e. if any of the conditions is met, the node is unhealthy.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassHealthCheckRemediation(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassHealthCheckRemediation configures if and how remediations are triggered if a MachineDeployment Machine is unhealthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "maxInFlight": { + SchemaProps: spec.SchemaProps{ + Description: "maxInFlight determines how many in flight remediations should happen at the same time.\n\nRemediation only happens on the MachineSet with the most current revision, while older MachineSets (usually present during rollout operations) aren't allowed to remediate.\n\nNote: In general (independent of remediations), unhealthy machines are always prioritized during scale down operations over healthy ones.\n\nMaxInFlight can be set to a fixed number or a percentage. Example: when this is set to 20%, the MachineSet controller deletes at most 20% of the desired replicas.\n\nIf not set, remediation is limited to all machines (bounded by replicas) under the active MachineSet's management.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "triggerIf": { + SchemaProps: spec.SchemaProps{ + Description: "triggerIf configures if remediations are triggered. If this field is not set, remediations are always triggered.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckRemediationTriggerIf"), + }, + }, + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a reference to a remediation template provided by an infrastructure provider.\n\nThis field is completely optional, when filled, the MachineHealthCheck controller creates a new object from the template referenced and hands off remediation of the machine to a controller that lives outside of Cluster API.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassHealthCheckRemediationTriggerIf", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassHealthCheckRemediationTriggerIf(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassHealthCheckRemediationTriggerIf configures if remediations are triggered.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "unhealthyLessThanOrEqualTo": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of unhealthy Machines is less than or equal to the configured value. unhealthyInRange takes precedence if set.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "unhealthyInRange": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyInRange specifies that remediations are only triggered if the number of unhealthy Machines is in the configured range. Takes precedence over unhealthyLessThanOrEqualTo. Eg. \"[3-5]\" - This means that remediation will be allowed only when: (a) there are at least 3 unhealthy Machines (and) (b) there are at most 5 unhealthy Machines", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassInfrastructureTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassInfrastructureTemplate defines the InfrastructureTemplate for a MachineDeployment.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a required reference to the InfrastructureTemplate for a MachineDeployment.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"), + }, + }, + }, + Required: []string{"templateRef"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassMachineDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassMachineDeletionSpec contains configuration options for Machine deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "order": { + SchemaProps: spec.SchemaProps{ + Description: "order defines the order in which Machines are deleted when downscaling. Defaults to \"Random\". Valid values are \"Random, \"Newest\", \"Oldest\"", + Type: []string{"string"}, + Format: "", + }, + }, + "nodeDrainTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. The default value is 0, meaning that the node can be drained without any time limitations. NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeVolumeDetachTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeDeletionTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. Defaults to 10 seconds. NOTE: This value can be overridden while defining a Cluster.Topology using this MachineDeploymentClass.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassNamingSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassNamingSpec defines the naming strategy for machine deployment objects.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template defines the template to use for generating the name of the MachineDeployment object. If not defined, it will fallback to `{{ .cluster.name }}-{{ .machineDeployment.topologyName }}-{{ .random }}`. If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will get concatenated with a random suffix of length 5. The templating mechanism provides the following arguments: * `.cluster.name`: The name of the cluster object. * `.random`: A random alphanumeric string, without vowels, of length 5. * `.machineDeployment.topologyName`: The name of the MachineDeployment topology (Cluster.spec.topology.workers.machineDeployments[].name).", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassRolloutSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassRolloutSpec defines the rollout behavior.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "strategy": { + SchemaProps: spec.SchemaProps{ + Description: "strategy specifies how to roll out control plane Machines.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutStrategy"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutStrategy"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassRolloutStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassRolloutStrategy describes how to replace existing machines with new ones.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "type": { + SchemaProps: spec.SchemaProps{ + Description: "type of rollout. Allowed values are RollingUpdate and OnDelete. Default is RollingUpdate.", + Type: []string{"string"}, + Format: "", + }, + }, + "rollingUpdate": { + SchemaProps: spec.SchemaProps{ + Description: "rollingUpdate is the rolling update config params. Present only if type = RollingUpdate.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutStrategyRollingUpdate"), + }, + }, + }, + Required: []string{"type"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClassRolloutStrategyRollingUpdate"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentClassRolloutStrategyRollingUpdate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentClassRolloutStrategyRollingUpdate is used to control the desired behavior of rolling update.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "maxUnavailable": { + SchemaProps: spec.SchemaProps{ + Description: "maxUnavailable is the maximum number of machines that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired machines (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 0. Example: when this is set to 30%, the old MachineSet can be scaled down to 70% of desired machines immediately when the rolling update starts. Once new machines are ready, old MachineSet can be scaled down further, followed by scaling up the new MachineSet, ensuring that the total number of machines available at all times during the update is at least 70% of desired machines.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "maxSurge": { + SchemaProps: spec.SchemaProps{ + Description: "maxSurge is the maximum number of machines that can be scheduled above the desired number of machines. Value can be an absolute number (ex: 5) or a percentage of desired machines (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 1. Example: when this is set to 30%, the new MachineSet can be scaled up immediately when the rolling update starts, such that the total number of old and new machines do not exceed 130% of desired machines. Once old machines have been killed, new MachineSet can be scaled up further, ensuring that total number of machines running at any time during the update is at most 130% of desired machines.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentDeletionSpec contains configuration options for MachineDeployment deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "order": { + SchemaProps: spec.SchemaProps{ + Description: "order defines the order in which Machines are deleted when downscaling. Defaults to \"Random\". Valid values are \"Random, \"Newest\", \"Oldest\"", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentDeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "v1beta1": { + SchemaProps: spec.SchemaProps{ + Description: "v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentV1Beta1DeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentV1Beta1DeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentList contains a list of MachineDeployment.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items is the list of MachineDeployments.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeployment"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeployment"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentRemediationSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentRemediationSpec controls how unhealthy Machines are remediated.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "maxInFlight": { + SchemaProps: spec.SchemaProps{ + Description: "maxInFlight determines how many in flight remediations should happen at the same time.\n\nRemediation only happens on the MachineSet with the most current revision, while older MachineSets (usually present during rollout operations) aren't allowed to remediate.\n\nNote: In general (independent of remediations), unhealthy machines are always prioritized during scale down operations over healthy ones.\n\nMaxInFlight can be set to a fixed number or a percentage. Example: when this is set to 20%, the MachineSet controller deletes at most 20% of the desired replicas.\n\nIf not set, remediation is limited to all machines (bounded by replicas) under the active MachineSet's management.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentRolloutSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentRolloutSpec defines the rollout behavior.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "after": { + SchemaProps: spec.SchemaProps{ + Description: "after is a field to indicate a rollout should be performed after the specified time even if no changes have been made to the MachineDeployment. Example: In the YAML the time can be specified in the RFC3339 format. To specify the rolloutAfter target as March 9, 2023, at 9 am UTC use \"2023-03-09T09:00:00Z\".", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), + }, + }, + "strategy": { + SchemaProps: spec.SchemaProps{ + Description: "strategy specifies how to roll out control plane Machines.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutStrategy"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Time", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutStrategy"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentRolloutStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentRolloutStrategy describes how to replace existing machines with new ones.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "type": { + SchemaProps: spec.SchemaProps{ + Description: "type of rollout. Allowed values are RollingUpdate and OnDelete. Default is RollingUpdate.", + Type: []string{"string"}, + Format: "", + }, + }, + "rollingUpdate": { + SchemaProps: spec.SchemaProps{ + Description: "rollingUpdate is the rolling update config params. Present only if type = RollingUpdate.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutStrategyRollingUpdate"), + }, + }, + }, + Required: []string{"type"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutStrategyRollingUpdate"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentRolloutStrategyRollingUpdate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentRolloutStrategyRollingUpdate is used to control the desired behavior of rolling update.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "maxUnavailable": { + SchemaProps: spec.SchemaProps{ + Description: "maxUnavailable is the maximum number of machines that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired machines (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 0. Example: when this is set to 30%, the old MachineSet can be scaled down to 70% of desired machines immediately when the rolling update starts. Once new machines are ready, old MachineSet can be scaled down further, followed by scaling up the new MachineSet, ensuring that the total number of machines available at all times during the update is at least 70% of desired machines.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "maxSurge": { + SchemaProps: spec.SchemaProps{ + Description: "maxSurge is the maximum number of machines that can be scheduled above the desired number of machines. Value can be an absolute number (ex: 5) or a percentage of desired machines (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 1. Example: when this is set to 30%, the new MachineSet can be scaled up immediately when the rolling update starts, such that the total number of old and new machines do not exceed 130% of desired machines. Once old machines have been killed, new MachineSet can be scaled up further, ensuring that total number of machines running at any time during the update is at most 130% of desired machines.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentSpec defines the desired state of MachineDeployment.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "clusterName": { + SchemaProps: spec.SchemaProps{ + Description: "clusterName is the name of the Cluster this object belongs to.", + Type: []string{"string"}, + Format: "", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the number of desired machines. This is a pointer to distinguish between explicit zero and not specified.\n\nDefaults to: * if the Kubernetes autoscaler min size and max size annotations are set:\n - if it's a new MachineDeployment, use min size\n - if the replicas field of the old MachineDeployment is < min size, use min size\n - if the replicas field of the old MachineDeployment is > max size, use max size\n - if the replicas field of the old MachineDeployment is in the (min size, max size) range, keep the value from the oldMD\n* otherwise use 1 Note: Defaulting will be run whenever the replicas field is not set: * A new MachineDeployment is created with replicas not set. * On an existing MachineDeployment the replicas field was first set and is now unset. Those cases are especially relevant for the following Kubernetes autoscaler use cases: * A new MachineDeployment is created and replicas should be managed by the autoscaler * An existing MachineDeployment which initially wasn't controlled by the autoscaler\n should be later controlled by the autoscaler", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "rollout": { + SchemaProps: spec.SchemaProps{ + Description: "rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. It allows you to require that all Machines are replaced after a certain time, and allows you to define the strategy used during rolling replacements.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutSpec"), + }, + }, + "selector": { + SchemaProps: spec.SchemaProps{ + Description: "selector is the label selector for machines. Existing MachineSets whose machines are selected by this will be the ones affected by this deployment. It must match the machine template's labels.", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), + }, + }, + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template describes the machines that will be created.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineTemplateSpec"), + }, + }, + "machineNaming": { + SchemaProps: spec.SchemaProps{ + Description: "machineNaming allows changing the naming pattern used when creating Machines. Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNamingSpec"), + }, + }, + "remediation": { + SchemaProps: spec.SchemaProps{ + Description: "remediation controls how unhealthy Machines are remediated.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRemediationSpec"), + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for MachineDeployment deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentDeletionSpec"), + }, + }, + "paused": { + SchemaProps: spec.SchemaProps{ + Description: "paused indicates that the deployment is paused.", + Type: []string{"boolean"}, + Format: "", + }, + }, + }, + Required: []string{"clusterName", "selector", "template"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRemediationSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentRolloutSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNamingSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineTemplateSpec"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentStatus defines the observed state of MachineDeployment.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observations of a MachineDeployment's current state. Known condition types are Available, MachinesReady, MachinesUpToDate, ScalingUp, ScalingDown, Remediating, Deleting, Paused.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "observedGeneration is the generation observed by the deployment controller.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "selector": { + SchemaProps: spec.SchemaProps{ + Description: "selector is the same as the label selector but in the string format to avoid introspection by clients. The string will be in the same format as the query-param syntax. More info about label selectors: http://kubernetes.io/docs/user-guide/labels#label-selectors", + Type: []string{"string"}, + Format: "", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the total number of non-terminated machines targeted by this deployment (their labels match the selector).", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the number of ready replicas for this MachineDeployment. A machine is considered ready when Machine's Ready condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the number of available replicas for this MachineDeployment. A machine is considered available when Machine's Available condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "upToDateReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "upToDateReplicas is the number of up-to-date replicas targeted by this deployment. A machine is considered up-to-date when Machine's UpToDate condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "phase": { + SchemaProps: spec.SchemaProps{ + Description: "phase represents the current phase of a MachineDeployment (ScalingUp, ScalingDown, Running, Failed, or Unknown).", + Type: []string{"string"}, + Format: "", + }, + }, + "deprecated": { + SchemaProps: spec.SchemaProps{ + Description: "deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentDeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentDeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopology specifies the different parameters for a set of worker nodes in the topology. This set of nodes is managed by a MachineDeployment object whose lifecycle is managed by the Cluster controller.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the metadata applied to the MachineDeployment and the machines of the MachineDeployment. At runtime this metadata is merged with the corresponding metadata from the ClusterClass.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"), + }, + }, + "class": { + SchemaProps: spec.SchemaProps{ + Description: "class is the name of the MachineDeploymentClass used to create the set of worker nodes. This should match one of the deployment classes defined in the ClusterClass object mentioned in the `Cluster.Spec.Class` field.", + Type: []string{"string"}, + Format: "", + }, + }, + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name is the unique identifier for this MachineDeploymentTopology. The value is used with other unique identifiers to create a MachineDeployment's Name (e.g. cluster's name, etc). In case the name is greater than the allowed maximum length, the values are hashed together.", + Type: []string{"string"}, + Format: "", + }, + }, + "failureDomain": { + SchemaProps: spec.SchemaProps{ + Description: "failureDomain is the failure domain the machines will be created in. Must match a key in the FailureDomains map stored on the cluster object.", + Type: []string{"string"}, + Format: "", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the number of worker nodes belonging to this set. If the value is nil, the MachineDeployment is created without the number of Replicas (defaulting to 1) and it's assumed that an external entity (like cluster autoscaler) is responsible for the management of this value.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "healthCheck": { + SchemaProps: spec.SchemaProps{ + Description: "healthCheck allows to enable, disable and override MachineDeployment health check configuration from the ClusterClass for this MachineDeployment.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheck"), + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for Machine deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyMachineDeletionSpec"), + }, + }, + "minReadySeconds": { + SchemaProps: spec.SchemaProps{ + Description: "minReadySeconds is the minimum number of seconds for which a newly created machine should be ready. Defaults to 0 (machine will be considered available as soon as it is ready)", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readinessGates": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "conditionType", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "readinessGates specifies additional conditions to include when evaluating Machine Ready condition.\n\nThis field can be used e.g. to instruct the machine controller to include in the computation for Machine's ready computation a condition, managed by an external controllers, reporting the status of special software/hardware installed on the Machine.\n\nIf this field is not defined, readinessGates from the corresponding MachineDeploymentClass will be used, if any.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate"), + }, + }, + }, + }, + }, + "rollout": { + SchemaProps: spec.SchemaProps{ + Description: "rollout allows you to configure the behaviour of rolling updates to the MachineDeployment Machines. It allows you to define the strategy used during rolling replacements.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutSpec"), + }, + }, + "variables": { + SchemaProps: spec.SchemaProps{ + Description: "variables can be used to customize the MachineDeployment through patches.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentVariables"), + }, + }, + }, + Required: []string{"class", "name"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheck", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyMachineDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentVariables", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate", "sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyHealthCheck(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopologyHealthCheck defines a MachineHealthCheck for MachineDeployment machines.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "enabled": { + SchemaProps: spec.SchemaProps{ + Description: "enabled controls if a MachineHealthCheck should be created for the target machines.\n\nIf false: No MachineHealthCheck will be created.\n\nIf not set(default): A MachineHealthCheck will be created if it is defined here or\n in the associated ClusterClass. If no MachineHealthCheck is defined then none will be created.\n\nIf true: A MachineHealthCheck is guaranteed to be created. Cluster validation will block if `enable` is true and no MachineHealthCheck definition is available.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "checks": { + SchemaProps: spec.SchemaProps{ + Description: "checks are the checks that are used to evaluate if a Machine is healthy.\n\nIf one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, and as a consequence the checks and remediation fields from Cluster will be used instead of the corresponding fields in ClusterClass.\n\nIndependent of this configuration the MachineHealthCheck controller will always flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and Machines with deleted Nodes as unhealthy.\n\nFurthermore, if checks.nodeStartupTimeoutSeconds is not set it is defaulted to 10 minutes and evaluated accordingly.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckChecks"), + }, + }, + "remediation": { + SchemaProps: spec.SchemaProps{ + Description: "remediation configures if and how remediations are triggered if a Machine is unhealthy.\n\nIf one of checks and remediation fields are set, the system assumes that an healthCheck override is defined, and as a consequence the checks and remediation fields from cluster will be used instead of the corresponding fields in ClusterClass.\n\nIf an health check override is defined and remediation or remediation.triggerIf is not set, remediation will always be triggered for unhealthy Machines.\n\nIf an health check override is defined and remediation or remediation.templateRef is not set, the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via the owner of the Machines, for example a MachineSet or a KubeadmControlPlane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckRemediation"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckChecks", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckRemediation"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyHealthCheckChecks(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopologyHealthCheckChecks are the checks that are used to evaluate if a MachineDeployment Machine is healthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeStartupTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck to consider a Machine unhealthy if a corresponding Node isn't associated through a `Spec.ProviderID` field.\n\nThe duration set in this field is compared to the greatest of: - Cluster's infrastructure ready condition timestamp (if and when available) - Control Plane's initialized condition timestamp (if and when available) - Machine's infrastructure ready condition timestamp (if and when available) - Machine's metadata creation timestamp\n\nDefaults to 10 minutes. If you wish to disable this feature, set the value explicitly to 0.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "unhealthyNodeConditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "unhealthyNodeConditions contains a list of conditions that determine whether a node is considered unhealthy. The conditions are combined in a logical OR, i.e. if any of the conditions is met, the node is unhealthy.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyHealthCheckRemediation(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopologyHealthCheckRemediation configures if and how remediations are triggered if a MachineDeployment Machine is unhealthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "maxInFlight": { + SchemaProps: spec.SchemaProps{ + Description: "maxInFlight determines how many in flight remediations should happen at the same time.\n\nRemediation only happens on the MachineSet with the most current revision, while older MachineSets (usually present during rollout operations) aren't allowed to remediate.\n\nNote: In general (independent of remediations), unhealthy machines are always prioritized during scale down operations over healthy ones.\n\nMaxInFlight can be set to a fixed number or a percentage. Example: when this is set to 20%, the MachineSet controller deletes at most 20% of the desired replicas.\n\nIf not set, remediation is limited to all machines (bounded by replicas) under the active MachineSet's management.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "triggerIf": { + SchemaProps: spec.SchemaProps{ + Description: "triggerIf configures if remediations are triggered. If this field is not set, remediations are always triggered.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckRemediationTriggerIf"), + }, + }, + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a reference to a remediation template provided by an infrastructure provider.\n\nThis field is completely optional, when filled, the MachineHealthCheck controller creates a new object from the template referenced and hands off remediation of the machine to a controller that lives outside of Cluster API.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyHealthCheckRemediationTriggerIf", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyHealthCheckRemediationTriggerIf(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopologyHealthCheckRemediationTriggerIf configures if remediations are triggered.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "unhealthyLessThanOrEqualTo": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of unhealthy Machines is less than or equal to the configured value. unhealthyInRange takes precedence if set.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "unhealthyInRange": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyInRange specifies that remediations are only triggered if the number of unhealthy Machines is in the configured range. Takes precedence over unhealthyLessThanOrEqualTo. Eg. \"[3-5]\" - This means that remediation will be allowed only when: (a) there are at least 3 unhealthy Machines (and) (b) there are at most 5 unhealthy Machines", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyMachineDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopologyMachineDeletionSpec contains configuration options for Machine deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "order": { + SchemaProps: spec.SchemaProps{ + Description: "order defines the order in which Machines are deleted when downscaling. Defaults to \"Random\". Valid values are \"Random, \"Newest\", \"Oldest\"", + Type: []string{"string"}, + Format: "", + }, + }, + "nodeDrainTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. The default value is 0, meaning that the node can be drained without any time limitations. NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout`", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeVolumeDetachTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeDeletionTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine hosts after the Machine is marked for deletion. A duration of 0 will retry deletion indefinitely. Defaults to 10 seconds.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyRolloutSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopologyRolloutSpec defines the rollout behavior.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "strategy": { + SchemaProps: spec.SchemaProps{ + Description: "strategy specifies how to roll out control plane Machines.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutStrategy"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutStrategy"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyRolloutStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopologyRolloutStrategy describes how to replace existing machines with new ones.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "type": { + SchemaProps: spec.SchemaProps{ + Description: "type of rollout. Allowed values are RollingUpdate and OnDelete. Default is RollingUpdate.", + Type: []string{"string"}, + Format: "", + }, + }, + "rollingUpdate": { + SchemaProps: spec.SchemaProps{ + Description: "rollingUpdate is the rolling update config params. Present only if type = RollingUpdate.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutStrategyRollingUpdate"), + }, + }, + }, + Required: []string{"type"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopologyRolloutStrategyRollingUpdate"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentTopologyRolloutStrategyRollingUpdate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentTopologyRolloutStrategyRollingUpdate is used to control the desired behavior of rolling update.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "maxUnavailable": { + SchemaProps: spec.SchemaProps{ + Description: "maxUnavailable is the maximum number of machines that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired machines (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 0. Example: when this is set to 30%, the old MachineSet can be scaled down to 70% of desired machines immediately when the rolling update starts. Once new machines are ready, old MachineSet can be scaled down further, followed by scaling up the new MachineSet, ensuring that the total number of machines available at all times during the update is at least 70% of desired machines.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "maxSurge": { + SchemaProps: spec.SchemaProps{ + Description: "maxSurge is the maximum number of machines that can be scheduled above the desired number of machines. Value can be an absolute number (ex: 5) or a percentage of desired machines (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 1. Example: when this is set to 30%, the new MachineSet can be scaled up immediately when the rolling update starts, such that the total number of old and new machines do not exceed 130% of desired machines. Once old machines have been killed, new MachineSet can be scaled up further, ensuring that total number of machines running at any time during the update is at most 130% of desired machines.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentV1Beta1DeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + SchemaProps: spec.SchemaProps{ + Description: "conditions defines current service state of the MachineDeployment.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"), + }, + }, + }, + }, + }, + "updatedReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "updatedReplicas is the total number of non-terminated machines targeted by this deployment that have the desired template spec.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the total number of ready machines targeted by this deployment.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the total number of available machines (ready for at least minReadySeconds) targeted by this deployment.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + "unavailableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "unavailableReplicas is the total number of unavailable machines targeted by this deployment. This is the total number of machines that are still required for the deployment to have 100% available capacity. They may either be machines that are running but not yet available or machines that still have not been created.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeploymentVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeploymentVariables can be used to provide variables for a specific MachineDeployment.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "overrides": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "name", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "overrides can be used to override Cluster level variables.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "v1beta1": { + SchemaProps: spec.SchemaProps{ + Description: "v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineV1Beta1DeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineV1Beta1DeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDrainRule(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDrainRule is the Schema for the MachineDrainRule API.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec defines the spec of a MachineDrainRule.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleSpec"), + }, + }, + }, + Required: []string{"metadata", "spec"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleSpec"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDrainRuleDrainConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDrainRuleDrainConfig configures if and how Pods are drained.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "behavior": { + SchemaProps: spec.SchemaProps{ + Description: "behavior defines the drain behavior. Can be either \"Drain\", \"Skip\", or \"WaitCompleted\". \"Drain\" means that the Pods to which this MachineDrainRule applies will be drained. If behavior is set to \"Drain\" the order in which Pods are drained can be configured with the order field. When draining Pods of a Node the Pods will be grouped by order and one group after another will be drained (by increasing order). Cluster API will wait until all Pods of a group are terminated / removed from the Node before starting with the next group. \"Skip\" means that the Pods to which this MachineDrainRule applies will be skipped during drain. \"WaitCompleted\" means that the pods to which this MachineDrainRule applies will never be evicted and we wait for them to be completed, it is enforced that pods marked with this behavior always have Order=0.", + Type: []string{"string"}, + Format: "", + }, + }, + "order": { + SchemaProps: spec.SchemaProps{ + Description: "order defines the order in which Pods are drained. Pods with higher order are drained after Pods with lower order. order can only be set if behavior is set to \"Drain\". If order is not set, 0 will be used. Valid values for order are from -2147483648 to 2147483647 (inclusive).", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + Required: []string{"behavior"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDrainRuleList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDrainRuleList contains a list of MachineDrainRules.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items contains the items of the MachineDrainRuleList.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRule"), + }, + }, + }, + }, + }, + }, + Required: []string{"metadata", "items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRule"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDrainRuleMachineSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDrainRuleMachineSelector defines to which Machines this MachineDrainRule should be applied.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "selector": { + SchemaProps: spec.SchemaProps{ + Description: "selector is a label selector which selects Machines by their labels. This field follows standard label selector semantics; if not present or empty, it selects all Machines.\n\nIf clusterSelector is also set, then the selector as a whole selects Machines matching selector belonging to Clusters selected by clusterSelector. If clusterSelector is not set, it selects all Machines matching selector in all Clusters.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), + }, + }, + "clusterSelector": { + SchemaProps: spec.SchemaProps{ + Description: "clusterSelector is a label selector which selects Machines by the labels of their Clusters. This field follows standard label selector semantics; if not present or empty, it selects Machines of all Clusters.\n\nIf selector is also set, then the selector as a whole selects Machines matching selector belonging to Clusters selected by clusterSelector. If selector is not set, it selects all Machines belonging to Clusters selected by clusterSelector.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDrainRulePodSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDrainRulePodSelector defines to which Pods this MachineDrainRule should be applied.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "selector": { + SchemaProps: spec.SchemaProps{ + Description: "selector is a label selector which selects Pods by their labels. This field follows standard label selector semantics; if not present or empty, it selects all Pods.\n\nIf namespaceSelector is also set, then the selector as a whole selects Pods matching selector in Namespaces selected by namespaceSelector. If namespaceSelector is not set, it selects all Pods matching selector in all Namespaces.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), + }, + }, + "namespaceSelector": { + SchemaProps: spec.SchemaProps{ + Description: "namespaceSelector is a label selector which selects Pods by the labels of their Namespaces. This field follows standard label selector semantics; if not present or empty, it selects Pods of all Namespaces.\n\nIf selector is also set, then the selector as a whole selects Pods matching selector in Namespaces selected by namespaceSelector. If selector is not set, it selects all Pods in Namespaces selected by namespaceSelector.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineDrainRuleSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineDrainRuleSpec defines the spec of a MachineDrainRule.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "drain": { + SchemaProps: spec.SchemaProps{ + Description: "drain configures if and how Pods are drained.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleDrainConfig"), + }, + }, + "machines": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "machines defines to which Machines this MachineDrainRule should be applied.\n\nIf machines is not set, the MachineDrainRule applies to all Machines in the Namespace. If machines contains multiple selectors, the results are ORed. Within a single Machine selector the results of selector and clusterSelector are ANDed. Machines will be selected from all Clusters in the Namespace unless otherwise restricted with the clusterSelector.\n\nExample: Selects control plane Machines in all Clusters or\n Machines with label \"os\" == \"linux\" in Clusters with label\n \"stage\" == \"production\".\n\n - selector:\n matchExpressions:\n - key: cluster.x-k8s.io/control-plane\n operator: Exists\n - selector:\n matchLabels:\n os: linux\n clusterSelector:\n matchExpressions:\n - key: stage\n operator: In\n values:\n - production", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleMachineSelector"), + }, + }, + }, + }, + }, + "pods": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "pods defines to which Pods this MachineDrainRule should be applied.\n\nIf pods is not set, the MachineDrainRule applies to all Pods in all Namespaces. If pods contains multiple selectors, the results are ORed. Within a single Pod selector the results of selector and namespaceSelector are ANDed. Pods will be selected from all Namespaces unless otherwise restricted with the namespaceSelector.\n\nExample: Selects Pods with label \"app\" == \"logging\" in all Namespaces or\n Pods with label \"app\" == \"prometheus\" in the \"monitoring\"\n Namespace.\n\n - selector:\n matchExpressions:\n - key: app\n operator: In\n values:\n - logging\n - selector:\n matchLabels:\n app: prometheus\n namespaceSelector:\n matchLabels:\n kubernetes.io/metadata.name: monitoring", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRulePodSelector"), + }, + }, + }, + }, + }, + }, + Required: []string{"drain"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleDrainConfig", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRuleMachineSelector", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDrainRulePodSelector"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheck(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheck is the Schema for the machinehealthchecks API.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the specification of machine health check policy", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status is the most recently observed status of MachineHealthCheck resource", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckChecks(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckChecks are the checks that are used to evaluate if a Machine is healthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeStartupTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeStartupTimeoutSeconds allows to set the maximum time for MachineHealthCheck to consider a Machine unhealthy if a corresponding Node isn't associated through a `Spec.ProviderID` field.\n\nThe duration set in this field is compared to the greatest of: - Cluster's infrastructure ready condition timestamp (if and when available) - Control Plane's initialized condition timestamp (if and when available) - Machine's infrastructure ready condition timestamp (if and when available) - Machine's metadata creation timestamp\n\nDefaults to 10 minutes. If you wish to disable this feature, set the value explicitly to 0.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "unhealthyNodeConditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "unhealthyNodeConditions contains a list of conditions that determine whether a node is considered unhealthy. The conditions are combined in a logical OR, i.e. if any of the conditions is met, the node is unhealthy.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.UnhealthyNodeCondition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckDeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "v1beta1": { + SchemaProps: spec.SchemaProps{ + Description: "v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckV1Beta1DeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckV1Beta1DeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckList contains a list of MachineHealthCheck.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items is the list of MachineHealthChecks.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheck"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheck"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckRemediation(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckRemediation configures if and how remediations are triggered if a Machine is unhealthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "triggerIf": { + SchemaProps: spec.SchemaProps{ + Description: "triggerIf configures if remediations are triggered. If this field is not set, remediations are always triggered.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTriggerIf"), + }, + }, + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a reference to a remediation template provided by an infrastructure provider.\n\nThis field is completely optional, when filled, the MachineHealthCheck controller creates a new object from the template referenced and hands off remediation of the machine to a controller that lives outside of Cluster API.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTemplateReference", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediationTriggerIf"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckRemediationTemplateReference(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckRemediationTemplateReference is a reference to a remediation template.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "kind of the remediation template. kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name of the remediation template. name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "apiVersion of the remediation template. apiVersion must be fully qualified domain name followed by / and a version. NOTE: This field must be kept in sync with the APIVersion of the remediation template.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"kind", "name", "apiVersion"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckRemediationTriggerIf(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckRemediationTriggerIf configures if remediations are triggered.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "unhealthyLessThanOrEqualTo": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyLessThanOrEqualTo specifies that remediations are only triggered if the number of unhealthy Machines is less than or equal to the configured value. unhealthyInRange takes precedence if set.", + Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), + }, + }, + "unhealthyInRange": { + SchemaProps: spec.SchemaProps{ + Description: "unhealthyInRange specifies that remediations are only triggered if the number of unhealthy Machines is in the configured range. Takes precedence over unhealthyLessThanOrEqualTo. Eg. \"[3-5]\" - This means that remediation will be allowed only when: (a) there are at least 3 unhealthy Machines (and) (b) there are at most 5 unhealthy Machines", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckSpec defines the desired state of MachineHealthCheck.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "clusterName": { + SchemaProps: spec.SchemaProps{ + Description: "clusterName is the name of the Cluster this object belongs to.", + Type: []string{"string"}, + Format: "", + }, + }, + "selector": { + SchemaProps: spec.SchemaProps{ + Description: "selector is a label selector to match machines whose health will be exercised", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), + }, + }, + "checks": { + SchemaProps: spec.SchemaProps{ + Description: "checks are the checks that are used to evaluate if a Machine is healthy.\n\nIndependent of this configuration the MachineHealthCheck controller will always flag Machines with `cluster.x-k8s.io/remediate-machine` annotation and Machines with deleted Nodes as unhealthy.\n\nFurthermore, if checks.nodeStartupTimeoutSeconds is not set it is defaulted to 10 minutes and evaluated accordingly.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckChecks"), + }, + }, + "remediation": { + SchemaProps: spec.SchemaProps{ + Description: "remediation configures if and how remediations are triggered if a Machine is unhealthy.\n\nIf remediation or remediation.triggerIf is not set, remediation will always be triggered for unhealthy Machines.\n\nIf remediation or remediation.templateRef is not set, the OwnerRemediated condition will be set on unhealthy Machines to trigger remediation via the owner of the Machines, for example a MachineSet or a KubeadmControlPlane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediation"), + }, + }, + }, + Required: []string{"clusterName", "selector"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckChecks", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckRemediation"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckStatus defines the observed state of MachineHealthCheck.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observations of a MachineHealthCheck's current state. Known condition types are RemediationAllowed, Paused.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "expectedMachines": { + SchemaProps: spec.SchemaProps{ + Description: "expectedMachines is the total number of machines counted by this machine health check", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "currentHealthy": { + SchemaProps: spec.SchemaProps{ + Description: "currentHealthy is the total number of healthy machines counted by this machine health check", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "remediationsAllowed": { + SchemaProps: spec.SchemaProps{ + Description: "remediationsAllowed is the number of further remediations allowed by this machine health check before maxUnhealthy short circuiting will be applied", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "observedGeneration is the latest generation observed by the controller.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "targets": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "targets shows the current list of machines the machine health check is watching", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "deprecated": { + SchemaProps: spec.SchemaProps{ + Description: "deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckDeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineHealthCheckDeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineHealthCheckV1Beta1DeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineHealthCheckV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + SchemaProps: spec.SchemaProps{ + Description: "conditions defines current service state of the MachineHealthCheck.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineInitializationStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineInitializationStatus provides observations of the Machine initialization process. NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Machine provisioning.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "infrastructureProvisioned": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructureProvisioned is true when the infrastructure provider reports that Machine's infrastructure is fully provisioned. NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. The value of this field is never updated after provisioning is completed.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "bootstrapDataSecretCreated": { + SchemaProps: spec.SchemaProps{ + Description: "bootstrapDataSecretCreated is true when the bootstrap provider reports that the Machine's boostrap secret is created. NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. The value of this field is never updated after provisioning is completed.", + Type: []string{"boolean"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineList contains a list of Machine.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items is the list of Machines.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Machine"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.Machine"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineNamingSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineNamingSpec allows changing the naming pattern used when creating Machines. Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template defines the template to use for generating the names of the Machine objects. If not defined, it will fallback to `{{ .machineSet.name }}-{{ .random }}`. If the generated name string exceeds 63 characters, it will be trimmed to 58 characters and will get concatenated with a random suffix of length 5. Length of the template string must not exceed 256 characters. The template allows the following variables `.cluster.name`, `.machineSet.name` and `.random`. The variable `.cluster.name` retrieves the name of the cluster object that owns the Machines being created. The variable `.machineSet.name` retrieves the name of the MachineSet object that owns the Machines being created. The variable `.random` is substituted with random alphanumeric string, without vowels, of length 5. This variable is required part of the template. If not provided, validation will fail.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineNodeReference(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineNodeReference is a reference to the node running on the machine.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name of the node. name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"name"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePool(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePool is the Schema for the machinepools API. NOTE: This CRD can only be used if the MachinePool feature gate is enabled.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the desired state of MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status is the observed state of MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolClass(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolClass serves as a template to define a pool of worker nodes of the cluster provisioned using `ClusterClass`.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the metadata applied to the MachinePool. At runtime this metadata is merged with the corresponding metadata from the topology.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"), + }, + }, + "class": { + SchemaProps: spec.SchemaProps{ + Description: "class denotes a type of machine pool present in the cluster, this name MUST be unique within a ClusterClass and can be referenced in the Cluster to create a managed MachinePool.", + Type: []string{"string"}, + Format: "", + }, + }, + "bootstrap": { + SchemaProps: spec.SchemaProps{ + Description: "bootstrap contains the bootstrap template reference to be used for the creation of the Machines in the MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassBootstrapTemplate"), + }, + }, + "infrastructure": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructure contains the infrastructure template reference to be used for the creation of the MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassInfrastructureTemplate"), + }, + }, + "failureDomains": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "failureDomains is the list of failure domains the MachinePool should be attached to. Must match a key in the FailureDomains map stored on the cluster object. NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "naming": { + SchemaProps: spec.SchemaProps{ + Description: "naming allows changing the naming pattern used when creating the MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassNamingSpec"), + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for Machine deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassMachineDeletionSpec"), + }, + }, + "minReadySeconds": { + SchemaProps: spec.SchemaProps{ + Description: "minReadySeconds is the minimum number of seconds for which a newly created machine pool should be ready. Defaults to 0 (machine will be considered available as soon as it is ready) NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + Required: []string{"class", "bootstrap", "infrastructure"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassBootstrapTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassInfrastructureTemplate", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassMachineDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClassNamingSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolClassBootstrapTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolClassBootstrapTemplate defines the BootstrapTemplate for a MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a required reference to the BootstrapTemplate for a MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"), + }, + }, + }, + Required: []string{"templateRef"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolClassInfrastructureTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolClassInfrastructureTemplate defines the InfrastructureTemplate for a MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "templateRef": { + SchemaProps: spec.SchemaProps{ + Description: "templateRef is a required reference to the InfrastructureTemplate for a MachinePool.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"), + }, + }, + }, + Required: []string{"templateRef"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassTemplateReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolClassMachineDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolClassMachineDeletionSpec contains configuration options for Machine deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeDrainTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. The default value is 0, meaning that the node can be drained without any time limitations. NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout` NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeVolumeDetachTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations. NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeDeletionTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the Machine hosts after the Machine Pool is marked for deletion. A duration of 0 will retry deletion indefinitely. Defaults to 10 seconds. NOTE: This value can be overridden while defining a Cluster.Topology using this MachinePoolClass.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolClassNamingSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolClassNamingSpec defines the naming strategy for MachinePool objects.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template defines the template to use for generating the name of the MachinePool object. If not defined, it will fallback to `{{ .cluster.name }}-{{ .machinePool.topologyName }}-{{ .random }}`. If the templated string exceeds 63 characters, it will be trimmed to 58 characters and will get concatenated with a random suffix of length 5. The templating mechanism provides the following arguments: * `.cluster.name`: The name of the cluster object. * `.random`: A random alphanumeric string, without vowels, of length 5. * `.machinePool.topologyName`: The name of the MachinePool topology (Cluster.spec.topology.workers.machinePools[].name).", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolDeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "v1beta1": { + SchemaProps: spec.SchemaProps{ + Description: "v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolV1Beta1DeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolV1Beta1DeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolInitializationStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolInitializationStatus provides observations of the MachinePool initialization process. NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial MachinePool provisioning.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "infrastructureProvisioned": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructureProvisioned is true when the infrastructure provider reports that MachinePool's infrastructure is fully provisioned. NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. The value of this field is never updated after provisioning is completed.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "bootstrapDataSecretCreated": { + SchemaProps: spec.SchemaProps{ + Description: "bootstrapDataSecretCreated is true when the bootstrap provider reports that the MachinePool's boostrap secret is created. NOTE: this field is part of the Cluster API contract, and it is used to orchestrate provisioning. The value of this field is never updated after provisioning is completed.", + Type: []string{"boolean"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolList contains a list of MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items is the list of MachinePools.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePool"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePool"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolSpec defines the desired state of MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "clusterName": { + SchemaProps: spec.SchemaProps{ + Description: "clusterName is the name of the Cluster this object belongs to.", + Type: []string{"string"}, + Format: "", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the number of desired machines. Defaults to 1. This is a pointer to distinguish between explicit zero and not specified.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template describes the machines that will be created.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineTemplateSpec"), + }, + }, + "providerIDList": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "providerIDList are the identification IDs of machine instances provided by the provider. This field must match the provider IDs as seen on the node objects corresponding to a machine pool's machine instances.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "failureDomains": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "failureDomains is the list of failure domains this MachinePool should be attached to.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + Required: []string{"clusterName", "template"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineTemplateSpec"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolStatus defines the observed state of MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observations of a MachinePool's current state. Known condition types are Available, BootstrapConfigReady, InfrastructureReady, MachinesReady, MachinesUpToDate, ScalingUp, ScalingDown, Remediating, Deleting, Paused.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "initialization": { + SchemaProps: spec.SchemaProps{ + Description: "initialization provides observations of the MachinePool initialization process. NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial MachinePool provisioning.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolInitializationStatus"), + }, + }, + "nodeRefs": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "nodeRefs will point to the corresponding Nodes if it they exist.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/api/core/v1.ObjectReference"), + }, + }, + }, + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the most recently observed number of replicas.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the number of ready replicas for this MachinePool. A machine is considered ready when Machine's Ready condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the number of available replicas for this MachinePool. A machine is considered available when Machine's Available condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "upToDateReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "upToDateReplicas is the number of up-to-date replicas targeted by this MachinePool. A machine is considered up-to-date when Machine's UpToDate condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "phase": { + SchemaProps: spec.SchemaProps{ + Description: "phase represents the current phase of cluster actuation.", + Type: []string{"string"}, + Format: "", + }, + }, + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "observedGeneration is the latest generation observed by the controller.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "deprecated": { + SchemaProps: spec.SchemaProps{ + Description: "deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolDeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolDeprecatedStatus", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolInitializationStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolTopology specifies the different parameters for a pool of worker nodes in the topology. This pool of nodes is managed by a MachinePool object whose lifecycle is managed by the Cluster controller.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the metadata applied to the MachinePool. At runtime this metadata is merged with the corresponding metadata from the ClusterClass.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"), + }, + }, + "class": { + SchemaProps: spec.SchemaProps{ + Description: "class is the name of the MachinePoolClass used to create the pool of worker nodes. This should match one of the deployment classes defined in the ClusterClass object mentioned in the `Cluster.Spec.Class` field.", + Type: []string{"string"}, + Format: "", + }, + }, + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name is the unique identifier for this MachinePoolTopology. The value is used with other unique identifiers to create a MachinePool's Name (e.g. cluster's name, etc). In case the name is greater than the allowed maximum length, the values are hashed together.", + Type: []string{"string"}, + Format: "", + }, + }, + "failureDomains": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "failureDomains is the list of failure domains the machine pool will be created in. Must match a key in the FailureDomains map stored on the cluster object.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for Machine deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolTopologyMachineDeletionSpec"), + }, + }, + "minReadySeconds": { + SchemaProps: spec.SchemaProps{ + Description: "minReadySeconds is the minimum number of seconds for which a newly created machine pool should be ready. Defaults to 0 (machine will be considered available as soon as it is ready)", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the number of nodes belonging to this pool. If the value is nil, the MachinePool is created without the number of Replicas (defaulting to 1) and it's assumed that an external entity (like cluster autoscaler) is responsible for the management of this value.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "variables": { + SchemaProps: spec.SchemaProps{ + Description: "variables can be used to customize the MachinePool through patches.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolVariables"), + }, + }, + }, + Required: []string{"class", "name"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolTopologyMachineDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolVariables", "sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolTopologyMachineDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolTopologyMachineDeletionSpec contains configuration options for Machine deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "nodeDrainTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDrainTimeoutSeconds is the total amount of time that the controller will spend on draining a node. The default value is 0, meaning that the node can be drained without any time limitations. NOTE: nodeDrainTimeoutSeconds is different from `kubectl drain --timeout`", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeVolumeDetachTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeVolumeDetachTimeoutSeconds is the total amount of time that the controller will spend on waiting for all volumes to be detached. The default value is 0, meaning that the volumes can be detached without any time limitations.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "nodeDeletionTimeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "nodeDeletionTimeoutSeconds defines how long the controller will attempt to delete the Node that the MachinePool hosts after the MachinePool is marked for deletion. A duration of 0 will retry deletion indefinitely. Defaults to 10 seconds.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolV1Beta1DeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + SchemaProps: spec.SchemaProps{ + Description: "conditions define the current service state of the MachinePool.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"), + }, + }, + }, + }, + }, + "failureReason": { + SchemaProps: spec.SchemaProps{ + Description: "failureReason indicates that there is a problem reconciling the state, and will be set to a token value suitable for programmatic interpretation.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + "failureMessage": { + SchemaProps: spec.SchemaProps{ + Description: "failureMessage indicates that there is a problem reconciling the state, and will be set to a descriptive error message.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the number of ready replicas for this MachinePool. A machine is considered ready when the node has been created and is \"Ready\".\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the number of available replicas (ready for at least minReadySeconds) for this MachinePool.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "unavailableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "unavailableReplicas is the total number of unavailable machine instances targeted by this machine pool. This is the total number of machine instances that are still required for the machine pool to have 100% available capacity. They may either be machine instances that are running but not yet available or machine instances that still have not been created.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachinePoolVariables(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachinePoolVariables can be used to provide variables for a specific MachinePool.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "overrides": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "name", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "overrides can be used to override Cluster level variables.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineReadinessGate(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineReadinessGate contains the type of a Machine condition to be used as a readiness gate.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditionType": { + SchemaProps: spec.SchemaProps{ + Description: "conditionType refers to a condition with matching type in the Machine's condition list. If the conditions doesn't exist, it will be treated as unknown. Note: Both Cluster API conditions or conditions added by 3rd party controllers can be used as readiness gates.", + Type: []string{"string"}, + Format: "", + }, + }, + "polarity": { + SchemaProps: spec.SchemaProps{ + Description: "polarity of the conditionType specified in this readinessGate. Valid values are Positive, Negative and omitted. When omitted, the default behaviour will be Positive. A positive polarity means that the condition should report a true status under normal conditions. A negative polarity means that the condition should report a false status under normal conditions.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"conditionType"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineSet(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineSet is the Schema for the machinesets API.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the desired state of MachineSet.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status is the observed state of MachineSet.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineSetDeletionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineSetDeletionSpec contains configuration options for MachineSet deletion.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "order": { + SchemaProps: spec.SchemaProps{ + Description: "order defines the order in which Machines are deleted when downscaling. Defaults to \"Random\". Valid values are \"Random, \"Newest\", \"Oldest\"", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineSetDeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineSetDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "v1beta1": { + SchemaProps: spec.SchemaProps{ + Description: "v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetV1Beta1DeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetV1Beta1DeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineSetList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineSetList contains a list of MachineSet.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items is the list of MachineSets.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSet"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSet"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineSetSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineSetSpec defines the desired state of MachineSet.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "clusterName": { + SchemaProps: spec.SchemaProps{ + Description: "clusterName is the name of the Cluster this object belongs to.", + Type: []string{"string"}, + Format: "", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified.\n\nDefaults to: * if the Kubernetes autoscaler min size and max size annotations are set:\n - if it's a new MachineSet, use min size\n - if the replicas field of the old MachineSet is < min size, use min size\n - if the replicas field of the old MachineSet is > max size, use max size\n - if the replicas field of the old MachineSet is in the (min size, max size) range, keep the value from the oldMS\n* otherwise use 1 Note: Defaulting will be run whenever the replicas field is not set: * A new MachineSet is created with replicas not set. * On an existing MachineSet the replicas field was first set and is now unset. Those cases are especially relevant for the following Kubernetes autoscaler use cases: * A new MachineSet is created and replicas should be managed by the autoscaler * An existing MachineSet which initially wasn't controlled by the autoscaler\n should be later controlled by the autoscaler", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "selector": { + SchemaProps: spec.SchemaProps{ + Description: "selector is a label query over machines that should match the replica count. Label keys and values that must match in order to be controlled by this MachineSet. It must match the machine template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), + }, + }, + "template": { + SchemaProps: spec.SchemaProps{ + Description: "template is the object that describes the machine that will be created if insufficient replicas are detected. Object references to custom resources are treated as templates.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineTemplateSpec"), + }, + }, + "machineNaming": { + SchemaProps: spec.SchemaProps{ + Description: "machineNaming allows changing the naming pattern used when creating Machines. Note: InfraMachines & BootstrapConfigs will use the same name as the corresponding Machines.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNamingSpec"), + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for MachineSet deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetDeletionSpec"), + }, + }, + }, + Required: []string{"clusterName", "selector", "template"}, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNamingSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineTemplateSpec"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineSetStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineSetStatus defines the observed state of MachineSet.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observations of a MachineSet's current state. Known condition types are MachinesReady, MachinesUpToDate, ScalingUp, ScalingDown, Remediating, Deleting, Paused.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "selector": { + SchemaProps: spec.SchemaProps{ + Description: "selector is the same as the label selector but in the string format to avoid introspection by clients. The string will be in the same format as the query-param syntax. More info about label selectors: http://kubernetes.io/docs/user-guide/labels#label-selectors", + Type: []string{"string"}, + Format: "", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the most recently observed number of replicas.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the number of ready replicas for this MachineSet. A machine is considered ready when Machine's Ready condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the number of available replicas for this MachineSet. A machine is considered available when Machine's Available condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "upToDateReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "upToDateReplicas is the number of up-to-date replicas for this MachineSet. A machine is considered up-to-date when Machine's UpToDate condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "observedGeneration reflects the generation of the most recently observed MachineSet.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "deprecated": { + SchemaProps: spec.SchemaProps{ + Description: "deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetDeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSetDeprecatedStatus"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineSetV1Beta1DeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineSetV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + SchemaProps: spec.SchemaProps{ + Description: "conditions defines current service state of the MachineSet.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"), + }, + }, + }, + }, + }, + "failureReason": { + SchemaProps: spec.SchemaProps{ + Description: "failureReason will be set in the event that there is a terminal problem reconciling the Machine and will contain a succinct value suitable for machine interpretation.\n\nIn the event that there is a terminal problem reconciling the replicas, both FailureReason and FailureMessage will be set. FailureReason will be populated with a succinct value suitable for machine interpretation, while FailureMessage will contain a more verbose string suitable for logging and human consumption.\n\nThese fields should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the MachineTemplate's spec or the configuration of the machine controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the machine controller, or the responsible machine controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the MachineSet object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + "failureMessage": { + SchemaProps: spec.SchemaProps{ + Description: "failureMessage will be set in the event that there is a terminal problem reconciling the Machine and will contain a more verbose string suitable for logging and human consumption.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + "fullyLabeledReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "fullyLabeledReplicas is the number of replicas that have labels matching the labels of the machine template of the MachineSet.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the number of ready replicas for this MachineSet. A machine is considered ready when the node has been created and is \"Ready\".\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the number of available replicas (ready for at least minReadySeconds) for this MachineSet.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineSpec defines the desired state of Machine.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "clusterName": { + SchemaProps: spec.SchemaProps{ + Description: "clusterName is the name of the Cluster this object belongs to.", + Type: []string{"string"}, + Format: "", + }, + }, + "bootstrap": { + SchemaProps: spec.SchemaProps{ + Description: "bootstrap is a reference to a local struct which encapsulates fields to configure the Machine’s bootstrapping mechanism.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Bootstrap"), + }, + }, + "infrastructureRef": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructureRef is a required reference to a custom resource offered by an infrastructure provider.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference"), + }, + }, + "version": { + SchemaProps: spec.SchemaProps{ + Description: "version defines the desired Kubernetes version. This field is meant to be optionally used by bootstrap providers.", + Type: []string{"string"}, + Format: "", + }, + }, + "providerID": { + SchemaProps: spec.SchemaProps{ + Description: "providerID is the identification ID of the machine provided by the provider. This field must match the provider ID as seen on the node object corresponding to this machine. This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a generic out-of-tree provider for autoscaler, this field is required by autoscaler to be able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver and then a comparison is done to find out unregistered machines and are marked for delete. This field will be set by the actuators and consumed by higher level entities like autoscaler that will be interfacing with cluster-api as generic provider.", + Type: []string{"string"}, + Format: "", + }, + }, + "failureDomain": { + SchemaProps: spec.SchemaProps{ + Description: "failureDomain is the failure domain the machine will be created in. Must match the name of a FailureDomain from the Cluster status.", + Type: []string{"string"}, + Format: "", + }, + }, + "minReadySeconds": { + SchemaProps: spec.SchemaProps{ + Description: "minReadySeconds is the minimum number of seconds for which a Machine should be ready before considering it available. Defaults to 0 (Machine will be considered available as soon as the Machine is ready)", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readinessGates": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "conditionType", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "readinessGates specifies additional conditions to include when evaluating Machine Ready condition.\n\nThis field can be used e.g. by Cluster API control plane providers to extend the semantic of the Ready condition for the Machine they control, like the kubeadm control provider adding ReadinessGates for the APIServerPodHealthy, SchedulerPodHealthy conditions, etc.\n\nAnother example are external controllers, e.g. responsible to install special software/hardware on the Machines; they can include the status of those components with a new condition and add this condition to ReadinessGates.\n\nNOTE: In case readinessGates conditions start with the APIServer, ControllerManager, Scheduler prefix, and all those readiness gates condition are reporting the same message, when computing the Machine's Ready condition those readinessGates will be replaced by a single entry reporting \"Control plane components: \" + message. This helps to improve readability of conditions bubbling up to the Machine's owner resource / to the Cluster).", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate"), + }, + }, + }, + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains configuration options for Machine deletion.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeletionSpec"), + }, + }, + }, + Required: []string{"clusterName", "bootstrap", "infrastructureRef"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.Bootstrap", "sigs.k8s.io/cluster-api/api/core/v1beta2.ContractVersionedObjectReference", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeletionSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineReadinessGate"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineStatus defines the observed state of Machine.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observations of a Machine's current state. Known condition types are Available, Ready, UpToDate, BootstrapConfigReady, InfrastructureReady, NodeReady, NodeHealthy, Deleting, Paused. If a MachineHealthCheck is targeting this machine, also HealthCheckSucceeded, OwnerRemediated conditions are added. Additionally control plane Machines controlled by KubeadmControlPlane will have following additional conditions: APIServerPodHealthy, ControllerManagerPodHealthy, SchedulerPodHealthy, EtcdPodHealthy, EtcdMemberHealthy.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "initialization": { + SchemaProps: spec.SchemaProps{ + Description: "initialization provides observations of the Machine initialization process. NOTE: Fields in this struct are part of the Cluster API contract and are used to orchestrate initial Machine provisioning.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineInitializationStatus"), + }, + }, + "nodeRef": { + SchemaProps: spec.SchemaProps{ + Description: "nodeRef will point to the corresponding Node if it exists.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNodeReference"), + }, + }, + "nodeInfo": { + SchemaProps: spec.SchemaProps{ + Description: "nodeInfo is a set of ids/uuids to uniquely identify the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#info", + Ref: ref("k8s.io/api/core/v1.NodeSystemInfo"), + }, + }, + "lastUpdated": { + SchemaProps: spec.SchemaProps{ + Description: "lastUpdated identifies when the phase of the Machine last transitioned.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), + }, + }, + "addresses": { + SchemaProps: spec.SchemaProps{ + Description: "addresses is a list of addresses assigned to the machine. This field is copied from the infrastructure provider reference.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineAddress"), + }, + }, + }, + }, + }, + "phase": { + SchemaProps: spec.SchemaProps{ + Description: "phase represents the current phase of machine actuation.", + Type: []string{"string"}, + Format: "", + }, + }, + "certificatesExpiryDate": { + SchemaProps: spec.SchemaProps{ + Description: "certificatesExpiryDate is the expiry date of the machine certificates. This value is only set for control plane machines.", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), + }, + }, + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "observedGeneration is the latest generation observed by the controller.", + Type: []string{"integer"}, + Format: "int64", + }, + }, + "deletion": { + SchemaProps: spec.SchemaProps{ + Description: "deletion contains information relating to removal of the Machine. Only present when the Machine has a deletionTimestamp and drain or wait for volume detach started.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeletionStatus"), + }, + }, + "deprecated": { + SchemaProps: spec.SchemaProps{ + Description: "deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeprecatedStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "k8s.io/api/core/v1.NodeSystemInfo", "k8s.io/apimachinery/pkg/apis/meta/v1.Condition", "k8s.io/apimachinery/pkg/apis/meta/v1.Time", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineAddress", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeletionStatus", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeprecatedStatus", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineInitializationStatus", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineNodeReference"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineTemplateSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineTemplateSpec describes the data needed to create a Machine from a template.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec is the specification of the desired behavior of the machine. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSpec"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineSpec", "sigs.k8s.io/cluster-api/api/core/v1beta2.ObjectMeta"}, + } +} + +func schema_cluster_api_api_core_v1beta2_MachineV1Beta1DeprecatedStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "MachineV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + SchemaProps: spec.SchemaProps{ + Description: "conditions defines current service state of the Machine.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"), + }, + }, + }, + }, + }, + "failureReason": { + SchemaProps: spec.SchemaProps{ + Description: "failureReason will be set in the event that there is a terminal problem reconciling the Machine and will contain a succinct value suitable for machine interpretation.\n\nThis field should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the Machine's spec or the configuration of the controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the controller, or the responsible controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the Machine object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + "failureMessage": { + SchemaProps: spec.SchemaProps{ + Description: "failureMessage will be set in the event that there is a terminal problem reconciling the Machine and will contain a more verbose string suitable for logging and human consumption.\n\nThis field should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the Machine's spec or the configuration of the controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the controller, or the responsible controller itself being critically misconfigured.\n\nAny transient errors that occur during the reconciliation of Machines can be added as events to the Machine object and/or logged in the controller's output.\n\nDeprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.Condition"}, + } +} + +func schema_cluster_api_api_core_v1beta2_NetworkRanges(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "NetworkRanges represents ranges of network addresses.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "cidrBlocks": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "cidrBlocks is a list of CIDR blocks.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + Required: []string{"cidrBlocks"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ObjectMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create. This is a copy of customizable fields from metav1.ObjectMeta.\n\nObjectMeta is embedded in `Machine.Spec`, `MachineDeployment.Template` and `MachineSet.Template`, which are not top-level Kubernetes objects. Given that metav1.ObjectMeta has lots of special cases and read-only fields which end up in the generated CRD validation, having it as a subset simplifies the API and some issues that can impact user experience.\n\nDuring the [upgrade to controller-tools@v2](https://github.com/kubernetes-sigs/cluster-api/pull/1054) for v1alpha2, we noticed a failure would occur running Cluster API test suite against the new CRDs, specifically `spec.metadata.creationTimestamp in body must be of type string: \"null\"`. The investigation showed that `controller-tools@v2` behaves differently than its previous version when handling types from [metav1](k8s.io/apimachinery/pkg/apis/meta/v1) package.\n\nIn more details, we found that embedded (non-top level) types that embedded `metav1.ObjectMeta` had validation properties, including for `creationTimestamp` (metav1.Time). The `metav1.Time` type specifies a custom json marshaller that, when IsZero() is true, returns `null` which breaks validation because the field isn't marked as nullable.\n\nIn future versions, controller-tools@v2 might allow overriding the type and validation for embedded types. When that happens, this hack should be revisited.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "labels": { + SchemaProps: spec.SchemaProps{ + Description: "labels is a map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "annotations": { + SchemaProps: spec.SchemaProps{ + Description: "annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_PatchDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "PatchDefinition defines a patch which is applied to customize the referenced templates.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "selector": { + SchemaProps: spec.SchemaProps{ + Description: "selector defines on which templates the patch should be applied.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelector"), + }, + }, + "jsonPatches": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "jsonPatches defines the patches which should be applied on the templates matching the selector. Note: Patches will be applied in the order of the array.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONPatch"), + }, + }, + }, + }, + }, + }, + Required: []string{"selector", "jsonPatches"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.JSONPatch", "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelector"}, + } +} + +func schema_cluster_api_api_core_v1beta2_PatchSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "PatchSelector defines on which templates the patch should be applied. Note: Matching on APIVersion and Kind is mandatory, to enforce that the patches are written for the correct version. The version of the references in the ClusterClass may be automatically updated during reconciliation if there is a newer version for the same contract. Note: The results of selection based on the individual fields are ANDed.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "apiVersion filters templates by apiVersion. apiVersion must be fully qualified domain name followed by / and a version.", + Type: []string{"string"}, + Format: "", + }, + }, + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "kind filters templates by kind. kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character.", + Type: []string{"string"}, + Format: "", + }, + }, + "matchResources": { + SchemaProps: spec.SchemaProps{ + Description: "matchResources selects templates based on where they are referenced.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatch"), + }, + }, + }, + Required: []string{"apiVersion", "kind", "matchResources"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatch"}, + } +} + +func schema_cluster_api_api_core_v1beta2_PatchSelectorMatch(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "PatchSelectorMatch selects templates based on where they are referenced. Note: The selector must match at least one template. Note: The results of selection based on the individual fields are ORed.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "controlPlane": { + SchemaProps: spec.SchemaProps{ + Description: "controlPlane selects templates referenced in .spec.ControlPlane. Note: this will match the controlPlane and also the controlPlane machineInfrastructure (depending on the kind and apiVersion).", + Type: []string{"boolean"}, + Format: "", + }, + }, + "infrastructureCluster": { + SchemaProps: spec.SchemaProps{ + Description: "infrastructureCluster selects templates referenced in .spec.infrastructure.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "machineDeploymentClass": { + SchemaProps: spec.SchemaProps{ + Description: "machineDeploymentClass selects templates referenced in specific MachineDeploymentClasses in .spec.workers.machineDeployments.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatchMachineDeploymentClass"), + }, + }, + "machinePoolClass": { + SchemaProps: spec.SchemaProps{ + Description: "machinePoolClass selects templates referenced in specific MachinePoolClasses in .spec.workers.machinePools.", + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatchMachinePoolClass"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatchMachineDeploymentClass", "sigs.k8s.io/cluster-api/api/core/v1beta2.PatchSelectorMatchMachinePoolClass"}, + } +} + +func schema_cluster_api_api_core_v1beta2_PatchSelectorMatchMachineDeploymentClass(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "PatchSelectorMatchMachineDeploymentClass selects templates referenced in specific MachineDeploymentClasses in .spec.workers.machineDeployments.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "names": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "names selects templates by class names.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_PatchSelectorMatchMachinePoolClass(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "PatchSelectorMatchMachinePoolClass selects templates referenced in specific MachinePoolClasses in .spec.workers.machinePools.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "names": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "names selects templates by class names.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_Topology(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Topology encapsulates the information of the managed resources.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "classRef": { + SchemaProps: spec.SchemaProps{ + Description: "classRef is the ref to the ClusterClass that should be used for the topology.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassRef"), + }, + }, + "version": { + SchemaProps: spec.SchemaProps{ + Description: "version is the Kubernetes version of the cluster.", + Type: []string{"string"}, + Format: "", + }, + }, + "controlPlane": { + SchemaProps: spec.SchemaProps{ + Description: "controlPlane describes the cluster control plane.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopology"), + }, + }, + "workers": { + SchemaProps: spec.SchemaProps{ + Description: "workers encapsulates the different constructs that form the worker nodes for the cluster.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersTopology"), + }, + }, + "variables": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "name", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "variables can be used to customize the Cluster through patches. They must comply to the corresponding VariableClasses defined in the ClusterClass.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable"), + }, + }, + }, + }, + }, + }, + Required: []string{"classRef", "version"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterClassRef", "sigs.k8s.io/cluster-api/api/core/v1beta2.ClusterVariable", "sigs.k8s.io/cluster-api/api/core/v1beta2.ControlPlaneTopology", "sigs.k8s.io/cluster-api/api/core/v1beta2.WorkersTopology"}, + } +} + +func schema_cluster_api_api_core_v1beta2_UnhealthyNodeCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "UnhealthyNodeCondition represents a Node condition type and value with a timeout specified as a duration. When the named condition has been in the given status for at least the timeout value, a node is considered unhealthy.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "type": { + SchemaProps: spec.SchemaProps{ + Description: "type of Node condition", + Type: []string{"string"}, + Format: "", + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status of the condition, one of True, False, Unknown.", + Type: []string{"string"}, + Format: "", + }, + }, + "timeoutSeconds": { + SchemaProps: spec.SchemaProps{ + Description: "timeoutSeconds is the duration that a node must be in a given status for, after which the node is considered unhealthy. For example, with a value of \"1h\", the node must match the status for at least 1 hour before being considered unhealthy.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + Required: []string{"type", "status", "timeoutSeconds"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_ValidationRule(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "ValidationRule describes a validation rule written in the CEL expression language.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "rule": { + SchemaProps: spec.SchemaProps{ + Description: "rule represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec The Rule is scoped to the location of the x-kubernetes-validations extension in the schema. The `self` variable in the CEL expression is bound to the scoped value. If the Rule is scoped to an object with properties, the accessible properties of the object are field selectable via `self.field` and field presence can be checked via `has(self.field)`. If the Rule is scoped to an object with additionalProperties (i.e. a map) the value of the map are accessible via `self[mapKey]`, map containment can be checked via `mapKey in self` and all entries of the map are accessible via CEL macros and functions such as `self.all(...)`. If the Rule is scoped to an array, the elements of the array are accessible via `self[i]` and also by macros and functions. If the Rule is scoped to a scalar, `self` is bound to the scalar value. Examples: - Rule scoped to a map of objects: {\"rule\": \"self.components['Widget'].priority < 10\"} - Rule scoped to a list of integers: {\"rule\": \"self.values.all(value, value >= 0 && value < 100)\"} - Rule scoped to a string value: {\"rule\": \"self.startsWith('kube')\"}\n\nUnknown data preserved in custom resources via x-kubernetes-preserve-unknown-fields is not accessible in CEL expressions. This includes: - Unknown field values that are preserved by object schemas with x-kubernetes-preserve-unknown-fields. - Object properties where the property schema is of an \"unknown type\". An \"unknown type\" is recursively defined as:\n - A schema with no type and x-kubernetes-preserve-unknown-fields set to true\n - An array where the items schema is of an \"unknown type\"\n - An object where the additionalProperties schema is of an \"unknown type\"\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Rule accessing a property named \"namespace\": {\"rule\": \"self.__namespace__ > 0\"}\n - Rule accessing a property named \"x-prop\": {\"rule\": \"self.x__dash__prop > 0\"}\n - Rule accessing a property named \"redact__d\": {\"rule\": \"self.redact__underscores__d > 0\"}\n\nIf `rule` makes use of the `oldSelf` variable it is implicitly a `transition rule`.\n\nBy default, the `oldSelf` variable is the same type as `self`.\n\nTransition rules by default are applied only on UPDATE requests and are skipped if an old value could not be found.", + Type: []string{"string"}, + Format: "", + }, + }, + "message": { + SchemaProps: spec.SchemaProps{ + Description: "message represents the message displayed when validation fails. The message is required if the Rule contains line breaks. The message must not contain line breaks. If unset, the message is \"failed rule: {Rule}\". e.g. \"must be a URL with the host matching spec.host\"", + Type: []string{"string"}, + Format: "", + }, + }, + "messageExpression": { + SchemaProps: spec.SchemaProps{ + Description: "messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a rule, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset. messageExpression has access to all the same variables as the rule; the only difference is the return type. Example: \"x must be less than max (\"+string(self.max)+\")\"", + Type: []string{"string"}, + Format: "", + }, + }, + "reason": { + SchemaProps: spec.SchemaProps{ + Description: "reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule. The currently supported reasons are: \"FieldValueInvalid\", \"FieldValueForbidden\", \"FieldValueRequired\", \"FieldValueDuplicate\". If not set, default to use \"FieldValueInvalid\". All future added reasons must be accepted by clients when reading this value and unknown reasons should be treated as FieldValueInvalid.", + Default: FieldValueInvalid, + Type: []string{"string"}, + Format: "", + }, + }, + "fieldPath": { + SchemaProps: spec.SchemaProps{ + Description: "fieldPath represents the field path returned when the validation fails. It must be a relative JSON path (i.e. with array notation) scoped to the location of this x-kubernetes-validations extension in the schema and refer to an existing field. e.g. when validation checks if a specific attribute `foo` under a map `testMap`, the fieldPath could be set to `.testMap.foo` If the validation checks two lists must have unique attributes, the fieldPath could be set to either of the list: e.g. `.testList` It does not support list numeric index. It supports child operation to refer to an existing field currently. Refer to [JSONPath support in Kubernetes](https://kubernetes.io/docs/reference/kubectl/jsonpath/) for more info. Numeric index of array is not supported. For field name which contains special characters, use `['specialName']` to refer the field name. e.g. for attribute `foo.34$` appears in a list `testList`, the fieldPath could be set to `.testList['foo.34$']`", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"rule"}, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_VariableSchema(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "VariableSchema defines the schema of a variable.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "openAPIV3Schema": { + SchemaProps: spec.SchemaProps{ + Description: "openAPIV3Schema defines the schema of a variable via OpenAPI v3 schema. The schema is a subset of the schema used in Kubernetes CRDs.", + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"), + }, + }, + }, + Required: []string{"openAPIV3Schema"}, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.JSONSchemaProps"}, + } +} + +func schema_cluster_api_api_core_v1beta2_VariableSchemaMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "VariableSchemaMetadata is the metadata of a variable or a nested field within a variable. It can be used to add additional data for higher level tools.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "labels": { + SchemaProps: spec.SchemaProps{ + Description: "labels is a map of string keys and values that can be used to organize and categorize (scope and select) variables.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "annotations": { + SchemaProps: spec.SchemaProps{ + Description: "annotations is an unstructured key value map that can be used to store and retrieve arbitrary metadata. They are not queryable.", + Type: []string{"object"}, + AdditionalProperties: &spec.SchemaOrBool{ + Allows: true, + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_WorkersClass(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "WorkersClass is a collection of deployment classes.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "machineDeployments": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "class", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "machineDeployments is a list of machine deployment classes that can be used to create a set of worker nodes.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClass"), + }, + }, + }, + }, + }, + "machinePools": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "class", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "machinePools is a list of machine pool classes that can be used to create a set of worker nodes.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClass"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentClass", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolClass"}, + } +} + +func schema_cluster_api_api_core_v1beta2_WorkersStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "WorkersStatus groups all the observations about workers current state.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "desiredReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "desiredReplicas is the total number of desired worker machines in this cluster.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "replicas": { + SchemaProps: spec.SchemaProps{ + Description: "replicas is the total number of worker machines in this cluster. NOTE: replicas also includes machines still being provisioned or being deleted.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "upToDateReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "upToDateReplicas is the number of up-to-date worker machines in this cluster. A machine is considered up-to-date when Machine's UpToDate condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "readyReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "readyReplicas is the total number of ready worker machines in this cluster. A machine is considered ready when Machine's Ready condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + "availableReplicas": { + SchemaProps: spec.SchemaProps{ + Description: "availableReplicas is the total number of available worker machines in this cluster. A machine is considered available when Machine's Available condition is true.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_cluster_api_api_core_v1beta2_WorkersTopology(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "WorkersTopology represents the different sets of worker nodes in the cluster.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "machineDeployments": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "name", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "machineDeployments is a list of machine deployments in the cluster.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopology"), + }, + }, + }, + }, + }, + "machinePools": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "name", + }, + "x-kubernetes-list-type": "map", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "machinePools is a list of machine pools in the cluster.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolTopology"), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + "sigs.k8s.io/cluster-api/api/core/v1beta2.MachineDeploymentTopology", "sigs.k8s.io/cluster-api/api/core/v1beta2.MachinePoolTopology"}, + } +} diff --git a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/conversion.go b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/conversion.go similarity index 81% rename from vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/conversion.go rename to vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/conversion.go index 91e5b549c388..c743eabcec9c 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/conversion.go +++ b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2021 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta1 +package v1beta2 -func (*MachinePool) Hub() {} -func (*MachinePoolList) Hub() {} +func (*IPAddress) Hub() {} +func (*IPAddressClaim) Hub() {} diff --git a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/doc.go b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/doc.go similarity index 72% rename from vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/doc.go rename to vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/doc.go index 81c65d7f34d0..714e2eeb9bfa 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/doc.go +++ b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1beta1 contains API Schema definitions for the v1beta1 IPAM API. -package v1beta1 +// Package v1beta2 contains API Schema definitions for the v1beta2 IPAM API. +// +kubebuilder:object:generate=true +// +groupName=ipam.cluster.x-k8s.io +package v1beta2 diff --git a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/groupversion_info.go b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/groupversion_info.go similarity index 89% rename from vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/groupversion_info.go rename to vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/groupversion_info.go index e01b1ad46179..d477a32300e1 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/groupversion_info.go +++ b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/groupversion_info.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,10 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +kubebuilder:object:generate=true -// +groupName=ipam.cluster.x-k8s.io - -package v1beta1 +package v1beta2 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -27,7 +24,7 @@ import ( var ( // GroupVersion is group version used to register these objects. - GroupVersion = schema.GroupVersion{Group: "ipam.cluster.x-k8s.io", Version: "v1beta1"} + GroupVersion = schema.GroupVersion{Group: "ipam.cluster.x-k8s.io", Version: "v1beta2"} // schemeBuilder is used to add go types to the GroupVersionKind scheme. schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) diff --git a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/ipaddress_types.go b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/ipaddress_types.go similarity index 57% rename from vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/ipaddress_types.go rename to vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/ipaddress_types.go index 8410bf08f794..5d88adea686a 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/ipaddress_types.go +++ b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/ipaddress_types.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,10 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta1 +package v1beta2 import ( - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -25,21 +24,23 @@ import ( type IPAddressSpec struct { // claimRef is a reference to the claim this IPAddress was created for. // +required - ClaimRef corev1.LocalObjectReference `json:"claimRef"` + ClaimRef IPAddressClaimReference `json:"claimRef,omitempty,omitzero"` // poolRef is a reference to the pool that this IPAddress was created from. // +required - PoolRef corev1.TypedLocalObjectReference `json:"poolRef"` + PoolRef IPPoolReference `json:"poolRef,omitempty,omitzero"` // address is the IP address. // +required // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=39 - Address string `json:"address"` + Address string `json:"address,omitempty"` // prefix is the prefix of the address. // +required - Prefix int `json:"prefix"` + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=128 + Prefix *int32 `json:"prefix,omitempty"` // gateway is the network gateway of the network the address is from. // +optional @@ -48,6 +49,44 @@ type IPAddressSpec struct { Gateway string `json:"gateway,omitempty"` } +// IPAddressClaimReference is a reference to an IPAddressClaim. +type IPAddressClaimReference struct { + // name of the IPAddressClaim. + // name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` +} + +// IPPoolReference is a reference to an IPPool. +type IPPoolReference struct { + // name of the IPPool. + // name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` + + // kind of the IPPool. + // kind must consist of alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-zA-Z]([-a-zA-Z0-9]*[a-zA-Z0-9])?$` + Kind string `json:"kind,omitempty"` + + // apiGroup of the IPPool. + // apiGroup must be fully qualified domain name. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + APIGroup string `json:"apiGroup,omitempty"` +} + // +kubebuilder:object:root=true // +kubebuilder:resource:path=ipaddresses,scope=Namespaced,categories=cluster-api // +kubebuilder:storageversion @@ -65,8 +104,8 @@ type IPAddress struct { metav1.ObjectMeta `json:"metadata,omitempty"` // spec is the desired state of IPAddress. - // +optional - Spec IPAddressSpec `json:"spec,omitempty"` + // +required + Spec IPAddressSpec `json:"spec,omitempty,omitzero"` } // +kubebuilder:object:root=true diff --git a/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/ipaddressclaim_types.go b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/ipaddressclaim_types.go new file mode 100644 index 000000000000..c702770b07a0 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/ipaddressclaim_types.go @@ -0,0 +1,174 @@ +/* +Copyright 2025 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" +) + +// IPAddressClaim's Ready condition and corresponding reasons. +const ( + // IPAddressClaimReadyCondition is true if the IPAddressClaim allocation succeeded. + IPAddressClaimReadyCondition = clusterv1.ReadyCondition + + // IPAddressClaimReadyAllocationFailedReason is the reason used when allocating an IP address for a claim fails. + // More details should be provided in the condition's message. + // When the IP pool is full, [PoolExhaustedReason] should be used for better visibility instead. + IPAddressClaimReadyAllocationFailedReason = "AllocationFailed" + + // IPAddressClaimReadyPoolNotReadyReason is the reason used when the referenced IP pool is not ready. + IPAddressClaimReadyPoolNotReadyReason = "PoolNotReady" + + // IPAddressClaimReadyPoolExhaustedReason is the reason used when an IP pool referenced by an [IPAddressClaim] is full and no address + // can be allocated for the claim. + IPAddressClaimReadyPoolExhaustedReason = "PoolExhausted" +) + +// IPAddressClaimSpec is the desired state of an IPAddressClaim. +type IPAddressClaimSpec struct { + // clusterName is the name of the Cluster this object belongs to. + // +optional + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=63 + ClusterName string `json:"clusterName,omitempty"` + + // poolRef is a reference to the pool from which an IP address should be created. + // +required + PoolRef IPPoolReference `json:"poolRef,omitempty,omitzero"` +} + +// IPAddressClaimStatus is the observed status of a IPAddressClaim. +// +kubebuilder:validation:MinProperties=1 +type IPAddressClaimStatus struct { + // conditions represents the observations of a IPAddressClaim's current state. + // Known condition types are Ready. + // +optional + // +listType=map + // +listMapKey=type + // +kubebuilder:validation:MaxItems=32 + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // addressRef is a reference to the address that was created for this claim. + // +optional + AddressRef IPAddressReference `json:"addressRef,omitempty,omitzero"` + + // deprecated groups all the status fields that are deprecated and will be removed when all the nested field are removed. + // +optional + Deprecated *IPAddressClaimDeprecatedStatus `json:"deprecated,omitempty"` +} + +// IPAddressReference is a reference to an IPAddress. +type IPAddressReference struct { + // name of the IPAddress. + // name must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character. + // +required + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + Name string `json:"name,omitempty"` +} + +// IPAddressClaimDeprecatedStatus groups all the status fields that are deprecated and will be removed in a future version. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type IPAddressClaimDeprecatedStatus struct { + // v1beta1 groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. + // +optional + V1Beta1 *IPAddressClaimV1Beta1DeprecatedStatus `json:"v1beta1,omitempty"` +} + +// IPAddressClaimV1Beta1DeprecatedStatus groups all the status fields that are deprecated and will be removed when support for v1beta1 will be dropped. +// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. +type IPAddressClaimV1Beta1DeprecatedStatus struct { + // conditions summarises the current state of the IPAddressClaim + // + // Deprecated: This field is deprecated and is going to be removed when support for v1beta1 will be dropped. Please see https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. + // + // +optional + Conditions clusterv1.Conditions `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:resource:path=ipaddressclaims,scope=Namespaced,categories=cluster-api +// +kubebuilder:subresource:status +// +kubebuilder:storageversion +// +kubebuilder:printcolumn:name="Pool Name",type="string",JSONPath=".spec.poolRef.name",description="Name of the pool to allocate an address from" +// +kubebuilder:printcolumn:name="Pool Kind",type="string",JSONPath=".spec.poolRef.kind",description="Kind of the pool to allocate an address from" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of IPAdressClaim" + +// IPAddressClaim is the Schema for the ipaddressclaim API. +type IPAddressClaim struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec is the desired state of IPAddressClaim. + // +required + Spec IPAddressClaimSpec `json:"spec,omitempty,omitzero"` + // status is the observed state of IPAddressClaim. + // +optional + Status IPAddressClaimStatus `json:"status,omitempty,omitzero"` +} + +// GetV1Beta1Conditions returns the set of conditions for this object. +func (m *IPAddressClaim) GetV1Beta1Conditions() clusterv1.Conditions { + if m.Status.Deprecated == nil || m.Status.Deprecated.V1Beta1 == nil { + return nil + } + return m.Status.Deprecated.V1Beta1.Conditions +} + +// SetV1Beta1Conditions sets the conditions on this object. +func (m *IPAddressClaim) SetV1Beta1Conditions(conditions clusterv1.Conditions) { + if m.Status.Deprecated == nil { + m.Status.Deprecated = &IPAddressClaimDeprecatedStatus{} + } + if m.Status.Deprecated.V1Beta1 == nil { + m.Status.Deprecated.V1Beta1 = &IPAddressClaimV1Beta1DeprecatedStatus{} + } + m.Status.Deprecated.V1Beta1.Conditions = conditions +} + +// GetConditions returns the set of conditions for this object. +func (m *IPAddressClaim) GetConditions() []metav1.Condition { + return m.Status.Conditions +} + +// SetConditions sets conditions for an API object. +func (m *IPAddressClaim) SetConditions(conditions []metav1.Condition) { + m.Status.Conditions = conditions +} + +// +kubebuilder:object:root=true + +// IPAddressClaimList is a list of IPAddressClaims. +type IPAddressClaimList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list's metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + // items is the list of IPAddressClaims. + Items []IPAddressClaim `json:"items"` +} + +func init() { + objectTypes = append(objectTypes, &IPAddressClaim{}, &IPAddressClaimList{}) +} diff --git a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/condition_consts.go b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/v1beta1_condition_consts.go similarity index 60% rename from vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/condition_consts.go rename to vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/v1beta1_condition_consts.go index db0c507aea3a..d915330a31ef 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/condition_consts.go +++ b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/v1beta1_condition_consts.go @@ -1,5 +1,5 @@ /* -Copyright 2024 The Kubernetes Authors. +Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,19 +14,19 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta1 +package v1beta2 // These reasons are intended to be used with failed Ready conditions on an [IPAddressClaim]. const ( - // AllocationFailedReason is the reason used when allocating an IP address for a claim fails. More details should be + // AllocationFailedV1Beta1Reason is the reason used when allocating an IP address for a claim fails. More details should be // provided in the condition's message. // When the IP pool is full, [PoolExhaustedReason] should be used for better visibility instead. - AllocationFailedReason = "AllocationFailed" + AllocationFailedV1Beta1Reason = "AllocationFailed" - // PoolNotReadyReason is the reason used when the referenced IP pool is not ready. - PoolNotReadyReason = "PoolNotReady" + // PoolNotReadyV1Beta1Reason is the reason used when the referenced IP pool is not ready. + PoolNotReadyV1Beta1Reason = "PoolNotReady" - // PoolExhaustedReason is the reason used when an IP pool referenced by an [IPAddressClaim] is full and no address + // PoolExhaustedV1Beta1Reason is the reason used when an IP pool referenced by an [IPAddressClaim] is full and no address // can be allocated for the claim. - PoolExhaustedReason = "PoolExhausted" + PoolExhaustedV1Beta1Reason = "PoolExhausted" ) diff --git a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/zz_generated.deepcopy.go similarity index 68% rename from vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/zz_generated.deepcopy.go rename to vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/zz_generated.deepcopy.go index 338a238c266a..721f13a61b37 100644 --- a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/zz_generated.deepcopy.go +++ b/vendor/sigs.k8s.io/cluster-api/api/ipam/v1beta2/zz_generated.deepcopy.go @@ -18,12 +18,12 @@ limitations under the License. // Code generated by controller-gen. DO NOT EDIT. -package v1beta1 +package v1beta2 import ( "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" + corev1beta2 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -57,7 +57,7 @@ func (in *IPAddressClaim) DeepCopyInto(out *IPAddressClaim) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) + out.Spec = in.Spec in.Status.DeepCopyInto(&out.Status) } @@ -79,6 +79,26 @@ func (in *IPAddressClaim) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IPAddressClaimDeprecatedStatus) DeepCopyInto(out *IPAddressClaimDeprecatedStatus) { + *out = *in + if in.V1Beta1 != nil { + in, out := &in.V1Beta1, &out.V1Beta1 + *out = new(IPAddressClaimV1Beta1DeprecatedStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressClaimDeprecatedStatus. +func (in *IPAddressClaimDeprecatedStatus) DeepCopy() *IPAddressClaimDeprecatedStatus { + if in == nil { + return nil + } + out := new(IPAddressClaimDeprecatedStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPAddressClaimList) DeepCopyInto(out *IPAddressClaimList) { *out = *in @@ -111,10 +131,25 @@ func (in *IPAddressClaimList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IPAddressClaimReference) DeepCopyInto(out *IPAddressClaimReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressClaimReference. +func (in *IPAddressClaimReference) DeepCopy() *IPAddressClaimReference { + if in == nil { + return nil + } + out := new(IPAddressClaimReference) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPAddressClaimSpec) DeepCopyInto(out *IPAddressClaimSpec) { *out = *in - in.PoolRef.DeepCopyInto(&out.PoolRef) + out.PoolRef = in.PoolRef } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressClaimSpec. @@ -130,17 +165,17 @@ func (in *IPAddressClaimSpec) DeepCopy() *IPAddressClaimSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPAddressClaimStatus) DeepCopyInto(out *IPAddressClaimStatus) { *out = *in - out.AddressRef = in.AddressRef if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) + *out = make([]v1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } - if in.V1Beta2 != nil { - in, out := &in.V1Beta2, &out.V1Beta2 - *out = new(IPAddressClaimV1Beta2Status) + out.AddressRef = in.AddressRef + if in.Deprecated != nil { + in, out := &in.Deprecated, &out.Deprecated + *out = new(IPAddressClaimDeprecatedStatus) (*in).DeepCopyInto(*out) } } @@ -156,23 +191,23 @@ func (in *IPAddressClaimStatus) DeepCopy() *IPAddressClaimStatus { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *IPAddressClaimV1Beta2Status) DeepCopyInto(out *IPAddressClaimV1Beta2Status) { +func (in *IPAddressClaimV1Beta1DeprecatedStatus) DeepCopyInto(out *IPAddressClaimV1Beta1DeprecatedStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]v1.Condition, len(*in)) + *out = make(corev1beta2.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressClaimV1Beta2Status. -func (in *IPAddressClaimV1Beta2Status) DeepCopy() *IPAddressClaimV1Beta2Status { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressClaimV1Beta1DeprecatedStatus. +func (in *IPAddressClaimV1Beta1DeprecatedStatus) DeepCopy() *IPAddressClaimV1Beta1DeprecatedStatus { if in == nil { return nil } - out := new(IPAddressClaimV1Beta2Status) + out := new(IPAddressClaimV1Beta1DeprecatedStatus) in.DeepCopyInto(out) return out } @@ -209,11 +244,31 @@ func (in *IPAddressList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IPAddressReference) DeepCopyInto(out *IPAddressReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressReference. +func (in *IPAddressReference) DeepCopy() *IPAddressReference { + if in == nil { + return nil + } + out := new(IPAddressReference) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPAddressSpec) DeepCopyInto(out *IPAddressSpec) { *out = *in out.ClaimRef = in.ClaimRef - in.PoolRef.DeepCopyInto(&out.PoolRef) + out.PoolRef = in.PoolRef + if in.Prefix != nil { + in, out := &in.Prefix, &out.Prefix + *out = new(int32) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAddressSpec. @@ -225,3 +280,18 @@ func (in *IPAddressSpec) DeepCopy() *IPAddressSpec { in.DeepCopyInto(out) return out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IPPoolReference) DeepCopyInto(out *IPPoolReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPPoolReference. +func (in *IPPoolReference) DeepCopy() *IPPoolReference { + if in == nil { + return nil + } + out := new(IPPoolReference) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/.import-restrictions b/vendor/sigs.k8s.io/cluster-api/api/v1beta1/.import-restrictions deleted file mode 100644 index a2e1dfd08133..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/.import-restrictions +++ /dev/null @@ -1,5 +0,0 @@ -rules: - - selectorRegexp: sigs[.]k8s[.]io/controller-runtime - allowedPrefixes: [] - forbiddenPrefixes: - - "sigs.k8s.io/controller-runtime" diff --git a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/conversion.go b/vendor/sigs.k8s.io/cluster-api/api/v1beta1/conversion.go deleted file mode 100644 index cbbc3b35d7b5..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/api/v1beta1/conversion.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -func (*Cluster) Hub() {} -func (*ClusterList) Hub() {} -func (*ClusterClass) Hub() {} -func (*ClusterClassList) Hub() {} -func (*Machine) Hub() {} -func (*MachineList) Hub() {} -func (*MachineSet) Hub() {} -func (*MachineSetList) Hub() {} -func (*MachineDeployment) Hub() {} -func (*MachineDeploymentList) Hub() {} -func (*MachineHealthCheck) Hub() {} -func (*MachineHealthCheckList) Hub() {} diff --git a/vendor/sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3/metadata_type.go b/vendor/sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3/metadata_type.go index fbe715e636c1..e7b6cf199f1f 100644 --- a/vendor/sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3/metadata_type.go +++ b/vendor/sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3/metadata_type.go @@ -32,12 +32,12 @@ type Metadata struct { // +optional metav1.ObjectMeta `json:"metadata,omitempty"` - // releaseSeries maps a provider release series (major/minor) with an API Version of Cluster API (contract). + // releaseSeries maps a provider release series (major/minor) with a Cluster API contract version. // +optional ReleaseSeries []ReleaseSeries `json:"releaseSeries"` } -// ReleaseSeries maps a provider release series (major/minor) with a API Version of Cluster API (contract). +// ReleaseSeries maps a provider release series (major/minor) with a Cluster API contract version. type ReleaseSeries struct { // major version of the release series // +optional diff --git a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/.import-restrictions b/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/.import-restrictions deleted file mode 100644 index a2e1dfd08133..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/.import-restrictions +++ /dev/null @@ -1,5 +0,0 @@ -rules: - - selectorRegexp: sigs[.]k8s[.]io/controller-runtime - allowedPrefixes: [] - forbiddenPrefixes: - - "sigs.k8s.io/controller-runtime" diff --git a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/condition_consts.go b/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/condition_consts.go deleted file mode 100644 index 18e29600ab5d..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/condition_consts.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" - -// Conditions and condition Reasons for the MachinePool object. - -const ( - // ReplicasReadyCondition reports an aggregate of current status of the replicas controlled by the MachinePool. - ReplicasReadyCondition clusterv1.ConditionType = "ReplicasReady" - - // WaitingForReplicasReadyReason (Severity=Info) documents a machinepool waiting for the required replicas - // to be ready. - WaitingForReplicasReadyReason = "WaitingForReplicasReady" -) diff --git a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/v1beta2_condition_consts.go b/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/v1beta2_condition_consts.go deleted file mode 100644 index afd7301f5288..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/v1beta2_condition_consts.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -/* -NOTE: we are commenting const for MachinePool's V1Beta2 conditions and reasons because not yet implemented for the 1.9 CAPI release. -However, we are keeping the v1beta2 struct in the MachinePool struct because the code that will collect conditions and replica -counters at cluster level is already implemented. - -// Conditions that will be used for the MachinePool object in v1Beta2 API version. -const ( - // MachinePoolAvailableV1Beta2Condition is true when InfrastructureReady and available replicas >= desired replicas. - MachinePoolAvailableV1Beta2Condition = clusterv1.AvailableV1Beta2Condition - - // MachinePoolBootstrapConfigReadyV1Beta2Condition mirrors the corresponding condition from the MachinePool's BootstrapConfig resource. - MachinePoolBootstrapConfigReadyV1Beta2Condition = clusterv1.BootstrapConfigReadyV1Beta2Condition - - // MachinePoolInfrastructureReadyV1Beta2Condition mirrors the corresponding condition from the MachinePool's Infrastructure resource. - MachinePoolInfrastructureReadyV1Beta2Condition = clusterv1.InfrastructureReadyV1Beta2Condition - - // MachinePoolMachinesReadyV1Beta2Condition surfaces detail of issues on the controlled machines, if any. - MachinePoolMachinesReadyV1Beta2Condition = clusterv1.MachinesReadyV1Beta2Condition - - // MachinePoolMachinesUpToDateV1Beta2Condition surfaces details of controlled machines not up to date, if any. - MachinePoolMachinesUpToDateV1Beta2Condition = clusterv1.MachinesUpToDateV1Beta2Condition - - // MachinePoolScalingUpV1Beta2Condition is true if available replicas < desired replicas. - MachinePoolScalingUpV1Beta2Condition = clusterv1.ScalingUpV1Beta2Condition - - // MachinePoolScalingDownV1Beta2Condition is true if replicas > desired replicas. - MachinePoolScalingDownV1Beta2Condition = clusterv1.ScalingDownV1Beta2Condition - - // MachinePoolRemediatingV1Beta2Condition surfaces details about ongoing remediation of the controlled machines, if any. - MachinePoolRemediatingV1Beta2Condition = clusterv1.RemediatingV1Beta2Condition - - // MachinePoolDeletingV1Beta2Condition surfaces details about ongoing deletion of the controlled machines. - MachinePoolDeletingV1Beta2Condition = clusterv1.DeletingV1Beta2Condition -). -*/ diff --git a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/zz_generated.deepcopy.go b/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/zz_generated.deepcopy.go deleted file mode 100644 index 06bd6b0e9a9b..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/exp/api/v1beta1/zz_generated.deepcopy.go +++ /dev/null @@ -1,203 +0,0 @@ -//go:build !ignore_autogenerated - -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by controller-gen. DO NOT EDIT. - -package v1beta1 - -import ( - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - apiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1" - "sigs.k8s.io/cluster-api/errors" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *MachinePool) DeepCopyInto(out *MachinePool) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePool. -func (in *MachinePool) DeepCopy() *MachinePool { - if in == nil { - return nil - } - out := new(MachinePool) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *MachinePool) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *MachinePoolList) DeepCopyInto(out *MachinePoolList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]MachinePool, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolList. -func (in *MachinePoolList) DeepCopy() *MachinePoolList { - if in == nil { - return nil - } - out := new(MachinePoolList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *MachinePoolList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *MachinePoolSpec) DeepCopyInto(out *MachinePoolSpec) { - *out = *in - if in.Replicas != nil { - in, out := &in.Replicas, &out.Replicas - *out = new(int32) - **out = **in - } - in.Template.DeepCopyInto(&out.Template) - if in.MinReadySeconds != nil { - in, out := &in.MinReadySeconds, &out.MinReadySeconds - *out = new(int32) - **out = **in - } - if in.ProviderIDList != nil { - in, out := &in.ProviderIDList, &out.ProviderIDList - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.FailureDomains != nil { - in, out := &in.FailureDomains, &out.FailureDomains - *out = make([]string, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolSpec. -func (in *MachinePoolSpec) DeepCopy() *MachinePoolSpec { - if in == nil { - return nil - } - out := new(MachinePoolSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *MachinePoolStatus) DeepCopyInto(out *MachinePoolStatus) { - *out = *in - if in.NodeRefs != nil { - in, out := &in.NodeRefs, &out.NodeRefs - *out = make([]v1.ObjectReference, len(*in)) - copy(*out, *in) - } - if in.FailureReason != nil { - in, out := &in.FailureReason, &out.FailureReason - *out = new(errors.MachinePoolStatusFailure) - **out = **in - } - if in.FailureMessage != nil { - in, out := &in.FailureMessage, &out.FailureMessage - *out = new(string) - **out = **in - } - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(apiv1beta1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.V1Beta2 != nil { - in, out := &in.V1Beta2, &out.V1Beta2 - *out = new(MachinePoolV1Beta2Status) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolStatus. -func (in *MachinePoolStatus) DeepCopy() *MachinePoolStatus { - if in == nil { - return nil - } - out := new(MachinePoolStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *MachinePoolV1Beta2Status) DeepCopyInto(out *MachinePoolV1Beta2Status) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]metav1.Condition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.ReadyReplicas != nil { - in, out := &in.ReadyReplicas, &out.ReadyReplicas - *out = new(int32) - **out = **in - } - if in.AvailableReplicas != nil { - in, out := &in.AvailableReplicas, &out.AvailableReplicas - *out = new(int32) - **out = **in - } - if in.UpToDateReplicas != nil { - in, out := &in.UpToDateReplicas, &out.UpToDateReplicas - *out = new(int32) - **out = **in - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachinePoolV1Beta2Status. -func (in *MachinePoolV1Beta2Status) DeepCopy() *MachinePoolV1Beta2Status { - if in == nil { - return nil - } - out := new(MachinePoolV1Beta2Status) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/.import-restrictions b/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/.import-restrictions deleted file mode 100644 index a2e1dfd08133..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/.import-restrictions +++ /dev/null @@ -1,5 +0,0 @@ -rules: - - selectorRegexp: sigs[.]k8s[.]io/controller-runtime - allowedPrefixes: [] - forbiddenPrefixes: - - "sigs.k8s.io/controller-runtime" diff --git a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/conversion.go b/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/conversion.go deleted file mode 100644 index 64f6e9d8d84b..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/conversion.go +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -func (*IPAddress) Hub() {} -func (*IPAddressList) Hub() {} -func (*IPAddressClaim) Hub() {} -func (*IPAddressClaimList) Hub() {} diff --git a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/ipaddressclaim_types.go b/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/ipaddressclaim_types.go deleted file mode 100644 index 635df232c674..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/exp/ipam/api/v1beta1/ipaddressclaim_types.go +++ /dev/null @@ -1,130 +0,0 @@ -/* -Copyright 2022 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import ( - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" -) - -// IPAddressClaimSpec is the desired state of an IPAddressClaim. -type IPAddressClaimSpec struct { - // clusterName is the name of the Cluster this object belongs to. - // +optional - // +kubebuilder:validation:MinLength=1 - // +kubebuilder:validation:MaxLength=63 - ClusterName string `json:"clusterName,omitempty"` - - // poolRef is a reference to the pool from which an IP address should be created. - // +required - PoolRef corev1.TypedLocalObjectReference `json:"poolRef"` -} - -// IPAddressClaimStatus is the observed status of a IPAddressClaim. -type IPAddressClaimStatus struct { - // addressRef is a reference to the address that was created for this claim. - // +optional - AddressRef corev1.LocalObjectReference `json:"addressRef,omitempty"` - - // conditions summarises the current state of the IPAddressClaim - // +optional - Conditions clusterv1.Conditions `json:"conditions,omitempty"` - - // v1beta2 groups all the fields that will be added or modified in IPAddressClaim's status with the V1Beta2 version. - // +optional - V1Beta2 *IPAddressClaimV1Beta2Status `json:"v1beta2,omitempty"` -} - -// IPAddressClaimV1Beta2Status groups all the fields that will be added or modified in IPAddressClaimStatus with the V1Beta2 version. -// See https://github.com/kubernetes-sigs/cluster-api/blob/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more context. -type IPAddressClaimV1Beta2Status struct { - // conditions represents the observations of a IPAddressClaim's current state. - // +optional - // +listType=map - // +listMapKey=type - // +kubebuilder:validation:MaxItems=32 - Conditions []metav1.Condition `json:"conditions,omitempty"` -} - -// +kubebuilder:object:root=true -// +kubebuilder:resource:path=ipaddressclaims,scope=Namespaced,categories=cluster-api -// +kubebuilder:subresource:status -// +kubebuilder:storageversion -// +kubebuilder:printcolumn:name="Pool Name",type="string",JSONPath=".spec.poolRef.name",description="Name of the pool to allocate an address from" -// +kubebuilder:printcolumn:name="Pool Kind",type="string",JSONPath=".spec.poolRef.kind",description="Kind of the pool to allocate an address from" -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of IPAdressClaim" - -// IPAddressClaim is the Schema for the ipaddressclaim API. -type IPAddressClaim struct { - metav1.TypeMeta `json:",inline"` - // metadata is the standard object's metadata. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // spec is the desired state of IPAddressClaim. - // +optional - Spec IPAddressClaimSpec `json:"spec,omitempty"` - // status is the observed state of IPAddressClaim. - // +optional - Status IPAddressClaimStatus `json:"status,omitempty"` -} - -// GetConditions returns the set of conditions for this object. -func (m *IPAddressClaim) GetConditions() clusterv1.Conditions { - return m.Status.Conditions -} - -// SetConditions sets the conditions on this object. -func (m *IPAddressClaim) SetConditions(conditions clusterv1.Conditions) { - m.Status.Conditions = conditions -} - -// GetV1Beta2Conditions returns the set of conditions for this object. -func (m *IPAddressClaim) GetV1Beta2Conditions() []metav1.Condition { - if m.Status.V1Beta2 == nil { - return nil - } - return m.Status.V1Beta2.Conditions -} - -// SetV1Beta2Conditions sets conditions for an API object. -func (m *IPAddressClaim) SetV1Beta2Conditions(conditions []metav1.Condition) { - if m.Status.V1Beta2 == nil { - m.Status.V1Beta2 = &IPAddressClaimV1Beta2Status{} - } - m.Status.V1Beta2.Conditions = conditions -} - -// +kubebuilder:object:root=true - -// IPAddressClaimList is a list of IPAddressClaims. -type IPAddressClaimList struct { - metav1.TypeMeta `json:",inline"` - // metadata is the standard list's metadata. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#lists-and-simple-kinds - // +optional - metav1.ListMeta `json:"metadata,omitempty"` - // items is the list of IPAddressClaims. - Items []IPAddressClaim `json:"items"` -} - -func init() { - objectTypes = append(objectTypes, &IPAddressClaim{}, &IPAddressClaimList{}) -} diff --git a/vendor/sigs.k8s.io/cluster-api/util/annotations/helpers.go b/vendor/sigs.k8s.io/cluster-api/util/annotations/helpers.go index 964609ac97a5..c378fa29872b 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/annotations/helpers.go +++ b/vendor/sigs.k8s.io/cluster-api/util/annotations/helpers.go @@ -22,13 +22,14 @@ import ( "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) // IsPaused returns true if the Cluster is paused or the object has the `paused` annotation. func IsPaused(cluster *clusterv1.Cluster, o metav1.Object) bool { - if cluster.Spec.Paused { + if ptr.Deref(cluster.Spec.Paused, false) { return true } return HasPaused(o) diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/aggregate.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/aggregate.go similarity index 99% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/aggregate.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/aggregate.go index 892fd9a9ce38..9b9b7e7c186a 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/aggregate.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/aggregate.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta2 +package conditions import ( "fmt" diff --git a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/doc.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/doc.go similarity index 85% rename from vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/doc.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/doc.go index d55ab5609a7b..6830163ce72a 100644 --- a/vendor/sigs.k8s.io/cluster-api/api/addons/v1beta1/doc.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2021 The Kubernetes Authors. +Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,4 +14,5 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package v1beta1 implements condition utilities. package v1beta1 diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/getter.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/getter.go new file mode 100644 index 000000000000..9d945d4dfacc --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/getter.go @@ -0,0 +1,273 @@ +/* +Copyright 2020 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" +) + +// Getter interface defines methods that a Cluster API object should implement in order to +// use the conditions package for getting conditions. +type Getter interface { + client.Object + + // GetConditions returns the list of conditions for a cluster API object. + GetV1Beta1Conditions() clusterv1.Conditions +} + +// Get returns the condition with the given type, if the condition does not exist, +// it returns nil. +func Get(from Getter, t clusterv1.ConditionType) *clusterv1.Condition { + conditions := from.GetV1Beta1Conditions() + if conditions == nil { + return nil + } + + for _, condition := range conditions { + if condition.Type == t { + return &condition + } + } + return nil +} + +// Has returns true if a condition with the given type exists. +func Has(from Getter, t clusterv1.ConditionType) bool { + return Get(from, t) != nil +} + +// IsTrue is true if the condition with the given type is True, otherwise it returns false +// if the condition is not True or if the condition does not exist (is nil). +func IsTrue(from Getter, t clusterv1.ConditionType) bool { + if c := Get(from, t); c != nil { + return c.Status == corev1.ConditionTrue + } + return false +} + +// IsFalse is true if the condition with the given type is False, otherwise it returns false +// if the condition is not False or if the condition does not exist (is nil). +func IsFalse(from Getter, t clusterv1.ConditionType) bool { + if c := Get(from, t); c != nil { + return c.Status == corev1.ConditionFalse + } + return false +} + +// IsUnknown is true if the condition with the given type is Unknown or if the condition +// does not exist (is nil). +func IsUnknown(from Getter, t clusterv1.ConditionType) bool { + if c := Get(from, t); c != nil { + return c.Status == corev1.ConditionUnknown + } + return true +} + +// GetReason returns a nil safe string of Reason for the condition with the given type. +func GetReason(from Getter, t clusterv1.ConditionType) string { + if c := Get(from, t); c != nil { + return c.Reason + } + return "" +} + +// GetMessage returns a nil safe string of Message. +func GetMessage(from Getter, t clusterv1.ConditionType) string { + if c := Get(from, t); c != nil { + return c.Message + } + return "" +} + +// GetSeverity returns the condition Severity or nil if the condition +// does not exist (is nil). +func GetSeverity(from Getter, t clusterv1.ConditionType) *clusterv1.ConditionSeverity { + if c := Get(from, t); c != nil { + return &c.Severity + } + return nil +} + +// GetLastTransitionTime returns the condition Severity or nil if the condition +// does not exist (is nil). +func GetLastTransitionTime(from Getter, t clusterv1.ConditionType) *metav1.Time { + if c := Get(from, t); c != nil { + return &c.LastTransitionTime + } + return nil +} + +// summary returns a Ready condition with the summary of all the conditions existing +// on an object. If the object does not have other conditions, no summary condition is generated. +// NOTE: The resulting Ready condition will have positive polarity; the conditions we are starting from might have positive or negative polarity. +func summary(from Getter, options ...MergeOption) *clusterv1.Condition { + conditions := from.GetV1Beta1Conditions() + + mergeOpt := &mergeOptions{} + for _, o := range options { + o(mergeOpt) + } + + // Identifies the conditions in scope for the Summary by taking all the existing conditions except Ready, + // or, if a list of conditions types is specified, only the conditions the condition in that list. + conditionsInScope := make([]localizedCondition, 0, len(conditions)) + for i := range conditions { + c := conditions[i] + if c.Type == clusterv1.ReadyV1Beta1Condition { + continue + } + + if mergeOpt.conditionTypes != nil { + found := false + for _, t := range mergeOpt.conditionTypes { + if c.Type == t { + found = true + break + } + } + if !found { + continue + } + } + + // Keep track of the polarity of the condition we are starting from. + polarity := PositivePolarity + for _, t := range mergeOpt.negativeConditionTypes { + if c.Type == t { + polarity = NegativePolarity + break + } + } + + conditionsInScope = append(conditionsInScope, localizedCondition{ + Condition: &c, + Polarity: polarity, + Getter: from, + }) + } + + // If it is required to add a step counter only if a subset of condition exists, check if the conditions + // in scope are included in this subset or not. + if mergeOpt.addStepCounterIfOnlyConditionTypes != nil { + for _, c := range conditionsInScope { + found := false + for _, t := range mergeOpt.addStepCounterIfOnlyConditionTypes { + if c.Type == t { + found = true + break + } + } + if !found { + mergeOpt.addStepCounter = false + break + } + } + } + + // If it is required to add a step counter, determine the total number of conditions defaulting + // to the selected conditions or, if defined, to the total number of conditions type to be considered. + if mergeOpt.addStepCounter { + mergeOpt.stepCounter = len(conditionsInScope) + if mergeOpt.conditionTypes != nil { + mergeOpt.stepCounter = len(mergeOpt.conditionTypes) + } + if mergeOpt.addStepCounterIfOnlyConditionTypes != nil { + mergeOpt.stepCounter = len(mergeOpt.addStepCounterIfOnlyConditionTypes) + } + } + + return merge(conditionsInScope, clusterv1.ReadyV1Beta1Condition, mergeOpt) +} + +// mirrorOptions allows to set options for the mirror operation. +type mirrorOptions struct { + fallbackTo *bool + fallbackReason string + fallbackSeverity clusterv1.ConditionSeverity + fallbackMessage string +} + +// MirrorOptions defines an option for mirroring conditions. +type MirrorOptions func(*mirrorOptions) + +// WithFallbackValue specify a fallback value to use in case the mirrored condition does not exist; +// in case the fallbackValue is false, given values for reason, severity and message will be used. +func WithFallbackValue(fallbackValue bool, reason string, severity clusterv1.ConditionSeverity, message string) MirrorOptions { + return func(c *mirrorOptions) { + c.fallbackTo = &fallbackValue + c.fallbackReason = reason + c.fallbackSeverity = severity + c.fallbackMessage = message + } +} + +// mirror mirrors the Ready condition from a dependent object into the target condition; +// if the Ready condition does not exist in the source object, no target conditions is generated. +// NOTE: Considering that we are mirroring Ready conditions with positive polarity, also the resulting condition will have positive polarity. +func mirror(from Getter, targetCondition clusterv1.ConditionType, options ...MirrorOptions) *clusterv1.Condition { + mirrorOpt := &mirrorOptions{} + for _, o := range options { + o(mirrorOpt) + } + + condition := Get(from, clusterv1.ReadyV1Beta1Condition) + + if mirrorOpt.fallbackTo != nil && condition == nil { + switch *mirrorOpt.fallbackTo { + case true: + condition = TrueCondition(targetCondition) + case false: + condition = FalseCondition(targetCondition, mirrorOpt.fallbackReason, mirrorOpt.fallbackSeverity, "%s", mirrorOpt.fallbackMessage) + } + } + + if condition != nil { + condition.Type = targetCondition + } + + return condition +} + +// Aggregates all the Ready condition from a list of dependent objects into the target object; +// if the Ready condition does not exist in one of the source object, the object is excluded from +// the aggregation; if none of the source object have ready condition, no target conditions is generated. +// NOTE: Considering that we are aggregating Ready conditions with positive polarity, also the resulting condition will have positive polarity. +func aggregate(from []Getter, targetCondition clusterv1.ConditionType, options ...MergeOption) *clusterv1.Condition { + conditionsInScope := make([]localizedCondition, 0, len(from)) + for i := range from { + condition := Get(from[i], clusterv1.ReadyV1Beta1Condition) + + conditionsInScope = append(conditionsInScope, localizedCondition{ + Condition: condition, + Polarity: PositivePolarity, + Getter: from[i], + }) + } + + mergeOpt := &mergeOptions{ + addStepCounter: true, + stepCounter: len(from), + } + for _, o := range options { + o(mergeOpt) + } + return merge(conditionsInScope, targetCondition, mergeOpt) +} diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/matcher.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/matcher.go similarity index 54% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/matcher.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/matcher.go index d842b2136e19..d92e06736f50 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/matcher.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/matcher.go @@ -1,5 +1,5 @@ /* -Copyright 2024 The Kubernetes Authors. +Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,61 +14,32 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta2 +package v1beta1 import ( "fmt" "github.com/onsi/gomega" "github.com/onsi/gomega/types" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// IgnoreLastTransitionTime instructs MatchConditions and MatchCondition to ignore the LastTransitionTime field. -type IgnoreLastTransitionTime bool - -// ApplyMatch applies this configuration to the given Match options. -func (f IgnoreLastTransitionTime) ApplyMatch(opts *MatchOptions) { - opts.ignoreLastTransitionTime = bool(f) -} - -// MatchOption is some configuration that modifies options for a match call. -type MatchOption interface { - // ApplyMatch applies this configuration to the given match options. - ApplyMatch(option *MatchOptions) -} - -// MatchOptions allows to set options for the match operation. -type MatchOptions struct { - ignoreLastTransitionTime bool -} -// ApplyOptions applies the given list options on these options, -// and then returns itself (for convenient chaining). -func (o *MatchOptions) ApplyOptions(opts []MatchOption) *MatchOptions { - for _, opt := range opts { - opt.ApplyMatch(o) - } - return o -} + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" +) -// MatchConditions returns a custom matcher to check equality of []metav1.Condition. -func MatchConditions(expected []metav1.Condition, opts ...MatchOption) types.GomegaMatcher { +// MatchConditions returns a custom matcher to check equality of clusterv1.Conditions. +func MatchConditions(expected clusterv1.Conditions) types.GomegaMatcher { return &matchConditions{ - opts: opts, expected: expected, } } type matchConditions struct { - opts []MatchOption - expected []metav1.Condition + expected clusterv1.Conditions } func (m matchConditions) Match(actual interface{}) (success bool, err error) { elems := []interface{}{} for _, condition := range m.expected { - elems = append(elems, MatchCondition(condition, m.opts...)) + elems = append(elems, MatchCondition(condition)) } return gomega.ConsistOf(elems...).Match(actual) @@ -82,28 +53,21 @@ func (m matchConditions) NegatedFailureMessage(actual interface{}) (message stri return fmt.Sprintf("expected\n\t%#v\nto not match\n\t%#v\n", actual, m.expected) } -// MatchCondition returns a custom matcher to check equality of metav1.Condition. -func MatchCondition(expected metav1.Condition, opts ...MatchOption) types.GomegaMatcher { +// MatchCondition returns a custom matcher to check equality of clusterv1.Condition. +func MatchCondition(expected clusterv1.Condition) types.GomegaMatcher { return &matchCondition{ - opts: opts, expected: expected, } } type matchCondition struct { - opts []MatchOption - expected metav1.Condition + expected clusterv1.Condition } func (m matchCondition) Match(actual interface{}) (success bool, err error) { - matchOpt := &MatchOptions{ - ignoreLastTransitionTime: false, - } - matchOpt.ApplyOptions(m.opts) - - actualCondition, ok := actual.(metav1.Condition) + actualCondition, ok := actual.(clusterv1.Condition) if !ok { - return false, fmt.Errorf("actual should be of type metav1.Condition") + return false, fmt.Errorf("actual should be of type Condition") } ok, err = gomega.Equal(m.expected.Type).Match(actualCondition.Type) @@ -114,7 +78,7 @@ func (m matchCondition) Match(actual interface{}) (success bool, err error) { if !ok { return ok, err } - ok, err = gomega.Equal(m.expected.ObservedGeneration).Match(actualCondition.ObservedGeneration) + ok, err = gomega.Equal(m.expected.Severity).Match(actualCondition.Severity) if !ok { return ok, err } @@ -127,13 +91,6 @@ func (m matchCondition) Match(actual interface{}) (success bool, err error) { return ok, err } - if !matchOpt.ignoreLastTransitionTime { - ok, err = gomega.BeTemporally("==", m.expected.LastTransitionTime.Time).Match(actualCondition.LastTransitionTime.Time) - if !ok { - return ok, err - } - } - return ok, err } diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/matchers.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/matchers.go similarity index 95% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/matchers.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/matchers.go index dfac4bb25614..3c3adb464743 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/matchers.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/matchers.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package conditions +package v1beta1 import ( "errors" @@ -22,7 +22,7 @@ import ( "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) // HaveSameStateOf matches a condition to have the same state of another. diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/merge.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/merge.go similarity index 97% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/merge.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/merge.go index 465606d710be..262c3672fc81 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/merge.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/merge.go @@ -14,14 +14,14 @@ See the License for the specific language governing permissions and limitations under the License. */ -package conditions +package v1beta1 import ( "sort" corev1 "k8s.io/api/core/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) type conditionPolarity string @@ -76,9 +76,9 @@ func merge(conditions []localizedCondition, targetCondition clusterv1.ConditionT targetReason := getReason(g, options) targetMessage := getMessage(g, options) if g.TopGroup().status == corev1.ConditionFalse { - return FalseCondition(targetCondition, targetReason, g.TopGroup().severity, targetMessage) + return FalseCondition(targetCondition, targetReason, g.TopGroup().severity, "%s", targetMessage) } - return UnknownCondition(targetCondition, targetReason, targetMessage) + return UnknownCondition(targetCondition, targetReason, "%s", targetMessage) } // getConditionGroups groups a list of conditions according to status, severity values. diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/merge_strategies.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/merge_strategies.go new file mode 100644 index 000000000000..ee9374d6bd02 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/merge_strategies.go @@ -0,0 +1,178 @@ +/* +Copyright 2020 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "fmt" + "strings" + + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" +) + +// mergeOptions allows to set strategies for merging a set of conditions into a single condition, +// and more specifically for computing the target Reason and the target Message. +type mergeOptions struct { + conditionTypes []clusterv1.ConditionType + negativeConditionTypes []clusterv1.ConditionType + addSourceRef bool + addStepCounter bool + addStepCounterIfOnlyConditionTypes []clusterv1.ConditionType + stepCounter int +} + +// MergeOption defines an option for computing a summary of conditions. +type MergeOption func(*mergeOptions) + +// WithConditions instructs merge about the condition types to consider when doing a merge operation; +// if this option is not specified, all the conditions (excepts Ready) will be considered. This is required, +// so we can provide some guarantees about the semantic of the target condition without worrying about +// side effects if someone or something adds custom conditions to the objects. +// +// NOTE: The order of conditions types defines the priority for determining the Reason and Message for the +// target condition. +// IMPORTANT: This options works only while generating the Summary condition. +func WithConditions(t ...clusterv1.ConditionType) MergeOption { + return func(c *mergeOptions) { + c.conditionTypes = t + } +} + +// WithNegativePolarityConditions instruct merge about which conditions should be considered having negative polarity. +// IMPORTANT: this must be a subset of WithConditions. +func WithNegativePolarityConditions(t ...clusterv1.ConditionType) MergeOption { + return func(c *mergeOptions) { + c.negativeConditionTypes = t + } +} + +// WithStepCounter instructs merge to add a "x of y completed" string to the message, +// where x is the number of conditions with Status=true and y is the number of conditions in scope. +func WithStepCounter() MergeOption { + return func(c *mergeOptions) { + c.addStepCounter = true + } +} + +// WithStepCounterIf adds a step counter if the value is true. +// This can be used e.g. to add a step counter only if the object is not being deleted. +// +// IMPORTANT: This options works only while generating the Summary condition. +func WithStepCounterIf(value bool) MergeOption { + return func(c *mergeOptions) { + c.addStepCounter = value + } +} + +// WithStepCounterIfOnly ensure a step counter is show only if a subset of condition exists. +// This applies for example on Machines, where we want to use +// the step counter notation while provisioning the machine, but then we want to move away from this notation +// as soon as the machine is provisioned and e.g. a Machine health check condition is generated +// +// IMPORTANT: This options requires WithStepCounter or WithStepCounterIf to be set. +// IMPORTANT: This options works only while generating the Summary condition. +func WithStepCounterIfOnly(t ...clusterv1.ConditionType) MergeOption { + return func(c *mergeOptions) { + c.addStepCounterIfOnlyConditionTypes = t + } +} + +// AddSourceRef instructs merge to add info about the originating object to the target Reason. +func AddSourceRef() MergeOption { + return func(c *mergeOptions) { + c.addSourceRef = true + } +} + +// getReason returns the reason to be applied to the condition resulting by merging a set of condition groups. +// The reason is computed according to the given mergeOptions. +func getReason(groups conditionGroups, options *mergeOptions) string { + return getFirstReason(groups, options.conditionTypes, options.addSourceRef) +} + +// getFirstReason returns the first reason from the ordered list of conditions in the top group. +// If required, the reason gets localized with the source object reference. +func getFirstReason(g conditionGroups, order []clusterv1.ConditionType, addSourceRef bool) string { + if condition := getFirstCondition(g, order); condition != nil { + reason := condition.Reason + if addSourceRef { + return localizeReason(reason, condition.Getter) + } + return reason + } + return "" +} + +// localizeReason adds info about the originating object to the target Reason. +func localizeReason(reason string, from Getter) string { + if strings.Contains(reason, "@") { + return reason + } + return fmt.Sprintf("%s @ %s/%s", reason, from.GetObjectKind().GroupVersionKind().Kind, from.GetName()) +} + +// getMessage returns the message to be applied to the condition resulting by merging a set of condition groups. +// The message is computed according to the given mergeOptions, but in case of errors or warning a +// summary of existing errors is automatically added. +func getMessage(groups conditionGroups, options *mergeOptions) string { + if options.addStepCounter { + return getStepCounterMessage(groups, options.stepCounter) + } + + return getFirstMessage(groups, options.conditionTypes) +} + +// getStepCounterMessage returns a message "x of y completed", where x is the number of conditions +// with Status=true and y is the number passed to this method. +func getStepCounterMessage(groups conditionGroups, to int) string { + ct := 0 + if trueGroup := groups.TrueGroup(); trueGroup != nil { + ct = len(trueGroup.conditions) + } + return fmt.Sprintf("%d of %d completed", ct, to) +} + +// getFirstMessage returns the message from the ordered list of conditions in the top group. +func getFirstMessage(groups conditionGroups, order []clusterv1.ConditionType) string { + if condition := getFirstCondition(groups, order); condition != nil { + return condition.Message + } + return "" +} + +// getFirstCondition returns a first condition from the ordered list of conditions in the top group. +func getFirstCondition(g conditionGroups, priority []clusterv1.ConditionType) *localizedCondition { + topGroup := g.TopGroup() + if topGroup == nil { + return nil + } + + switch len(topGroup.conditions) { + case 0: + return nil + case 1: + return &topGroup.conditions[0] + default: + for _, p := range priority { + for _, c := range topGroup.conditions { + if c.Type == p { + return &c + } + } + } + return &topGroup.conditions[0] + } +} diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/patch.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/patch.go similarity index 51% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/patch.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/patch.go index 939ff41ff01b..c805d193b316 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/patch.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/patch.go @@ -1,5 +1,5 @@ /* -Copyright 2024 The Kubernetes Authors. +Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,31 +14,29 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta2 +package v1beta1 import ( "reflect" - "sort" "github.com/google/go-cmp/cmp" "github.com/pkg/errors" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/cluster-api/util" ) // Patch defines a list of operations to change a list of conditions into another. type Patch []PatchOperation -// PatchOperation defines an operation that changes a single condition. +// PatchOperation define an operation that changes a single condition. type PatchOperation struct { - Before *metav1.Condition - After *metav1.Condition + Before *clusterv1.Condition + After *clusterv1.Condition Op PatchOperationType } -// PatchOperationType defines a condition patch operation type. +// PatchOperationType defines patch operation types. type PatchOperationType string const ( @@ -53,108 +51,107 @@ const ( ) // NewPatch returns the Patch required to align source conditions to after conditions. -func NewPatch(before, after Getter) (Patch, error) { +func NewPatch(before Getter, after Getter) (Patch, error) { var patch Patch if util.IsNil(before) { return nil, errors.New("error creating patch: before object is nil") } - beforeConditions := before.GetV1Beta2Conditions() - if util.IsNil(after) { return nil, errors.New("error creating patch: after object is nil") } - afterConditions := after.GetV1Beta2Conditions() // Identify AddCondition and ModifyCondition changes. - for i := range afterConditions { - afterCondition := afterConditions[i] - beforeCondition := meta.FindStatusCondition(beforeConditions, afterCondition.Type) - if beforeCondition == nil { - patch = append(patch, PatchOperation{Op: AddConditionPatch, After: &afterCondition}) + targetConditions := after.GetV1Beta1Conditions() + for i := range targetConditions { + targetCondition := targetConditions[i] + currentCondition := Get(before, targetCondition.Type) + if currentCondition == nil { + patch = append(patch, PatchOperation{Op: AddConditionPatch, After: &targetCondition}) continue } - if !reflect.DeepEqual(&afterCondition, beforeCondition) { - patch = append(patch, PatchOperation{Op: ChangeConditionPatch, After: &afterCondition, Before: beforeCondition}) + if !reflect.DeepEqual(&targetCondition, currentCondition) { + patch = append(patch, PatchOperation{Op: ChangeConditionPatch, After: &targetCondition, Before: currentCondition}) } } // Identify RemoveCondition changes. - for i := range beforeConditions { - beforeCondition := beforeConditions[i] - afterCondition := meta.FindStatusCondition(afterConditions, beforeCondition.Type) - if afterCondition == nil { - patch = append(patch, PatchOperation{Op: RemoveConditionPatch, Before: &beforeCondition}) + baseConditions := before.GetV1Beta1Conditions() + for i := range baseConditions { + baseCondition := baseConditions[i] + targetCondition := Get(after, baseCondition.Type) + if targetCondition == nil { + patch = append(patch, PatchOperation{Op: RemoveConditionPatch, Before: &baseCondition}) } } return patch, nil } -// PatchApplyOption is some configuration that modifies options for a patch apply call. -type PatchApplyOption interface { - // ApplyToPatchApply applies this configuration to the given patch apply options. - ApplyToPatchApply(option *PatchApplyOptions) +// applyOptions allows to set strategies for patch apply. +type applyOptions struct { + ownedConditions []clusterv1.ConditionType + forceOverwrite bool } -// PatchApplyOptions allows to set strategies for patch apply. -type PatchApplyOptions struct { - ownedConditionTypes []string - forceOverwrite bool - conditionSortFunc ConditionSortFunc +func (o *applyOptions) isOwnedCondition(t clusterv1.ConditionType) bool { + for _, i := range o.ownedConditions { + if i == t { + return true + } + } + return false } -// ApplyOptions applies the given list options on these options, -// and then returns itself (for convenient chaining). -func (o *PatchApplyOptions) ApplyOptions(opts []PatchApplyOption) *PatchApplyOptions { - for _, opt := range opts { - if util.IsNil(opt) { - continue - } - opt.ApplyToPatchApply(o) +// ApplyOption defines an option for applying a condition patch. +type ApplyOption func(*applyOptions) + +// WithOwnedConditions allows to define condition types owned by the controller. +// In case of conflicts for the owned conditions, the patch helper will always use the value provided by the controller. +func WithOwnedConditions(t ...clusterv1.ConditionType) ApplyOption { + return func(c *applyOptions) { + c.ownedConditions = t } - return o } -func (o *PatchApplyOptions) isOwnedConditionType(conditionType string) bool { - for _, i := range o.ownedConditionTypes { - if i == conditionType { - return true - } +// WithForceOverwrite In case of conflicts for the owned conditions, the patch helper will always use the value provided by the controller. +func WithForceOverwrite(v bool) ApplyOption { + return func(c *applyOptions) { + c.forceOverwrite = v } - return false } // Apply executes a three-way merge of a list of Patch. // When merge conflicts are detected (latest deviated from before in an incompatible way), an error is returned. -func (p Patch) Apply(latest Setter, opts ...PatchApplyOption) error { +func (p Patch) Apply(latest Setter, options ...ApplyOption) error { if p.IsZero() { return nil } if util.IsNil(latest) { - return errors.New("error patching conditions: latest object is nil") + return errors.New("error patching conditions: latest object was nil") } - latestConditions := latest.GetV1Beta2Conditions() - applyOpt := &PatchApplyOptions{ - // By default, sort conditions by the default condition order: available and ready always first, deleting and paused always last, all the other conditions in alphabetical order. - conditionSortFunc: defaultSortLessFunc, + applyOpt := &applyOptions{} + for _, o := range options { + if util.IsNil(o) { + return errors.New("error patching conditions: ApplyOption was nil") + } + o(applyOpt) } - applyOpt.ApplyOptions(opts) for _, conditionPatch := range p { switch conditionPatch.Op { case AddConditionPatch: - // If the condition is owned, always keep the after value. - if applyOpt.forceOverwrite || applyOpt.isOwnedConditionType(conditionPatch.After.Type) { - setStatusCondition(&latestConditions, *conditionPatch.After) + // If the conditions is owned, always keep the after value. + if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.After.Type) { + Set(latest, conditionPatch.After) continue } // If the condition is already on latest, check if latest and after agree on the change; if not, this is a conflict. - if latestCondition := meta.FindStatusCondition(latestConditions, conditionPatch.After.Type); latestCondition != nil { - // If latest and after disagree on the change, then it is a conflict + if latestCondition := Get(latest, conditionPatch.After.Type); latestCondition != nil { + // If latest and after agree on the change, then it is a conflict. if !HasSameState(latestCondition, conditionPatch.After) { return errors.Errorf("error patching conditions: The condition %q was modified by a different process and this caused a merge/AddCondition conflict: %v", conditionPatch.After.Type, cmp.Diff(latestCondition, conditionPatch.After)) } @@ -163,16 +160,16 @@ func (p Patch) Apply(latest Setter, opts ...PatchApplyOption) error { continue } // If the condition does not exists on the latest, add the new after condition. - setStatusCondition(&latestConditions, *conditionPatch.After) + Set(latest, conditionPatch.After) case ChangeConditionPatch: // If the conditions is owned, always keep the after value. - if applyOpt.forceOverwrite || applyOpt.isOwnedConditionType(conditionPatch.After.Type) { - setStatusCondition(&latestConditions, *conditionPatch.After) + if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.After.Type) { + Set(latest, conditionPatch.After) continue } - latestCondition := meta.FindStatusCondition(latestConditions, conditionPatch.After.Type) + latestCondition := Get(latest, conditionPatch.After.Type) // If the condition does not exist anymore on the latest, this is a conflict. if latestCondition == nil { @@ -190,39 +187,26 @@ func (p Patch) Apply(latest Setter, opts ...PatchApplyOption) error { continue } // Otherwise apply the new after condition. - setStatusCondition(&latestConditions, *conditionPatch.After) + Set(latest, conditionPatch.After) case RemoveConditionPatch: - // If latestConditions is nil or empty, nothing to remove. - if len(latestConditions) == 0 { - continue - } - // If the conditions is owned, always keep the after value (condition should be deleted). - if applyOpt.forceOverwrite || applyOpt.isOwnedConditionType(conditionPatch.Before.Type) { - meta.RemoveStatusCondition(&latestConditions, conditionPatch.Before.Type) + if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.Before.Type) { + Delete(latest, conditionPatch.Before.Type) continue } // If the condition is still on the latest, check if it is changed in the meantime; // if so then this is a conflict. - if latestCondition := meta.FindStatusCondition(latestConditions, conditionPatch.Before.Type); latestCondition != nil { + if latestCondition := Get(latest, conditionPatch.Before.Type); latestCondition != nil { if !HasSameState(latestCondition, conditionPatch.Before) { return errors.Errorf("error patching conditions: The condition %q was modified by a different process and this caused a merge/RemoveCondition conflict: %v", conditionPatch.Before.Type, cmp.Diff(latestCondition, conditionPatch.Before)) } } // Otherwise the latest and after agreed on the delete operation, so there's nothing to change. - meta.RemoveStatusCondition(&latestConditions, conditionPatch.Before.Type) + Delete(latest, conditionPatch.Before.Type) } } - - if applyOpt.conditionSortFunc != nil { - sort.SliceStable(latestConditions, func(i, j int) bool { - return applyOpt.conditionSortFunc(latestConditions[i], latestConditions[j]) - }) - } - - latest.SetV1Beta2Conditions(latestConditions) return nil } @@ -233,22 +217,3 @@ func (p Patch) IsZero() bool { } return len(p) == 0 } - -// HasSameState returns true if a condition has the same state of another; state is defined -// by the union of following fields: Type, Status, Reason, ObservedGeneration and Message (it excludes LastTransitionTime). -func HasSameState(i, j *metav1.Condition) bool { - return i.Type == j.Type && - i.Status == j.Status && - i.ObservedGeneration == j.ObservedGeneration && - i.Reason == j.Reason && - i.Message == j.Message -} - -// HasSameStateExceptObservedGeneration returns true if a condition has the same state of another; state is defined -// by the union of following fields: Type, Status, Reason and Message (it excludes ObservedGeneration and LastTransitionTime). -func HasSameStateExceptObservedGeneration(i, j *metav1.Condition) bool { - return i.Type == j.Type && - i.Status == j.Status && - i.Reason == j.Reason && - i.Message == j.Message -} diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/setter.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/setter.go new file mode 100644 index 000000000000..33797137f0e6 --- /dev/null +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/setter.go @@ -0,0 +1,262 @@ +/* +Copyright 2020 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "fmt" + "sort" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" +) + +// Setter interface defines methods that a Cluster API object should implement in order to +// use the conditions package for setting conditions. +type Setter interface { + Getter + SetV1Beta1Conditions(clusterv1.Conditions) +} + +// Set sets the given condition. +// +// NOTE: If a condition already exists, the LastTransitionTime is updated only if a change is detected +// in any of the following fields: Status, Reason, Severity and Message. +func Set(to Setter, condition *clusterv1.Condition) { + if to == nil || condition == nil { + return + } + + // Check if the new conditions already exists, and change it only if there is a status + // transition (otherwise we should preserve the current last transition time)- + conditions := to.GetV1Beta1Conditions() + exists := false + for i := range conditions { + existingCondition := conditions[i] + if existingCondition.Type == condition.Type { + exists = true + if !HasSameState(&existingCondition, condition) { + condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) + conditions[i] = *condition + break + } + condition.LastTransitionTime = existingCondition.LastTransitionTime + break + } + } + + // If the condition does not exist, add it, setting the transition time only if not already set + if !exists { + if condition.LastTransitionTime.IsZero() { + condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) + } + conditions = append(conditions, *condition) + } + + // Sorts conditions for convenience of the consumer, i.e. kubectl. + sort.Slice(conditions, func(i, j int) bool { + return lexicographicLess(&conditions[i], &conditions[j]) + }) + + to.SetV1Beta1Conditions(conditions) +} + +// SetWithCustomLastTransitionTime is similar to Set function which sets the given condition but following changes for LastTransitionTime. +// +// 1. if the condition of the specified type already exists (all fields of the existing condition are updated to +// new condition, LastTransitionTime is set to current time if unset and new status differs from the old status) +// 2. if a condition of the specified type does not exist (LastTransitionTime is set to current time if unset, and newCondition is appended) +func SetWithCustomLastTransitionTime(to Setter, condition *clusterv1.Condition) { + if to == nil || condition == nil { + return + } + + // Check if the new conditions already exists, and change it only if there is a status + // transition (otherwise we should preserve the current last transition time)- + conditions := to.GetV1Beta1Conditions() + exists := false + for i := range conditions { + existingCondition := conditions[i] + if existingCondition.Type == condition.Type { + exists = true + if !HasSameState(&existingCondition, condition) { + if existingCondition.Status != condition.Status { + if condition.LastTransitionTime.IsZero() { + condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) + } + } else { + condition.LastTransitionTime = existingCondition.LastTransitionTime + } + conditions[i] = *condition + } + break + } + } + + // If the condition does not exist, add it, setting the transition time only if not already set + if !exists { + if condition.LastTransitionTime.IsZero() { + condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) + } + conditions = append(conditions, *condition) + } + + // Sorts conditions for convenience of the consumer, i.e. kubectl. + sort.Slice(conditions, func(i, j int) bool { + return lexicographicLess(&conditions[i], &conditions[j]) + }) + + to.SetV1Beta1Conditions(conditions) +} + +// TrueCondition returns a condition with Status=True and the given type. +func TrueCondition(t clusterv1.ConditionType) *clusterv1.Condition { + return &clusterv1.Condition{ + Type: t, + Status: corev1.ConditionTrue, + } +} + +// TrueConditionWithNegativePolarity returns a condition with negative polarity, Status=True and the given type (Status=True has a negative meaning). +func TrueConditionWithNegativePolarity(t clusterv1.ConditionType, reason string, severity clusterv1.ConditionSeverity, messageFormat string, messageArgs ...interface{}) *clusterv1.Condition { + return &clusterv1.Condition{ + Type: t, + Status: corev1.ConditionTrue, + Reason: reason, + Severity: severity, + Message: fmt.Sprintf(messageFormat, messageArgs...), + } +} + +// FalseCondition returns a condition with Status=False and the given type. +func FalseCondition(t clusterv1.ConditionType, reason string, severity clusterv1.ConditionSeverity, messageFormat string, messageArgs ...interface{}) *clusterv1.Condition { + return &clusterv1.Condition{ + Type: t, + Status: corev1.ConditionFalse, + Reason: reason, + Severity: severity, + Message: fmt.Sprintf(messageFormat, messageArgs...), + } +} + +// FalseConditionWithNegativePolarity returns a condition with negative polarity, Status=false and the given type (Status=False has a positive meaning). +func FalseConditionWithNegativePolarity(t clusterv1.ConditionType) *clusterv1.Condition { + return &clusterv1.Condition{ + Type: t, + Status: corev1.ConditionFalse, + } +} + +// UnknownCondition returns a condition with Status=Unknown and the given type. +func UnknownCondition(t clusterv1.ConditionType, reason string, messageFormat string, messageArgs ...interface{}) *clusterv1.Condition { + return &clusterv1.Condition{ + Type: t, + Status: corev1.ConditionUnknown, + Reason: reason, + Message: fmt.Sprintf(messageFormat, messageArgs...), + } +} + +// MarkTrue sets Status=True for the condition with the given type. +func MarkTrue(to Setter, t clusterv1.ConditionType) { + Set(to, TrueCondition(t)) +} + +// MarkTrueWithNegativePolarity sets Status=True for a condition with negative polarity and the given type (Status=True has a negative meaning). +func MarkTrueWithNegativePolarity(to Setter, t clusterv1.ConditionType, reason string, severity clusterv1.ConditionSeverity, messageFormat string, messageArgs ...interface{}) { + Set(to, TrueConditionWithNegativePolarity(t, reason, severity, messageFormat, messageArgs...)) +} + +// MarkUnknown sets Status=Unknown for the condition with the given type. +func MarkUnknown(to Setter, t clusterv1.ConditionType, reason, messageFormat string, messageArgs ...interface{}) { + Set(to, UnknownCondition(t, reason, messageFormat, messageArgs...)) +} + +// MarkFalse sets Status=False for the condition with the given type. +func MarkFalse(to Setter, t clusterv1.ConditionType, reason string, severity clusterv1.ConditionSeverity, messageFormat string, messageArgs ...interface{}) { + Set(to, FalseCondition(t, reason, severity, messageFormat, messageArgs...)) +} + +// MarkFalseWithNegativePolarity sets Status=False for a condition with negative polarity and the given type (Status=False has a positive meaning). +func MarkFalseWithNegativePolarity(to Setter, t clusterv1.ConditionType) { + Set(to, FalseConditionWithNegativePolarity(t)) +} + +// SetSummary sets a Ready condition with the summary of all the conditions existing +// on an object. If the object does not have other conditions, no summary condition is generated. +func SetSummary(to Setter, options ...MergeOption) { + Set(to, summary(to, options...)) +} + +// SetMirror creates a new condition by mirroring the Ready condition from a dependent object; +// if the Ready condition does not exist in the source object, no target conditions is generated. +func SetMirror(to Setter, targetCondition clusterv1.ConditionType, from Getter, options ...MirrorOptions) { + Set(to, mirror(from, targetCondition, options...)) +} + +// SetAggregate creates a new condition with the aggregation of all the Ready condition +// from a list of dependent objects; if the Ready condition does not exist in one of the source object, +// the object is excluded from the aggregation; if none of the source object have ready condition, +// no target conditions is generated. +func SetAggregate(to Setter, targetCondition clusterv1.ConditionType, from []Getter, options ...MergeOption) { + Set(to, aggregate(from, targetCondition, options...)) +} + +// Delete deletes the condition with the given type. +func Delete(to Setter, t clusterv1.ConditionType) { + if to == nil { + return + } + + conditions := to.GetV1Beta1Conditions() + newConditions := make(clusterv1.Conditions, 0, len(conditions)) + for _, condition := range conditions { + if condition.Type != t { + newConditions = append(newConditions, condition) + } + } + to.SetV1Beta1Conditions(newConditions) +} + +// lexicographicLess returns true if a condition is less than another in regard to +// the order of conditions designed for convenience of the consumer, i.e. kubectl. +// According to this order the Ready condition always goes first, followed by all the other +// conditions sorted by Type. +func lexicographicLess(i, j *clusterv1.Condition) bool { + if i == nil { + return true + } + if j == nil { + return false + } + return (i.Type == clusterv1.ReadyV1Beta1Condition || i.Type < j.Type) && j.Type != clusterv1.ReadyV1Beta1Condition +} + +// HasSameState returns true if a condition has the same state of another; state is defined +// by the union of following fields: Type, Status, Reason, Severity and Message (it excludes LastTransitionTime). +func HasSameState(i, j *clusterv1.Condition) bool { + if i == nil || j == nil { + return i == j + } + return i.Type == j.Type && + i.Status == j.Status && + i.Reason == j.Reason && + i.Severity == j.Severity && + i.Message == j.Message +} diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/unstructured.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/unstructured.go similarity index 92% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/unstructured.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/unstructured.go index 3bc3bc7dda55..b752f31d09af 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/unstructured.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1/unstructured.go @@ -14,14 +14,14 @@ See the License for the specific language governing permissions and limitations under the License. */ -package conditions +package v1beta1 import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/log" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/cluster-api/util" ) @@ -50,7 +50,7 @@ type unstructuredWrapper struct { // in both cases the operation returns an empty slice is returned. // - If the object doesn't implement conditions on under status as defined in Cluster API, // JSON-unmarshal matches incoming object keys to the keys; this can lead to conditions values partially set. -func (c *unstructuredWrapper) GetConditions() clusterv1.Conditions { +func (c *unstructuredWrapper) GetV1Beta1Conditions() clusterv1.Conditions { conditions := clusterv1.Conditions{} if err := util.UnstructuredUnmarshalField(c.Unstructured, &conditions, "status", "conditions"); err != nil { return nil @@ -65,7 +65,7 @@ func (c *unstructuredWrapper) GetConditions() clusterv1.Conditions { // - Errors during JSON-unmarshal are ignored and a empty collection list is returned. // - It's not possible to detect if the object has an empty condition list or if it does not implement conditions; // in both cases the operation returns an empty slice is returned. -func (c *unstructuredWrapper) SetConditions(conditions clusterv1.Conditions) { +func (c *unstructuredWrapper) SetV1Beta1Conditions(conditions clusterv1.Conditions) { v := make([]interface{}, 0, len(conditions)) for i := range conditions { m, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&conditions[i]) @@ -77,7 +77,7 @@ func (c *unstructuredWrapper) SetConditions(conditions clusterv1.Conditions) { } // unstructured.SetNestedField returns an error only if value cannot be set because one of // the nesting levels is not a map[string]interface{}; this is not the case so the error should never happen here. - err := unstructured.SetNestedField(c.Unstructured.Object, v, "status", "conditions") + err := unstructured.SetNestedField(c.Object, v, "status", "conditions") if err != nil { log.Log.Error(err, "Failed to set Conditions on unstructured object. This error shouldn't have occurred, please file an issue.", "groupVersionKind", c.GroupVersionKind(), "name", c.GetName(), "namespace", c.GetNamespace()) } diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/doc.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/doc.go index 019d42d7c0c7..54f17ac79528 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/doc.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2020 The Kubernetes Authors. +Copyright 2024 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package conditions implements condition utilities. +// Package conditions implements utils for metav1.Conditions that will be used starting with the v1beta2 API. +// +// Please see the proposal https://github.com/kubernetes-sigs/cluster-api/tree/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. package conditions diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/getter.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/getter.go index 71a4a49acda9..e79774c20d0f 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/getter.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/getter.go @@ -1,5 +1,5 @@ /* -Copyright 2020 The Kubernetes Authors. +Copyright 2024 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,257 +17,243 @@ limitations under the License. package conditions import ( - corev1 "k8s.io/api/core/v1" + "github.com/pkg/errors" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/client" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + "sigs.k8s.io/cluster-api/util" ) -// Getter interface defines methods that a Cluster API object should implement in order to +// TODO: Move to the API package. +const ( + // NoReasonReported identifies a clusterv1.Condition that reports no reason. + NoReasonReported = "NoReasonReported" +) + +// Getter interface defines methods that an API object should implement in order to // use the conditions package for getting conditions. type Getter interface { - client.Object - // GetConditions returns the list of conditions for a cluster API object. - GetConditions() clusterv1.Conditions + GetConditions() []metav1.Condition } -// Get returns the condition with the given type, if the condition does not exist, -// it returns nil. -func Get(from Getter, t clusterv1.ConditionType) *clusterv1.Condition { - conditions := from.GetConditions() - if conditions == nil { +// Get returns a condition from the object implementing the Getter interface. +// +// Please note that Get does not support reading conditions from unstructured objects nor from API types not implementing +// the Getter interface. Eventually, users can implement wrappers on those types implementing this interface and +// taking care of aligning the condition format if necessary. +func Get(sourceObj Getter, sourceConditionType string) *metav1.Condition { + // if obj is nil, the requested condition does not exist. + if util.IsNil(sourceObj) { return nil } - for _, condition := range conditions { - if condition.Type == t { - return &condition - } - } - return nil + // Otherwise get the requested condition. + return meta.FindStatusCondition(sourceObj.GetConditions(), sourceConditionType) } // Has returns true if a condition with the given type exists. -func Has(from Getter, t clusterv1.ConditionType) bool { - return Get(from, t) != nil +func Has(from Getter, conditionType string) bool { + return Get(from, conditionType) != nil } // IsTrue is true if the condition with the given type is True, otherwise it returns false // if the condition is not True or if the condition does not exist (is nil). -func IsTrue(from Getter, t clusterv1.ConditionType) bool { - if c := Get(from, t); c != nil { - return c.Status == corev1.ConditionTrue +func IsTrue(from Getter, conditionType string) bool { + if c := Get(from, conditionType); c != nil { + return c.Status == metav1.ConditionTrue } return false } // IsFalse is true if the condition with the given type is False, otherwise it returns false // if the condition is not False or if the condition does not exist (is nil). -func IsFalse(from Getter, t clusterv1.ConditionType) bool { - if c := Get(from, t); c != nil { - return c.Status == corev1.ConditionFalse +func IsFalse(from Getter, conditionType string) bool { + if c := Get(from, conditionType); c != nil { + return c.Status == metav1.ConditionFalse } return false } // IsUnknown is true if the condition with the given type is Unknown or if the condition // does not exist (is nil). -func IsUnknown(from Getter, t clusterv1.ConditionType) bool { - if c := Get(from, t); c != nil { - return c.Status == corev1.ConditionUnknown +func IsUnknown(from Getter, conditionType string) bool { + if c := Get(from, conditionType); c != nil { + return c.Status == metav1.ConditionUnknown } return true } // GetReason returns a nil safe string of Reason for the condition with the given type. -func GetReason(from Getter, t clusterv1.ConditionType) string { - if c := Get(from, t); c != nil { +func GetReason(from Getter, conditionType string) string { + if c := Get(from, conditionType); c != nil { return c.Reason } return "" } // GetMessage returns a nil safe string of Message. -func GetMessage(from Getter, t clusterv1.ConditionType) string { - if c := Get(from, t); c != nil { +func GetMessage(from Getter, conditionType string) string { + if c := Get(from, conditionType); c != nil { return c.Message } return "" } -// GetSeverity returns the condition Severity or nil if the condition -// does not exist (is nil). -func GetSeverity(from Getter, t clusterv1.ConditionType) *clusterv1.ConditionSeverity { - if c := Get(from, t); c != nil { - return &c.Severity - } - return nil -} - -// GetLastTransitionTime returns the condition Severity or nil if the condition -// does not exist (is nil). -func GetLastTransitionTime(from Getter, t clusterv1.ConditionType) *metav1.Time { - if c := Get(from, t); c != nil { +// GetLastTransitionTime returns a nil safe metav1.Time of LastTransitionTime. +func GetLastTransitionTime(from Getter, conditionType string) *metav1.Time { + if c := Get(from, conditionType); c != nil { return &c.LastTransitionTime } return nil } -// summary returns a Ready condition with the summary of all the conditions existing -// on an object. If the object does not have other conditions, no summary condition is generated. -// NOTE: The resulting Ready condition will have positive polarity; the conditions we are starting from might have positive or negative polarity. -func summary(from Getter, options ...MergeOption) *clusterv1.Condition { - conditions := from.GetConditions() - - mergeOpt := &mergeOptions{} - for _, o := range options { - o(mergeOpt) +// UnstructuredGetAll returns conditions from an Unstructured object. +// +// UnstructuredGetAll supports retrieving conditions from objects at different stages of the transition from +// clusterv1.conditions to the metav1.Condition type: +// - Objects with clusterv1.Conditions in status.conditions; in this case a best effort conversion +// to metav1.Condition is performed, just enough to allow surfacing a condition from a provider object with Mirror +// - Objects with metav1.Condition in status.v1beta2.conditions +// - Objects with metav1.Condition in status.conditions +func UnstructuredGetAll(sourceObj runtime.Unstructured) ([]metav1.Condition, error) { + if util.IsNil(sourceObj) { + return nil, errors.New("sourceObj is nil") } - // Identifies the conditions in scope for the Summary by taking all the existing conditions except Ready, - // or, if a list of conditions types is specified, only the conditions the condition in that list. - conditionsInScope := make([]localizedCondition, 0, len(conditions)) - for i := range conditions { - c := conditions[i] - if c.Type == clusterv1.ReadyCondition { - continue - } + ownerInfo := getConditionOwnerInfo(sourceObj) - if mergeOpt.conditionTypes != nil { - found := false - for _, t := range mergeOpt.conditionTypes { - if c.Type == t { - found = true - break - } - } - if !found { - continue + value, exists, err := unstructured.NestedFieldNoCopy(sourceObj.UnstructuredContent(), "status", "v1beta2", "conditions") + if exists && err == nil { + if conditions, ok := value.([]interface{}); ok { + r, err := convertFromUnstructuredConditions(conditions) + if err != nil { + return nil, errors.Wrapf(err, "failed to convert status.v1beta2.conditions from %s to []metav1.Condition", ownerInfo.Kind) } + return r, nil } + } - // Keep track of the polarity of the condition we are starting from. - polarity := PositivePolarity - for _, t := range mergeOpt.negativeConditionTypes { - if c.Type == t { - polarity = NegativePolarity - break + value, exists, err = unstructured.NestedFieldNoCopy(sourceObj.UnstructuredContent(), "status", "conditions") + if exists && err == nil { + if conditions, ok := value.([]interface{}); ok { + r, err := convertFromUnstructuredConditions(conditions) + if err != nil { + return nil, errors.Wrapf(err, "failed to convert status.conditions from %s to []metav1.Condition", ownerInfo.Kind) } + return r, nil } + } + + // With unstructured, it is not possible to detect if conditions are not set if the type is wrongly defined. + // This methods assume condition are not set. + return nil, nil +} - conditionsInScope = append(conditionsInScope, localizedCondition{ - Condition: &c, - Polarity: polarity, - Getter: from, - }) +// UnstructuredGet returns a condition from an Unstructured object. +// +// UnstructuredGet supports retrieving conditions from objects at different stages of the transition from +// clusterv1.conditions to the metav1.Condition type: +// - Objects with clusterv1.Conditions in status.conditions; in this case a best effort conversion +// to metav1.Condition is performed, just enough to allow surfacing a condition from a provider object with Mirror +// - Objects with metav1.Condition in status.v1beta2.conditions +// - Objects with metav1.Condition in status.conditions +func UnstructuredGet(sourceObj runtime.Unstructured, sourceConditionType string) (*metav1.Condition, error) { + r, err := UnstructuredGetAll(sourceObj) + if err != nil { + return nil, err } + return meta.FindStatusCondition(r, sourceConditionType), nil +} - // If it is required to add a step counter only if a subset of condition exists, check if the conditions - // in scope are included in this subset or not. - if mergeOpt.addStepCounterIfOnlyConditionTypes != nil { - for _, c := range conditionsInScope { - found := false - for _, t := range mergeOpt.addStepCounterIfOnlyConditionTypes { - if c.Type == t { - found = true - break - } - } - if !found { - mergeOpt.addStepCounter = false - break - } - } +// convertFromUnstructuredConditions converts []interface{} to []metav1.Condition; this operation must account for +// objects which are not transitioning to metav1.Condition, or not yet fully transitioned, and thus a best +// effort conversion of values to metav1.Condition is performed. +func convertFromUnstructuredConditions(conditions []interface{}) ([]metav1.Condition, error) { + if conditions == nil { + return nil, nil } - // If it is required to add a step counter, determine the total number of conditions defaulting - // to the selected conditions or, if defined, to the total number of conditions type to be considered. - if mergeOpt.addStepCounter { - mergeOpt.stepCounter = len(conditionsInScope) - if mergeOpt.conditionTypes != nil { - mergeOpt.stepCounter = len(mergeOpt.conditionTypes) + convertedConditions := make([]metav1.Condition, 0, len(conditions)) + for _, c := range conditions { + cMap, ok := c.(map[string]interface{}) + if !ok || cMap == nil { + continue } - if mergeOpt.addStepCounterIfOnlyConditionTypes != nil { - mergeOpt.stepCounter = len(mergeOpt.addStepCounterIfOnlyConditionTypes) + + var conditionType string + if v, ok := cMap["type"]; ok { + conditionType = v.(string) } - } - return merge(conditionsInScope, clusterv1.ReadyCondition, mergeOpt) -} + var status string + if v, ok := cMap["status"]; ok { + status = v.(string) + } -// mirrorOptions allows to set options for the mirror operation. -type mirrorOptions struct { - fallbackTo *bool - fallbackReason string - fallbackSeverity clusterv1.ConditionSeverity - fallbackMessage string -} + var observedGeneration int64 + if v, ok := cMap["observedGeneration"]; ok { + observedGeneration = v.(int64) + } -// MirrorOptions defines an option for mirroring conditions. -type MirrorOptions func(*mirrorOptions) - -// WithFallbackValue specify a fallback value to use in case the mirrored condition does not exist; -// in case the fallbackValue is false, given values for reason, severity and message will be used. -func WithFallbackValue(fallbackValue bool, reason string, severity clusterv1.ConditionSeverity, message string) MirrorOptions { - return func(c *mirrorOptions) { - c.fallbackTo = &fallbackValue - c.fallbackReason = reason - c.fallbackSeverity = severity - c.fallbackMessage = message - } -} + var lastTransitionTime metav1.Time + if v, ok := cMap["lastTransitionTime"]; ok && v != nil && v.(string) != "" { + if err := lastTransitionTime.UnmarshalQueryParameter(v.(string)); err != nil { + return nil, errors.Wrapf(err, "failed to unmarshal lastTransitionTime value: %s", v) + } + } -// mirror mirrors the Ready condition from a dependent object into the target condition; -// if the Ready condition does not exist in the source object, no target conditions is generated. -// NOTE: Considering that we are mirroring Ready conditions with positive polarity, also the resulting condition will have positive polarity. -func mirror(from Getter, targetCondition clusterv1.ConditionType, options ...MirrorOptions) *clusterv1.Condition { - mirrorOpt := &mirrorOptions{} - for _, o := range options { - o(mirrorOpt) - } + var reason string + if v, ok := cMap["reason"]; ok { + reason = v.(string) + } - condition := Get(from, clusterv1.ReadyCondition) + var message string + if v, ok := cMap["message"]; ok { + message = v.(string) + } - if mirrorOpt.fallbackTo != nil && condition == nil { - switch *mirrorOpt.fallbackTo { - case true: - condition = TrueCondition(targetCondition) - case false: - condition = FalseCondition(targetCondition, mirrorOpt.fallbackReason, mirrorOpt.fallbackSeverity, mirrorOpt.fallbackMessage) + c := metav1.Condition{ + Type: conditionType, + Status: metav1.ConditionStatus(status), + ObservedGeneration: observedGeneration, + LastTransitionTime: lastTransitionTime, + Reason: reason, + Message: message, + } + if err := validateAndFixConvertedCondition(&c); err != nil { + return nil, err } - } - if condition != nil { - condition.Type = targetCondition + convertedConditions = append(convertedConditions, c) } - - return condition + return convertedConditions, nil } -// Aggregates all the Ready condition from a list of dependent objects into the target object; -// if the Ready condition does not exist in one of the source object, the object is excluded from -// the aggregation; if none of the source object have ready condition, no target conditions is generated. -// NOTE: Considering that we are aggregating Ready conditions with positive polarity, also the resulting condition will have positive polarity. -func aggregate(from []Getter, targetCondition clusterv1.ConditionType, options ...MergeOption) *clusterv1.Condition { - conditionsInScope := make([]localizedCondition, 0, len(from)) - for i := range from { - condition := Get(from[i], clusterv1.ReadyCondition) - - conditionsInScope = append(conditionsInScope, localizedCondition{ - Condition: condition, - Polarity: PositivePolarity, - Getter: from[i], - }) +// validateAndFixConvertedCondition validates and fixes a clusterv1.Condition converted to a metav1.Condition. +// this operation assumes conditions have been set using Cluster API condition utils; +// also, only a few, minimal rules are enforced, just enough to allow surfacing a condition from a providers object with Mirror. +func validateAndFixConvertedCondition(c *metav1.Condition) error { + if c.Type == "" { + return errors.New("type must be set for all conditions") } - - mergeOpt := &mergeOptions{ - addStepCounter: true, - stepCounter: len(from), + if c.Status == "" { + return errors.Errorf("status must be set for the %s condition", c.Type) + } + switch c.Status { + case metav1.ConditionFalse, metav1.ConditionTrue, metav1.ConditionUnknown: + break + default: + return errors.Errorf("status for the %s condition must be one of %s, %s, %s", c.Type, metav1.ConditionTrue, metav1.ConditionFalse, metav1.ConditionUnknown) } - for _, o := range options { - o(mergeOpt) + if c.Reason == "" { + c.Reason = NoReasonReported } - return merge(conditionsInScope, targetCondition, mergeOpt) + + // NOTE: Empty LastTransitionTime is tolerated because it will be set when assigning the newly generated mirror condition to an object. + // NOTE: Other metav1.Condition validations rules, e.g. regex, are not enforced at this stage; they will be enforced by the API server at a later stage. + + return nil } diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/matcher.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/matcher.go index 97fa86d35b88..f2efd3484c0e 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/matcher.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/matcher.go @@ -1,5 +1,5 @@ /* -Copyright 2020 The Kubernetes Authors. +Copyright 2024 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,25 +21,54 @@ import ( "github.com/onsi/gomega" "github.com/onsi/gomega/types" - - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// MatchConditions returns a custom matcher to check equality of clusterv1.Conditions. -func MatchConditions(expected clusterv1.Conditions) types.GomegaMatcher { +// IgnoreLastTransitionTime instructs MatchConditions and MatchCondition to ignore the LastTransitionTime field. +type IgnoreLastTransitionTime bool + +// ApplyMatch applies this configuration to the given Match options. +func (f IgnoreLastTransitionTime) ApplyMatch(opts *MatchOptions) { + opts.ignoreLastTransitionTime = bool(f) +} + +// MatchOption is some configuration that modifies options for a match call. +type MatchOption interface { + // ApplyMatch applies this configuration to the given match options. + ApplyMatch(option *MatchOptions) +} + +// MatchOptions allows to set options for the match operation. +type MatchOptions struct { + ignoreLastTransitionTime bool +} + +// ApplyOptions applies the given list options on these options, +// and then returns itself (for convenient chaining). +func (o *MatchOptions) ApplyOptions(opts []MatchOption) *MatchOptions { + for _, opt := range opts { + opt.ApplyMatch(o) + } + return o +} + +// MatchConditions returns a custom matcher to check equality of []metav1.Condition. +func MatchConditions(expected []metav1.Condition, opts ...MatchOption) types.GomegaMatcher { return &matchConditions{ + opts: opts, expected: expected, } } type matchConditions struct { - expected clusterv1.Conditions + opts []MatchOption + expected []metav1.Condition } func (m matchConditions) Match(actual interface{}) (success bool, err error) { elems := []interface{}{} for _, condition := range m.expected { - elems = append(elems, MatchCondition(condition)) + elems = append(elems, MatchCondition(condition, m.opts...)) } return gomega.ConsistOf(elems...).Match(actual) @@ -53,21 +82,28 @@ func (m matchConditions) NegatedFailureMessage(actual interface{}) (message stri return fmt.Sprintf("expected\n\t%#v\nto not match\n\t%#v\n", actual, m.expected) } -// MatchCondition returns a custom matcher to check equality of clusterv1.Condition. -func MatchCondition(expected clusterv1.Condition) types.GomegaMatcher { +// MatchCondition returns a custom matcher to check equality of metav1.Condition. +func MatchCondition(expected metav1.Condition, opts ...MatchOption) types.GomegaMatcher { return &matchCondition{ + opts: opts, expected: expected, } } type matchCondition struct { - expected clusterv1.Condition + opts []MatchOption + expected metav1.Condition } func (m matchCondition) Match(actual interface{}) (success bool, err error) { - actualCondition, ok := actual.(clusterv1.Condition) + matchOpt := &MatchOptions{ + ignoreLastTransitionTime: false, + } + matchOpt.ApplyOptions(m.opts) + + actualCondition, ok := actual.(metav1.Condition) if !ok { - return false, fmt.Errorf("actual should be of type Condition") + return false, fmt.Errorf("actual should be of type metav1.Condition") } ok, err = gomega.Equal(m.expected.Type).Match(actualCondition.Type) @@ -78,7 +114,7 @@ func (m matchCondition) Match(actual interface{}) (success bool, err error) { if !ok { return ok, err } - ok, err = gomega.Equal(m.expected.Severity).Match(actualCondition.Severity) + ok, err = gomega.Equal(m.expected.ObservedGeneration).Match(actualCondition.ObservedGeneration) if !ok { return ok, err } @@ -91,6 +127,13 @@ func (m matchCondition) Match(actual interface{}) (success bool, err error) { return ok, err } + if !matchOpt.ignoreLastTransitionTime { + ok, err = gomega.BeTemporally("==", m.expected.LastTransitionTime.Time).Match(actualCondition.LastTransitionTime.Time) + if !ok { + return ok, err + } + } + return ok, err } diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/merge_strategies.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/merge_strategies.go index f4d038ff039f..c61701bef0cd 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/merge_strategies.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/merge_strategies.go @@ -1,5 +1,5 @@ /* -Copyright 2020 The Kubernetes Authors. +Copyright 2024 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,161 +18,633 @@ package conditions import ( "fmt" + "reflect" + "regexp" + "sort" "strings" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + "github.com/gobuffalo/flect" + "github.com/pkg/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/sets" + + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) -// mergeOptions allows to set strategies for merging a set of conditions into a single condition, -// and more specifically for computing the target Reason and the target Message. -type mergeOptions struct { - conditionTypes []clusterv1.ConditionType - negativeConditionTypes []clusterv1.ConditionType - addSourceRef bool - addStepCounter bool - addStepCounterIfOnlyConditionTypes []clusterv1.ConditionType - stepCounter int +// ConditionWithOwnerInfo is a wrapper around metav1.Condition with additional ConditionOwnerInfo. +// These infos can be used when generating the message resulting from the merge operation. +type ConditionWithOwnerInfo struct { + OwnerResource ConditionOwnerInfo + metav1.Condition } -// MergeOption defines an option for computing a summary of conditions. -type MergeOption func(*mergeOptions) +// ConditionOwnerInfo contains infos about the object that owns the condition. +type ConditionOwnerInfo struct { + Kind string + Name string + IsControlPlaneMachine bool +} -// WithConditions instructs merge about the condition types to consider when doing a merge operation; -// if this option is not specified, all the conditions (excepts Ready) will be considered. This is required, -// so we can provide some guarantees about the semantic of the target condition without worrying about -// side effects if someone or something adds custom conditions to the objects. -// -// NOTE: The order of conditions types defines the priority for determining the Reason and Message for the -// target condition. -// IMPORTANT: This options works only while generating the Summary condition. -func WithConditions(t ...clusterv1.ConditionType) MergeOption { - return func(c *mergeOptions) { - c.conditionTypes = t - } +// String returns a string representation of the ConditionOwnerInfo. +func (o ConditionOwnerInfo) String() string { + return fmt.Sprintf("%s %s", o.Kind, o.Name) } -// WithNegativePolarityConditions instruct merge about which conditions should be considered having negative polarity. -// IMPORTANT: this must be a subset of WithConditions. -func WithNegativePolarityConditions(t ...clusterv1.ConditionType) MergeOption { - return func(c *mergeOptions) { - c.negativeConditionTypes = t - } +// MergeOperation defines merge operations. +type MergeOperation string + +const ( + // SummaryMergeOperation defines a merge operation of type Summary. + // Summary should merge different conditions from the same object. + SummaryMergeOperation MergeOperation = "Summary" + + // AggregateMergeOperation defines a merge operation of type Aggregate. + // Aggregate should merge the same condition across many objects. + AggregateMergeOperation MergeOperation = "Aggregate" +) + +// MergeStrategy defines a strategy used to merge conditions during the aggregate or summary operation. +type MergeStrategy interface { + // Merge passed in conditions. + // + // It is up to the caller to ensure that all the expected conditions exist (e.g. by adding new conditions with status Unknown). + // Conditions passed in must be of the given conditionTypes (other condition types must be discarded). + // + // The list of conditionTypes has an implicit order; it is up to the implementation of merge to use this info or not. + Merge(operation MergeOperation, conditions []ConditionWithOwnerInfo, conditionTypes []string) (status metav1.ConditionStatus, reason, message string, err error) +} + +// DefaultMergeStrategyOption is some configuration that modifies the DefaultMergeStrategy behaviour. +type DefaultMergeStrategyOption interface { + // ApplyToDefaultMergeStrategy applies this configuration to the given DefaultMergeStrategy options. + ApplyToDefaultMergeStrategy(option *DefaultMergeStrategyOptions) +} + +// DefaultMergeStrategyOptions allows to set options for the DefaultMergeStrategy behaviour. +type DefaultMergeStrategyOptions struct { + getPriorityFunc func(condition metav1.Condition) MergePriority + targetConditionHasPositivePolarity bool + computeReasonFunc func(issueConditions []ConditionWithOwnerInfo, unknownConditions []ConditionWithOwnerInfo, infoConditions []ConditionWithOwnerInfo) string + summaryMessageTransformFunc func([]string) []string } -// WithStepCounter instructs merge to add a "x of y completed" string to the message, -// where x is the number of conditions with Status=true and y is the number of conditions in scope. -func WithStepCounter() MergeOption { - return func(c *mergeOptions) { - c.addStepCounter = true +// ApplyOptions applies the given list options on these options, +// and then returns itself (for convenient chaining). +func (o *DefaultMergeStrategyOptions) ApplyOptions(opts []DefaultMergeStrategyOption) *DefaultMergeStrategyOptions { + for _, opt := range opts { + opt.ApplyToDefaultMergeStrategy(o) } + return o } -// WithStepCounterIf adds a step counter if the value is true. -// This can be used e.g. to add a step counter only if the object is not being deleted. +// DefaultMergeStrategy returns the default merge strategy. +// +// Use the GetPriorityFunc option to customize how the MergePriority for a given condition is computed. +// If not specified, conditions are considered issues or not if not to their normal state given the polarity +// (e.g. a positive polarity condition is considered to be reporting an issue when status is false, +// otherwise the condition is considered to be reporting an info unless status is unknown). // -// IMPORTANT: This options works only while generating the Summary condition. -func WithStepCounterIf(value bool) MergeOption { - return func(c *mergeOptions) { - c.addStepCounter = value +// Use the TargetConditionHasPositivePolarity to define the polarity of the condition returned by the DefaultMergeStrategy. +// If not specified, the generate condition will have positive polarity (status true = good). +// +// Use the ComputeReasonFunc to customize how the reason for the resulting condition will be computed. +// If not specified, generic reasons will be used. +func DefaultMergeStrategy(opts ...DefaultMergeStrategyOption) MergeStrategy { + strategyOpt := &DefaultMergeStrategyOptions{ + targetConditionHasPositivePolarity: true, + computeReasonFunc: GetDefaultComputeMergeReasonFunc(issuesReportedReason, unknownReportedReason, infoReportedReason), // NOTE: when no specific reason are provided, generic ones are used. + getPriorityFunc: GetDefaultMergePriorityFunc(), + summaryMessageTransformFunc: nil, + } + strategyOpt.ApplyOptions(opts) + + return &defaultMergeStrategy{ + getPriorityFunc: strategyOpt.getPriorityFunc, + computeReasonFunc: strategyOpt.computeReasonFunc, + targetConditionHasPositivePolarity: strategyOpt.targetConditionHasPositivePolarity, + summaryMessageTransformFunc: strategyOpt.summaryMessageTransformFunc, } } -// WithStepCounterIfOnly ensure a step counter is show only if a subset of condition exists. -// This applies for example on Machines, where we want to use -// the step counter notation while provisioning the machine, but then we want to move away from this notation -// as soon as the machine is provisioned and e.g. a Machine health check condition is generated -// -// IMPORTANT: This options requires WithStepCounter or WithStepCounterIf to be set. -// IMPORTANT: This options works only while generating the Summary condition. -func WithStepCounterIfOnly(t ...clusterv1.ConditionType) MergeOption { - return func(c *mergeOptions) { - c.addStepCounterIfOnlyConditionTypes = t +// GetDefaultMergePriorityFunc returns the merge priority for each condition. +// It assigns following priority values to conditions: +// - issues: conditions with positive polarity (normal True) and status False or conditions with negative polarity (normal False) and status True. +// - unknown: conditions with status unknown. +// - info: conditions with positive polarity (normal True) and status True or conditions with negative polarity (normal False) and status False. +func GetDefaultMergePriorityFunc(negativePolarityConditionTypes ...string) func(condition metav1.Condition) MergePriority { + negativePolarityConditionTypesSet := sets.New[string](negativePolarityConditionTypes...) + return func(condition metav1.Condition) MergePriority { + switch condition.Status { + case metav1.ConditionTrue: + if negativePolarityConditionTypesSet.Has(condition.Type) { + return IssueMergePriority + } + return InfoMergePriority + case metav1.ConditionFalse: + if negativePolarityConditionTypesSet.Has(condition.Type) { + return InfoMergePriority + } + return IssueMergePriority + case metav1.ConditionUnknown: + return UnknownMergePriority + } + + // Note: this should never happen. In case, those conditions are considered like conditions with unknown status. + return UnknownMergePriority } } -// AddSourceRef instructs merge to add info about the originating object to the target Reason. -func AddSourceRef() MergeOption { - return func(c *mergeOptions) { - c.addSourceRef = true +// MergePriority defines the priority for a condition during a merge operation. +type MergePriority uint8 + +const ( + // IssueMergePriority is the merge priority used by GetDefaultMergePriority in case the condition state is considered an issue. + IssueMergePriority MergePriority = iota + + // UnknownMergePriority is the merge priority used by GetDefaultMergePriority in case of unknown conditions. + UnknownMergePriority + + // InfoMergePriority is the merge priority used by GetDefaultMergePriority in case the condition state is not considered an issue. + InfoMergePriority +) + +// GetDefaultComputeMergeReasonFunc return a function picking one of the three reasons in input depending on +// the status of the conditions being merged. +func GetDefaultComputeMergeReasonFunc(issueReason, unknownReason, infoReason string) func(issueConditions []ConditionWithOwnerInfo, unknownConditions []ConditionWithOwnerInfo, infoConditions []ConditionWithOwnerInfo) string { + return func(issueConditions []ConditionWithOwnerInfo, unknownConditions []ConditionWithOwnerInfo, _ []ConditionWithOwnerInfo) string { + switch { + case len(issueConditions) > 0: + return issueReason + case len(unknownConditions) > 0: + return unknownReason + default: + // Note: This func can assume that there is at least one condition, so this branch is equivalent to len(infoReason) > 0, + // and it makes the linter happy. + return infoReason + } } } -// getReason returns the reason to be applied to the condition resulting by merging a set of condition groups. -// The reason is computed according to the given mergeOptions. -func getReason(groups conditionGroups, options *mergeOptions) string { - return getFirstReason(groups, options.conditionTypes, options.addSourceRef) +const ( + // issuesReportedReason is set on conditions generated during aggregate or summary operations when at least one conditions/objects are reporting issues. + // NOTE: This const is used by GetDefaultComputeMergeReasonFunc if no specific reasons are provided. + issuesReportedReason = "IssuesReported" + + // unknownReportedReason is set on conditions generated during aggregate or summary operations when at least one conditions/objects are reporting unknown. + // NOTE: This const is used by GetDefaultComputeMergeReasonFunc if no specific reasons are provided. + unknownReportedReason = "UnknownReported" + + // infoReportedReason is set on conditions generated during aggregate or summary operations when at least one conditions/objects are reporting info. + // NOTE: This const is used by GetDefaultComputeMergeReasonFunc if no specific reasons are provided. + infoReportedReason = "InfoReported" +) + +// defaultMergeStrategy defines the default merge strategy for Cluster API conditions. +type defaultMergeStrategy struct { + getPriorityFunc func(condition metav1.Condition) MergePriority + targetConditionHasPositivePolarity bool + computeReasonFunc func(issueConditions []ConditionWithOwnerInfo, unknownConditions []ConditionWithOwnerInfo, infoConditions []ConditionWithOwnerInfo) string + summaryMessageTransformFunc func([]string) []string } -// getFirstReason returns the first reason from the ordered list of conditions in the top group. -// If required, the reason gets localized with the source object reference. -func getFirstReason(g conditionGroups, order []clusterv1.ConditionType, addSourceRef bool) string { - if condition := getFirstCondition(g, order); condition != nil { - reason := condition.Reason - if addSourceRef { - return localizeReason(reason, condition.Getter) +// Merge all conditions in input based on a strategy that surfaces issues first, then unknown conditions, then info (if none of issues and unknown condition exists). +// - issues: conditions with positive polarity (normal True) and status False or conditions with negative polarity (normal False) and status True. +// - unknown: conditions with status unknown. +// - info: conditions with positive polarity (normal True) and status True or conditions with negative polarity (normal False) and status False. +func (d *defaultMergeStrategy) Merge(operation MergeOperation, conditions []ConditionWithOwnerInfo, conditionTypes []string) (status metav1.ConditionStatus, reason, message string, err error) { + if len(conditions) == 0 { + return "", "", "", errors.New("can't merge an empty list of conditions") + } + + if d.getPriorityFunc == nil { + return "", "", "", errors.New("can't merge without a getPriority func") + } + + // sortConditions the relevance defined by the users (the order of condition types), LastTransition time (older first). + sortConditions(conditions, conditionTypes) + + issueConditions, unknownConditions, infoConditions := splitConditionsByPriority(conditions, d.getPriorityFunc) + + // Compute the status for the target condition: + // Note: This function always returns a condition with positive polarity. + // - if there are issues, use false + // - else if there are unknown, use unknown + // - else if there are info, use true + switch { + case len(issueConditions) > 0: + if d.targetConditionHasPositivePolarity { + status = metav1.ConditionFalse + } else { + status = metav1.ConditionTrue + } + case len(unknownConditions) > 0: + status = metav1.ConditionUnknown + case len(infoConditions) > 0: + if d.targetConditionHasPositivePolarity { + status = metav1.ConditionTrue + } else { + status = metav1.ConditionFalse + } + default: + // NOTE: this is already handled above, but repeating also here for better readability. + return "", "", "", errors.New("can't merge an empty list of conditions") + } + + // Compute the reason for the target condition: + // - In case there is only one condition in the top group, use the reason from this condition + // - In case there are more than one condition in the top group, use a generic reason (for the target group) + reason = d.computeReasonFunc(issueConditions, unknownConditions, infoConditions) + + // Compute the message for the target condition, which is optimized for the operation being performed. + + // When performing the summary operation, usually we are merging a small set of conditions from the same object, + // Considering the small number of conditions, involved it is acceptable/preferred to provide as much detail + // as possible about the messages from the conditions being merged. + // + // Accordingly, the resulting message is composed by all the messages from conditions classified as issues/unknown; + // messages from conditions classified as info are included only if there are no issues/unknown. + // + // e.g. Condition-B (False): Message-B; Condition-!C (True): Message-!C; Condition-A (Unknown): Message-A + // + // When including messages from conditions, they are sorted by issue/unknown and by the implicit order of condition types + // provided by the user (it is considered as order of relevance). + if operation == SummaryMergeOperation { + message = summaryMessage(conditions, d, status) + } + + // When performing the aggregate operation, we are merging one single condition from potentially many objects. + // Considering the high number of conditions involved, the messages from the conditions being merged must be filtered/summarized + // using rules designed to surface the most important issues. + // + // Accordingly, the resulting message is composed by only three messages from conditions classified as issues/unknown; + // instead three messages from conditions classified as info are included only if there are no issues/unknown. + // + // Three criteria are used to pick the messages to be shown + // - Messages for control plane machines always go first + // - Messages for issues always go before messages for unknown, info messages goes last + // - The number of objects reporting the same message determine the order used to pick within the messages in the same bucket + // + // For each message it is reported a list of max 3 objects reporting the message; if more objects are reporting the same + // message, the number of those objects is surfaced. + // + // e.g. (False): Message-1 from obj0, obj1, obj2 and 2 more Objects + // + // If there are other objects - objects not included in the list above - reporting issues/unknown (or info there no issues/unknown), + // the number of those objects is surfaced. + // + // e.g. ...; 2 more Objects with issues; 1 more Objects with unknown status + // + if operation == AggregateMergeOperation { + n := 3 + messages := []string{} + + // Get max n issue/unknown messages, decrement n, and track if there are other objects reporting issues/unknown not included in the messages. + if len(issueConditions) > 0 || len(unknownConditions) > 0 { + issueMessages := aggregateMessages(append(issueConditions, unknownConditions...), &n, false, d.getPriorityFunc, map[MergePriority]string{IssueMergePriority: "with other issues", UnknownMergePriority: "with status unknown"}) + messages = append(messages, issueMessages...) } - return reason + + // Only if there are no issue or unknown, + // Get max n info messages, decrement n, and track if there are other objects reporting info not included in the messages. + if len(issueConditions) == 0 && len(unknownConditions) == 0 && len(infoConditions) > 0 { + infoMessages := aggregateMessages(infoConditions, &n, true, d.getPriorityFunc, map[MergePriority]string{InfoMergePriority: "with additional info"}) + messages = append(messages, infoMessages...) + } + + message = strings.Join(messages, "\n") + } + + return status, reason, message, nil +} + +// sortConditions by condition types order, LastTransitionTime +// (the order of relevance defined by the users, the oldest first). +func sortConditions(conditions []ConditionWithOwnerInfo, orderedConditionTypes []string) { + conditionOrder := make(map[string]int, len(orderedConditionTypes)) + for i, conditionType := range orderedConditionTypes { + conditionOrder[conditionType] = i } - return "" + + sort.SliceStable(conditions, func(i, j int) bool { + // Sort by condition order (user defined, useful when computing summary of different conditions from the same object) + return conditionOrder[conditions[i].Type] < conditionOrder[conditions[j].Type] || + // If same condition order, sort by last transition time (useful when computing aggregation of the same conditions from different objects) + (conditionOrder[conditions[i].Type] == conditionOrder[conditions[j].Type] && conditions[i].LastTransitionTime.Before(&conditions[j].LastTransitionTime)) + }) } -// localizeReason adds info about the originating object to the target Reason. -func localizeReason(reason string, from Getter) string { - if strings.Contains(reason, "@") { - return reason +// splitConditionsByPriority split conditions in 3 groups: +// - conditions representing an issue. +// - conditions with status unknown. +// - conditions representing an info. +// NOTE: The order of conditions is preserved in each group. +func splitConditionsByPriority(conditions []ConditionWithOwnerInfo, getPriority func(condition metav1.Condition) MergePriority) (issueConditions, unknownConditions, infoConditions []ConditionWithOwnerInfo) { + for _, condition := range conditions { + switch getPriority(condition.Condition) { + case IssueMergePriority: + issueConditions = append(issueConditions, condition) + case UnknownMergePriority: + unknownConditions = append(unknownConditions, condition) + case InfoMergePriority: + infoConditions = append(infoConditions, condition) + } } - return fmt.Sprintf("%s @ %s/%s", reason, from.GetObjectKind().GroupVersionKind().Kind, from.GetName()) + return issueConditions, unknownConditions, infoConditions } -// getMessage returns the message to be applied to the condition resulting by merging a set of condition groups. -// The message is computed according to the given mergeOptions, but in case of errors or warning a -// summary of existing errors is automatically added. -func getMessage(groups conditionGroups, options *mergeOptions) string { - if options.addStepCounter { - return getStepCounterMessage(groups, options.stepCounter) +// summaryMessage returns message for the summary operation. +func summaryMessage(conditions []ConditionWithOwnerInfo, d *defaultMergeStrategy, status metav1.ConditionStatus) string { + messages := []string{} + + // Note: use conditions because we want to preserve the order of relevance defined by the users (the order of condition types). + for _, condition := range conditions { + priority := d.getPriorityFunc(condition.Condition) + if priority == InfoMergePriority { + // Drop info messages when we are surfacing issues or unknown. + if status != metav1.ConditionTrue { + continue + } + // Drop info conditions with empty messages. + if condition.Message == "" { + continue + } + } + + m := fmt.Sprintf("* %s:", condition.Type) + if condition.Message != "" { + m += indentIfMultiline(condition.Message) + } else { + m += fmt.Sprintf(" %s", condition.Reason) + } + messages = append(messages, m) + } + + if d.summaryMessageTransformFunc != nil { + messages = d.summaryMessageTransformFunc(messages) } - return getFirstMessage(groups, options.conditionTypes) + return strings.Join(messages, "\n") } -// getStepCounterMessage returns a message "x of y completed", where x is the number of conditions -// with Status=true and y is the number passed to this method. -func getStepCounterMessage(groups conditionGroups, to int) string { - ct := 0 - if trueGroup := groups.TrueGroup(); trueGroup != nil { - ct = len(trueGroup.conditions) +// aggregateMessages returns messages for the aggregate operation. +func aggregateMessages(conditions []ConditionWithOwnerInfo, n *int, dropEmpty bool, getPriority func(condition metav1.Condition) MergePriority, otherMessages map[MergePriority]string) (messages []string) { + // create a map with all the messages and the list of objects reporting the same message. + messageObjMap := map[string]map[string][]string{} + messagePriorityMap := map[string]MergePriority{} + messageMustGoFirst := map[string]bool{} + cpMachines := sets.Set[string]{} + for _, condition := range conditions { + if dropEmpty && condition.Message == "" { + continue + } + + // Keep track of the message and the list of objects it applies to. + m := condition.Message + if _, ok := messageObjMap[condition.OwnerResource.Kind]; !ok { + messageObjMap[condition.OwnerResource.Kind] = map[string][]string{} + } + messageObjMap[condition.OwnerResource.Kind][m] = append(messageObjMap[condition.OwnerResource.Kind][m], condition.OwnerResource.Name) + + // Keep track of CP machines + if condition.OwnerResource.IsControlPlaneMachine { + cpMachines.Insert(condition.OwnerResource.Name) + } + + // Keep track of the priority of the message. + // In case the same message exists with different priorities, the highest according to issue/unknown/info applies. + currentPriority, ok := messagePriorityMap[m] + newPriority := getPriority(condition.Condition) + switch { + case !ok: + messagePriorityMap[m] = newPriority + case currentPriority == IssueMergePriority: + // No-op, issue is already the highest priority. + case currentPriority == UnknownMergePriority: + // If current priority is unknown, use new one only if higher. + if newPriority == IssueMergePriority { + messagePriorityMap[m] = newPriority + } + case currentPriority == InfoMergePriority: + // if current priority is info, new one can be equal or higher, use it. + messagePriorityMap[m] = newPriority + } + + // Keep track if this message belongs to control plane machines, and thus it should go first. + // Note: it is enough that on object is a control plane machine to move the message as first. + first, ok := messageMustGoFirst[m] + if !ok || !first { + if condition.OwnerResource.IsControlPlaneMachine { + messageMustGoFirst[m] = true + } + } + } + + // Gets the objects kind (with a stable order). + kinds := make([]string, 0, len(messageObjMap)) + for kind := range messageObjMap { + kinds = append(kinds, kind) + } + sort.Strings(kinds) + + // Aggregate messages for each object kind. + for _, kind := range kinds { + kindPlural := flect.Pluralize(kind) + messageObjMapForKind := messageObjMap[kind] + + // compute the order of messages according to: + // - message should go first (e.g. it applies to a control plane machine) + // - message priority (e.g. first issues, then unknown) + // - the number of objects reporting the same message. + // Note: The list of object names is used as a secondary criteria to sort messages with the same number of objects. + messageIndex := make([]string, 0, len(messageObjMapForKind)) + for m := range messageObjMapForKind { + messageIndex = append(messageIndex, m) + } + + sort.SliceStable(messageIndex, func(i, j int) bool { + return sortMessage(messageIndex[i], messageIndex[j], messageMustGoFirst, messagePriorityMap, messageObjMapForKind) + }) + + // Pick the first n messages, decrement n. + // For each message, add up to three objects; if more add the number of the remaining objects with the same message. + // Count the number of objects reporting messages not included in the above. + // Note: we are showing up to three objects because usually control plane has 3 machines, and we want to show all issues + // to control plane machines if any, + others := map[MergePriority]int{} + for _, m := range messageIndex { + if *n == 0 { + others[messagePriorityMap[m]] += len(messageObjMapForKind[m]) + continue + } + + msg := "" + allObjects := messageObjMapForKind[m] + sort.Slice(allObjects, func(i, j int) bool { + return sortObj(allObjects[i], allObjects[j], cpMachines) + }) + switch { + case len(allObjects) == 0: + // This should never happen, entry in the map exists only when an object reports a message. + case len(allObjects) == 1: + msg += fmt.Sprintf("* %s %s:", kind, strings.Join(allObjects, ", ")) + case len(allObjects) <= 3: + msg += fmt.Sprintf("* %s %s:", kindPlural, strings.Join(allObjects, ", ")) + default: + msg += fmt.Sprintf("* %s %s, ... (%d more):", kindPlural, strings.Join(allObjects[:3], ", "), len(allObjects)-3) + } + msg += indentIfMultiline(m) + + messages = append(messages, msg) + *n-- + } + + for _, p := range []MergePriority{IssueMergePriority, UnknownMergePriority, InfoMergePriority} { + other, ok := others[p] + if !ok { + continue + } + + otherMessage, ok := otherMessages[p] + if !ok { + continue + } + if other == 1 { + messages = append(messages, fmt.Sprintf("And %d %s %s", other, kind, otherMessage)) + } + if other > 1 { + messages = append(messages, fmt.Sprintf("And %d %s %s", other, kindPlural, otherMessage)) + } + } } - return fmt.Sprintf("%d of %d completed", ct, to) + + return messages } -// getFirstMessage returns the message from the ordered list of conditions in the top group. -func getFirstMessage(groups conditionGroups, order []clusterv1.ConditionType) string { - if condition := getFirstCondition(groups, order); condition != nil { - return condition.Message +func sortMessage(i, j string, messageMustGoFirst map[string]bool, messagePriorityMap map[string]MergePriority, messageObjMapForKind map[string][]string) bool { + if messageMustGoFirst[i] && !messageMustGoFirst[j] { + return true + } + if !messageMustGoFirst[i] && messageMustGoFirst[j] { + return false + } + + if messagePriorityMap[i] < messagePriorityMap[j] { + return true + } + if messagePriorityMap[i] > messagePriorityMap[j] { + return false + } + + if len(messageObjMapForKind[i]) > len(messageObjMapForKind[j]) { + return true + } + if len(messageObjMapForKind[i]) < len(messageObjMapForKind[j]) { + return false } - return "" + + return strings.Join(messageObjMapForKind[i], ",") < strings.Join(messageObjMapForKind[j], ",") } -// getFirstCondition returns a first condition from the ordered list of conditions in the top group. -func getFirstCondition(g conditionGroups, priority []clusterv1.ConditionType) *localizedCondition { - topGroup := g.TopGroup() - if topGroup == nil { - return nil +func sortObj(i, j string, cpMachines sets.Set[string]) bool { + if cpMachines.Has(i) && !cpMachines.Has(j) { + return true + } + if !cpMachines.Has(i) && cpMachines.Has(j) { + return false } + return i < j +} - switch len(topGroup.conditions) { - case 0: - return nil - case 1: - return &topGroup.conditions[0] - default: - for _, p := range priority { - for _, c := range topGroup.conditions { - if c.Type == p { - return &c +var re = regexp.MustCompile(`\s*\*\s+`) + +func indentIfMultiline(m string) string { + msg := "" + // If it is a multiline string or if it start with a bullet, indent the message. + if strings.Contains(m, "\n") || re.MatchString(m) { + msg += "\n" + + // Split the message in lines, and add a prefix; prefix can be + // " " when indenting a line starting in a bullet + // " * " when indenting a line starting without a bullet (indent + add a bullet) + // " " when indenting a line starting with a bullet, but other lines required adding a bullet + lines := strings.Split(m, "\n") + prefix := " " + hasLinesWithoutBullet := false + for i := range lines { + if !re.MatchString(lines[i]) { + hasLinesWithoutBullet = true + break + } + } + for i, l := range lines { + prefix := prefix + if hasLinesWithoutBullet { + if !re.MatchString(lines[i]) { + prefix += "* " + } else { + prefix += " " } } + lines[i] = prefix + l } - return &topGroup.conditions[0] + msg += strings.Join(lines, "\n") + } else { + msg += " " + m } + return msg +} + +// getConditionsWithOwnerInfo return all the conditions from an object each one with the corresponding ConditionOwnerInfo. +func getConditionsWithOwnerInfo(obj Getter) []ConditionWithOwnerInfo { + ret := make([]ConditionWithOwnerInfo, 0, 10) + conditions := obj.GetConditions() + ownerInfo := getConditionOwnerInfo(obj) + for _, condition := range conditions { + ret = append(ret, ConditionWithOwnerInfo{ + OwnerResource: ownerInfo, + Condition: condition, + }) + } + return ret +} + +// getConditionOwnerInfo return the ConditionOwnerInfo for the given object. +// Note: Given that controller runtime often does not set typeMeta for objects, +// in case kind is missing we are falling back to the type name, which in most cases +// is the same as kind. +func getConditionOwnerInfo(obj any) ConditionOwnerInfo { + var kind, name string + var isControlPlaneMachine bool + if runtimeObject, ok := obj.(runtime.Object); ok { + kind = runtimeObject.GetObjectKind().GroupVersionKind().Kind + } + + if kind == "" { + t := reflect.TypeOf(obj) + if t.Kind() == reflect.Pointer { + kind = t.Elem().Name() + } else { + kind = t.Name() + } + } + + if objMeta, ok := obj.(objectWithNameAndLabels); ok { + name = objMeta.GetName() + if kind == "Machine" { + _, isControlPlaneMachine = objMeta.GetLabels()[clusterv1.MachineControlPlaneLabel] + } + } + + return ConditionOwnerInfo{ + Kind: kind, + Name: name, + IsControlPlaneMachine: isControlPlaneMachine, + } +} + +// objectWithNameAndLabels is a subset of metav1.Object. +type objectWithNameAndLabels interface { + GetName() string + GetLabels() map[string]string } diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/mirror.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/mirror.go similarity index 99% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/mirror.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/mirror.go index bbf5986fe079..ca756cfd2915 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/mirror.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/mirror.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta2 +package conditions import ( "fmt" diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/options.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/options.go similarity index 99% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/options.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/options.go index c212fb90089b..2e099031d7bd 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/options.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/options.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta2 +package conditions import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/patch.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/patch.go index 46eb0abda67f..867f8f302a27 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/patch.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/patch.go @@ -1,5 +1,5 @@ /* -Copyright 2020 The Kubernetes Authors. +Copyright 2024 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,25 +18,27 @@ package conditions import ( "reflect" + "sort" "github.com/google/go-cmp/cmp" "github.com/pkg/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" "sigs.k8s.io/cluster-api/util" ) // Patch defines a list of operations to change a list of conditions into another. type Patch []PatchOperation -// PatchOperation define an operation that changes a single condition. +// PatchOperation defines an operation that changes a single condition. type PatchOperation struct { - Before *clusterv1.Condition - After *clusterv1.Condition + Before *metav1.Condition + After *metav1.Condition Op PatchOperationType } -// PatchOperationType defines patch operation types. +// PatchOperationType defines a condition patch operation type. type PatchOperationType string const ( @@ -51,107 +53,108 @@ const ( ) // NewPatch returns the Patch required to align source conditions to after conditions. -func NewPatch(before Getter, after Getter) (Patch, error) { +func NewPatch(before, after Getter) (Patch, error) { var patch Patch if util.IsNil(before) { return nil, errors.New("error creating patch: before object is nil") } + beforeConditions := before.GetConditions() + if util.IsNil(after) { return nil, errors.New("error creating patch: after object is nil") } + afterConditions := after.GetConditions() // Identify AddCondition and ModifyCondition changes. - targetConditions := after.GetConditions() - for i := range targetConditions { - targetCondition := targetConditions[i] - currentCondition := Get(before, targetCondition.Type) - if currentCondition == nil { - patch = append(patch, PatchOperation{Op: AddConditionPatch, After: &targetCondition}) + for i := range afterConditions { + afterCondition := afterConditions[i] + beforeCondition := meta.FindStatusCondition(beforeConditions, afterCondition.Type) + if beforeCondition == nil { + patch = append(patch, PatchOperation{Op: AddConditionPatch, After: &afterCondition}) continue } - if !reflect.DeepEqual(&targetCondition, currentCondition) { - patch = append(patch, PatchOperation{Op: ChangeConditionPatch, After: &targetCondition, Before: currentCondition}) + if !reflect.DeepEqual(&afterCondition, beforeCondition) { + patch = append(patch, PatchOperation{Op: ChangeConditionPatch, After: &afterCondition, Before: beforeCondition}) } } // Identify RemoveCondition changes. - baseConditions := before.GetConditions() - for i := range baseConditions { - baseCondition := baseConditions[i] - targetCondition := Get(after, baseCondition.Type) - if targetCondition == nil { - patch = append(patch, PatchOperation{Op: RemoveConditionPatch, Before: &baseCondition}) + for i := range beforeConditions { + beforeCondition := beforeConditions[i] + afterCondition := meta.FindStatusCondition(afterConditions, beforeCondition.Type) + if afterCondition == nil { + patch = append(patch, PatchOperation{Op: RemoveConditionPatch, Before: &beforeCondition}) } } return patch, nil } -// applyOptions allows to set strategies for patch apply. -type applyOptions struct { - ownedConditions []clusterv1.ConditionType - forceOverwrite bool +// PatchApplyOption is some configuration that modifies options for a patch apply call. +type PatchApplyOption interface { + // ApplyToPatchApply applies this configuration to the given patch apply options. + ApplyToPatchApply(option *PatchApplyOptions) } -func (o *applyOptions) isOwnedCondition(t clusterv1.ConditionType) bool { - for _, i := range o.ownedConditions { - if i == t { - return true - } - } - return false +// PatchApplyOptions allows to set strategies for patch apply. +type PatchApplyOptions struct { + ownedConditionTypes []string + forceOverwrite bool + conditionSortFunc ConditionSortFunc } -// ApplyOption defines an option for applying a condition patch. -type ApplyOption func(*applyOptions) - -// WithOwnedConditions allows to define condition types owned by the controller. -// In case of conflicts for the owned conditions, the patch helper will always use the value provided by the controller. -func WithOwnedConditions(t ...clusterv1.ConditionType) ApplyOption { - return func(c *applyOptions) { - c.ownedConditions = t +// ApplyOptions applies the given list options on these options, +// and then returns itself (for convenient chaining). +func (o *PatchApplyOptions) ApplyOptions(opts []PatchApplyOption) *PatchApplyOptions { + for _, opt := range opts { + if util.IsNil(opt) { + continue + } + opt.ApplyToPatchApply(o) } + return o } -// WithForceOverwrite In case of conflicts for the owned conditions, the patch helper will always use the value provided by the controller. -func WithForceOverwrite(v bool) ApplyOption { - return func(c *applyOptions) { - c.forceOverwrite = v +func (o *PatchApplyOptions) isOwnedConditionType(conditionType string) bool { + for _, i := range o.ownedConditionTypes { + if i == conditionType { + return true + } } + return false } // Apply executes a three-way merge of a list of Patch. // When merge conflicts are detected (latest deviated from before in an incompatible way), an error is returned. -func (p Patch) Apply(latest Setter, options ...ApplyOption) error { +func (p Patch) Apply(latest Setter, opts ...PatchApplyOption) error { if p.IsZero() { return nil } if util.IsNil(latest) { - return errors.New("error patching conditions: latest object was nil") + return errors.New("error patching conditions: latest object is nil") } + latestConditions := latest.GetConditions() - applyOpt := &applyOptions{} - for _, o := range options { - if util.IsNil(o) { - return errors.New("error patching conditions: ApplyOption was nil") - } - o(applyOpt) + applyOpt := &PatchApplyOptions{ + // By default, sort conditions by the default condition order: available and ready always first, deleting and paused always last, all the other conditions in alphabetical order. + conditionSortFunc: defaultSortLessFunc, } + applyOpt.ApplyOptions(opts) for _, conditionPatch := range p { switch conditionPatch.Op { case AddConditionPatch: - // If the conditions is owned, always keep the after value. - if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.After.Type) { - Set(latest, conditionPatch.After) + // If the condition is owned, always keep the after value. + if applyOpt.forceOverwrite || applyOpt.isOwnedConditionType(conditionPatch.After.Type) { + setStatusCondition(&latestConditions, *conditionPatch.After) continue } // If the condition is already on latest, check if latest and after agree on the change; if not, this is a conflict. - if latestCondition := Get(latest, conditionPatch.After.Type); latestCondition != nil { - // If latest and after agree on the change, then it is a conflict. + if latestCondition := meta.FindStatusCondition(latestConditions, conditionPatch.After.Type); latestCondition != nil { + // If latest and after disagree on the change, then it is a conflict if !HasSameState(latestCondition, conditionPatch.After) { return errors.Errorf("error patching conditions: The condition %q was modified by a different process and this caused a merge/AddCondition conflict: %v", conditionPatch.After.Type, cmp.Diff(latestCondition, conditionPatch.After)) } @@ -160,16 +163,16 @@ func (p Patch) Apply(latest Setter, options ...ApplyOption) error { continue } // If the condition does not exists on the latest, add the new after condition. - Set(latest, conditionPatch.After) + setStatusCondition(&latestConditions, *conditionPatch.After) case ChangeConditionPatch: // If the conditions is owned, always keep the after value. - if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.After.Type) { - Set(latest, conditionPatch.After) + if applyOpt.forceOverwrite || applyOpt.isOwnedConditionType(conditionPatch.After.Type) { + setStatusCondition(&latestConditions, *conditionPatch.After) continue } - latestCondition := Get(latest, conditionPatch.After.Type) + latestCondition := meta.FindStatusCondition(latestConditions, conditionPatch.After.Type) // If the condition does not exist anymore on the latest, this is a conflict. if latestCondition == nil { @@ -187,26 +190,39 @@ func (p Patch) Apply(latest Setter, options ...ApplyOption) error { continue } // Otherwise apply the new after condition. - Set(latest, conditionPatch.After) + setStatusCondition(&latestConditions, *conditionPatch.After) case RemoveConditionPatch: + // If latestConditions is nil or empty, nothing to remove. + if len(latestConditions) == 0 { + continue + } + // If the conditions is owned, always keep the after value (condition should be deleted). - if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.Before.Type) { - Delete(latest, conditionPatch.Before.Type) + if applyOpt.forceOverwrite || applyOpt.isOwnedConditionType(conditionPatch.Before.Type) { + meta.RemoveStatusCondition(&latestConditions, conditionPatch.Before.Type) continue } // If the condition is still on the latest, check if it is changed in the meantime; // if so then this is a conflict. - if latestCondition := Get(latest, conditionPatch.Before.Type); latestCondition != nil { + if latestCondition := meta.FindStatusCondition(latestConditions, conditionPatch.Before.Type); latestCondition != nil { if !HasSameState(latestCondition, conditionPatch.Before) { return errors.Errorf("error patching conditions: The condition %q was modified by a different process and this caused a merge/RemoveCondition conflict: %v", conditionPatch.Before.Type, cmp.Diff(latestCondition, conditionPatch.Before)) } } // Otherwise the latest and after agreed on the delete operation, so there's nothing to change. - Delete(latest, conditionPatch.Before.Type) + meta.RemoveStatusCondition(&latestConditions, conditionPatch.Before.Type) } } + + if applyOpt.conditionSortFunc != nil { + sort.SliceStable(latestConditions, func(i, j int) bool { + return applyOpt.conditionSortFunc(latestConditions[i], latestConditions[j]) + }) + } + + latest.SetConditions(latestConditions) return nil } @@ -217,3 +233,22 @@ func (p Patch) IsZero() bool { } return len(p) == 0 } + +// HasSameState returns true if a condition has the same state of another; state is defined +// by the union of following fields: Type, Status, Reason, ObservedGeneration and Message (it excludes LastTransitionTime). +func HasSameState(i, j *metav1.Condition) bool { + return i.Type == j.Type && + i.Status == j.Status && + i.ObservedGeneration == j.ObservedGeneration && + i.Reason == j.Reason && + i.Message == j.Message +} + +// HasSameStateExceptObservedGeneration returns true if a condition has the same state of another; state is defined +// by the union of following fields: Type, Status, Reason and Message (it excludes ObservedGeneration and LastTransitionTime). +func HasSameStateExceptObservedGeneration(i, j *metav1.Condition) bool { + return i.Type == j.Type && + i.Status == j.Status && + i.Reason == j.Reason && + i.Message == j.Message +} diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/setter.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/setter.go index 8cea760581e5..376c2c0890bb 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/setter.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/setter.go @@ -1,5 +1,5 @@ /* -Copyright 2020 The Kubernetes Authors. +Copyright 2024 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,246 +17,112 @@ limitations under the License. package conditions import ( - "fmt" "sort" "time" - corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + "sigs.k8s.io/cluster-api/util" ) // Setter interface defines methods that a Cluster API object should implement in order to // use the conditions package for setting conditions. type Setter interface { Getter - SetConditions(clusterv1.Conditions) + + // SetConditions sets conditions for an API object. + SetConditions([]metav1.Condition) } -// Set sets the given condition. -// -// NOTE: If a condition already exists, the LastTransitionTime is updated only if a change is detected -// in any of the following fields: Status, Reason, Severity and Message. -func Set(to Setter, condition *clusterv1.Condition) { - if to == nil || condition == nil { - return - } +// SetOption is some configuration that modifies options for a Set request. +type SetOption interface { + // ApplyToSet applies this configuration to the given Set options. + ApplyToSet(option *SetOptions) +} - // Check if the new conditions already exists, and change it only if there is a status - // transition (otherwise we should preserve the current last transition time)- - conditions := to.GetConditions() - exists := false - for i := range conditions { - existingCondition := conditions[i] - if existingCondition.Type == condition.Type { - exists = true - if !HasSameState(&existingCondition, condition) { - condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) - conditions[i] = *condition - break - } - condition.LastTransitionTime = existingCondition.LastTransitionTime - break - } - } +// SetOptions allows to define options for the set operation. +type SetOptions struct { + conditionSortFunc ConditionSortFunc +} - // If the condition does not exist, add it, setting the transition time only if not already set - if !exists { - if condition.LastTransitionTime.IsZero() { - condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) - } - conditions = append(conditions, *condition) +// ApplyOptions applies the given list options on these options, +// and then returns itself (for convenient chaining). +func (o *SetOptions) ApplyOptions(opts []SetOption) *SetOptions { + for _, opt := range opts { + opt.ApplyToSet(o) } - - // Sorts conditions for convenience of the consumer, i.e. kubectl. - sort.Slice(conditions, func(i, j int) bool { - return lexicographicLess(&conditions[i], &conditions[j]) - }) - - to.SetConditions(conditions) + return o } -// SetWithCustomLastTransitionTime is similar to Set function which sets the given condition but following changes for LastTransitionTime. +// Set a condition on the given object implementing the Setter interface; if the object is nil, the operation is a no-op. +// +// When setting a condition: +// - condition.ObservedGeneration will be set to object.Metadata.Generation if targetObj is a metav1.Object. +// - If the condition does not exist and condition.LastTransitionTime is not set, time.Now is used. +// - If the condition already exists, condition.Status is changing and condition.LastTransitionTime is not set, time.Now is used. +// - If the condition already exists, condition.Status is NOT changing, all the fields can be changed except for condition.LastTransitionTime. // -// 1. if the condition of the specified type already exists (all fields of the existing condition are updated to -// new condition, LastTransitionTime is set to current time if unset and new status differs from the old status) -// 2. if a condition of the specified type does not exist (LastTransitionTime is set to current time if unset, and newCondition is appended) -func SetWithCustomLastTransitionTime(to Setter, condition *clusterv1.Condition) { - if to == nil || condition == nil { +// Additionally, Set enforces a default condition order (Available and Ready fist, everything else in alphabetical order), +// but this can be changed by using the ConditionSortFunc option. +// +// Please note that Set does not support setting conditions to an unstructured object nor to API types not implementing +// the Setter interface. Eventually, users can implement wrappers on those types implementing this interface and +// taking care of aligning the condition format if necessary. +func Set(targetObj Setter, condition metav1.Condition, opts ...SetOption) { + if util.IsNil(targetObj) { return } - // Check if the new conditions already exists, and change it only if there is a status - // transition (otherwise we should preserve the current last transition time)- - conditions := to.GetConditions() - exists := false - for i := range conditions { - existingCondition := conditions[i] - if existingCondition.Type == condition.Type { - exists = true - if !HasSameState(&existingCondition, condition) { - if existingCondition.Status != condition.Status { - if condition.LastTransitionTime.IsZero() { - condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) - } - } else { - condition.LastTransitionTime = existingCondition.LastTransitionTime - } - conditions[i] = *condition - } - break - } - } - - // If the condition does not exist, add it, setting the transition time only if not already set - if !exists { - if condition.LastTransitionTime.IsZero() { - condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) - } - conditions = append(conditions, *condition) + setOpt := &SetOptions{ + // By default, sort conditions by the default condition order: available and ready always first, deleting and paused always last, all the other conditions in alphabetical order. + conditionSortFunc: defaultSortLessFunc, } + setOpt.ApplyOptions(opts) - // Sorts conditions for convenience of the consumer, i.e. kubectl. - sort.Slice(conditions, func(i, j int) bool { - return lexicographicLess(&conditions[i], &conditions[j]) - }) - - to.SetConditions(conditions) -} - -// TrueCondition returns a condition with Status=True and the given type. -func TrueCondition(t clusterv1.ConditionType) *clusterv1.Condition { - return &clusterv1.Condition{ - Type: t, - Status: corev1.ConditionTrue, + if objMeta, ok := targetObj.(metav1.Object); ok { + condition.ObservedGeneration = objMeta.GetGeneration() } -} -// TrueConditionWithNegativePolarity returns a condition with negative polarity, Status=True and the given type (Status=True has a negative meaning). -func TrueConditionWithNegativePolarity(t clusterv1.ConditionType, reason string, severity clusterv1.ConditionSeverity, messageFormat string, messageArgs ...interface{}) *clusterv1.Condition { - return &clusterv1.Condition{ - Type: t, - Status: corev1.ConditionTrue, - Reason: reason, - Severity: severity, - Message: fmt.Sprintf(messageFormat, messageArgs...), + conditions := targetObj.GetConditions() + if changed := setStatusCondition(&conditions, condition); !changed { + return } -} -// FalseCondition returns a condition with Status=False and the given type. -func FalseCondition(t clusterv1.ConditionType, reason string, severity clusterv1.ConditionSeverity, messageFormat string, messageArgs ...interface{}) *clusterv1.Condition { - return &clusterv1.Condition{ - Type: t, - Status: corev1.ConditionFalse, - Reason: reason, - Severity: severity, - Message: fmt.Sprintf(messageFormat, messageArgs...), + if setOpt.conditionSortFunc != nil { + sort.SliceStable(conditions, func(i, j int) bool { + return setOpt.conditionSortFunc(conditions[i], conditions[j]) + }) } -} -// FalseConditionWithNegativePolarity returns a condition with negative polarity, Status=false and the given type (Status=False has a positive meaning). -func FalseConditionWithNegativePolarity(t clusterv1.ConditionType) *clusterv1.Condition { - return &clusterv1.Condition{ - Type: t, - Status: corev1.ConditionFalse, - } + targetObj.SetConditions(conditions) } -// UnknownCondition returns a condition with Status=Unknown and the given type. -func UnknownCondition(t clusterv1.ConditionType, reason string, messageFormat string, messageArgs ...interface{}) *clusterv1.Condition { - return &clusterv1.Condition{ - Type: t, - Status: corev1.ConditionUnknown, - Reason: reason, - Message: fmt.Sprintf(messageFormat, messageArgs...), +func setStatusCondition(conditions *[]metav1.Condition, condition metav1.Condition) bool { + // Truncate last transition time to seconds. + // This prevents inconsistencies from what we have in objects in memory and what Marshal/Unmarshal + // will do while the data is sent to/read from the API server. + if condition.LastTransitionTime.IsZero() { + condition.LastTransitionTime = metav1.Now() } -} - -// MarkTrue sets Status=True for the condition with the given type. -func MarkTrue(to Setter, t clusterv1.ConditionType) { - Set(to, TrueCondition(t)) -} - -// MarkTrueWithNegativePolarity sets Status=True for a condition with negative polarity and the given type (Status=True has a negative meaning). -func MarkTrueWithNegativePolarity(to Setter, t clusterv1.ConditionType, reason string, severity clusterv1.ConditionSeverity, messageFormat string, messageArgs ...interface{}) { - Set(to, TrueConditionWithNegativePolarity(t, reason, severity, messageFormat, messageArgs...)) -} - -// MarkUnknown sets Status=Unknown for the condition with the given type. -func MarkUnknown(to Setter, t clusterv1.ConditionType, reason, messageFormat string, messageArgs ...interface{}) { - Set(to, UnknownCondition(t, reason, messageFormat, messageArgs...)) -} - -// MarkFalse sets Status=False for the condition with the given type. -func MarkFalse(to Setter, t clusterv1.ConditionType, reason string, severity clusterv1.ConditionSeverity, messageFormat string, messageArgs ...interface{}) { - Set(to, FalseCondition(t, reason, severity, messageFormat, messageArgs...)) -} - -// MarkFalseWithNegativePolarity sets Status=False for a condition with negative polarity and the given type (Status=False has a positive meaning). -func MarkFalseWithNegativePolarity(to Setter, t clusterv1.ConditionType) { - Set(to, FalseConditionWithNegativePolarity(t)) -} - -// SetSummary sets a Ready condition with the summary of all the conditions existing -// on an object. If the object does not have other conditions, no summary condition is generated. -func SetSummary(to Setter, options ...MergeOption) { - Set(to, summary(to, options...)) -} - -// SetMirror creates a new condition by mirroring the Ready condition from a dependent object; -// if the Ready condition does not exist in the source object, no target conditions is generated. -func SetMirror(to Setter, targetCondition clusterv1.ConditionType, from Getter, options ...MirrorOptions) { - Set(to, mirror(from, targetCondition, options...)) -} - -// SetAggregate creates a new condition with the aggregation of all the Ready condition -// from a list of dependent objects; if the Ready condition does not exist in one of the source object, -// the object is excluded from the aggregation; if none of the source object have ready condition, -// no target conditions is generated. -func SetAggregate(to Setter, targetCondition clusterv1.ConditionType, from []Getter, options ...MergeOption) { - Set(to, aggregate(from, targetCondition, options...)) + condition.LastTransitionTime.Time = condition.LastTransitionTime.Truncate(1 * time.Second) + return meta.SetStatusCondition(conditions, condition) } // Delete deletes the condition with the given type. -func Delete(to Setter, t clusterv1.ConditionType) { +func Delete(to Setter, conditionType string) { if to == nil { return } conditions := to.GetConditions() - newConditions := make(clusterv1.Conditions, 0, len(conditions)) + // allocate same length array because the conditions length might be 0 + // or the condition to be deleted might not be part of the list. + newConditions := make([]metav1.Condition, 0, len(conditions)) for _, condition := range conditions { - if condition.Type != t { + if condition.Type != conditionType { newConditions = append(newConditions, condition) } } to.SetConditions(newConditions) } - -// lexicographicLess returns true if a condition is less than another in regard to -// the order of conditions designed for convenience of the consumer, i.e. kubectl. -// According to this order the Ready condition always goes first, followed by all the other -// conditions sorted by Type. -func lexicographicLess(i, j *clusterv1.Condition) bool { - if i == nil { - return true - } - if j == nil { - return false - } - return (i.Type == clusterv1.ReadyCondition || i.Type < j.Type) && j.Type != clusterv1.ReadyCondition -} - -// HasSameState returns true if a condition has the same state of another; state is defined -// by the union of following fields: Type, Status, Reason, Severity and Message (it excludes LastTransitionTime). -func HasSameState(i, j *clusterv1.Condition) bool { - if i == nil || j == nil { - return i == j - } - return i.Type == j.Type && - i.Status == j.Status && - i.Reason == j.Reason && - i.Severity == j.Severity && - i.Message == j.Message -} diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/sort.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/sort.go similarity index 65% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/sort.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/sort.go index f48a03b8983d..d0be13af9e30 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/sort.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/sort.go @@ -14,12 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta2 +package conditions import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) var orderMap = map[string]int{} @@ -94,42 +94,42 @@ func defaultSortLessFunc(i, j metav1.Condition) bool { // | Deleting | x | x | x | x | x | x | // . var order = []string{ - clusterv1.AvailableV1Beta2Condition, - clusterv1.ReadyV1Beta2Condition, - clusterv1.MachineUpToDateV1Beta2Condition, - clusterv1.ClusterRemoteConnectionProbeV1Beta2Condition, - clusterv1.BootstrapConfigReadyV1Beta2Condition, - clusterv1.InfrastructureReadyV1Beta2Condition, - clusterv1.ClusterControlPlaneInitializedV1Beta2Condition, - clusterv1.ClusterControlPlaneAvailableV1Beta2Condition, - clusterv1.ClusterWorkersAvailableV1Beta2Condition, - kubeadmControlPlaneCertificatesAvailableV1Beta2Condition, - kubeadmControlPlaneInitializedV1Beta2Condition, - kubeadmControlPlaneEtcdClusterHealthyV1Beta2Condition, - kubeadmControlPlaneControlPlaneComponentsHealthyV1Beta2Condition, - clusterv1.MachineNodeHealthyV1Beta2Condition, - clusterv1.MachineNodeReadyV1Beta2Condition, - kubeadmControlPlaneMachineEtcdPodHealthyV1Beta2Condition, - kubeadmControlPlaneMachineEtcdMemberHealthyV1Beta2Condition, - kubeadmControlPlaneMachineAPIServerPodHealthyV1Beta2Condition, - kubeadmControlPlaneMachineControllerManagerPodHealthyV1Beta2Condition, - kubeadmControlPlaneMachineSchedulerPodHealthyV1Beta2Condition, - clusterv1.MachineHealthCheckSucceededV1Beta2Condition, - clusterv1.MachineOwnerRemediatedV1Beta2Condition, - clusterv1.ClusterTopologyReconciledV1Beta2Condition, - clusterv1.RollingOutV1Beta2Condition, - clusterv1.RemediatingV1Beta2Condition, - clusterv1.ScalingDownV1Beta2Condition, - clusterv1.ScalingUpV1Beta2Condition, - clusterv1.MachinesReadyV1Beta2Condition, - clusterv1.ClusterControlPlaneMachinesReadyV1Beta2Condition, - clusterv1.ClusterWorkerMachinesReadyV1Beta2Condition, - clusterv1.MachinesUpToDateV1Beta2Condition, - clusterv1.ClusterControlPlaneMachinesUpToDateV1Beta2Condition, - clusterv1.ClusterWorkerMachinesUpToDateV1Beta2Condition, + clusterv1.AvailableCondition, + clusterv1.ReadyCondition, + clusterv1.MachineUpToDateCondition, + clusterv1.ClusterRemoteConnectionProbeCondition, + clusterv1.BootstrapConfigReadyCondition, + clusterv1.InfrastructureReadyCondition, + clusterv1.ClusterControlPlaneInitializedCondition, + clusterv1.ClusterControlPlaneAvailableCondition, + clusterv1.ClusterWorkersAvailableCondition, + kubeadmControlPlaneCertificatesAvailableCondition, + kubeadmControlPlaneInitializedCondition, + kubeadmControlPlaneEtcdClusterHealthyCondition, + kubeadmControlPlaneControlPlaneComponentsHealthyCondition, + clusterv1.MachineNodeHealthyCondition, + clusterv1.MachineNodeReadyCondition, + kubeadmControlPlaneMachineEtcdPodHealthyCondition, + kubeadmControlPlaneMachineEtcdMemberHealthyCondition, + kubeadmControlPlaneMachineAPIServerPodHealthyCondition, + kubeadmControlPlaneMachineControllerManagerPodHealthyCondition, + kubeadmControlPlaneMachineSchedulerPodHealthyCondition, + clusterv1.MachineHealthCheckSucceededCondition, + clusterv1.MachineOwnerRemediatedCondition, + clusterv1.ClusterTopologyReconciledCondition, + clusterv1.RollingOutCondition, + clusterv1.RemediatingCondition, + clusterv1.ScalingDownCondition, + clusterv1.ScalingUpCondition, + clusterv1.MachinesReadyCondition, + clusterv1.ClusterControlPlaneMachinesReadyCondition, + clusterv1.ClusterWorkerMachinesReadyCondition, + clusterv1.MachinesUpToDateCondition, + clusterv1.ClusterControlPlaneMachinesUpToDateCondition, + clusterv1.ClusterWorkerMachinesUpToDateCondition, readinessAndAvailabilityGates, - clusterv1.PausedV1Beta2Condition, - clusterv1.DeletingV1Beta2Condition, + clusterv1.PausedCondition, + clusterv1.DeletingCondition, } // Constants defining a placeholder for readiness and availability gates. @@ -139,13 +139,13 @@ const ( // Constants inlined for ordering (we want to avoid importing the KCP API package). const ( - kubeadmControlPlaneCertificatesAvailableV1Beta2Condition = "CertificatesAvailable" - kubeadmControlPlaneInitializedV1Beta2Condition = "Initialized" - kubeadmControlPlaneEtcdClusterHealthyV1Beta2Condition = "EtcdClusterHealthy" - kubeadmControlPlaneControlPlaneComponentsHealthyV1Beta2Condition = "ControlPlaneComponentsHealthy" - kubeadmControlPlaneMachineAPIServerPodHealthyV1Beta2Condition = "APIServerPodHealthy" - kubeadmControlPlaneMachineControllerManagerPodHealthyV1Beta2Condition = "ControllerManagerPodHealthy" - kubeadmControlPlaneMachineSchedulerPodHealthyV1Beta2Condition = "SchedulerPodHealthy" - kubeadmControlPlaneMachineEtcdPodHealthyV1Beta2Condition = "EtcdPodHealthy" - kubeadmControlPlaneMachineEtcdMemberHealthyV1Beta2Condition = "EtcdMemberHealthy" + kubeadmControlPlaneCertificatesAvailableCondition = "CertificatesAvailable" + kubeadmControlPlaneInitializedCondition = "Initialized" + kubeadmControlPlaneEtcdClusterHealthyCondition = "EtcdClusterHealthy" + kubeadmControlPlaneControlPlaneComponentsHealthyCondition = "ControlPlaneComponentsHealthy" + kubeadmControlPlaneMachineAPIServerPodHealthyCondition = "APIServerPodHealthy" + kubeadmControlPlaneMachineControllerManagerPodHealthyCondition = "ControllerManagerPodHealthy" + kubeadmControlPlaneMachineSchedulerPodHealthyCondition = "SchedulerPodHealthy" + kubeadmControlPlaneMachineEtcdPodHealthyCondition = "EtcdPodHealthy" + kubeadmControlPlaneMachineEtcdMemberHealthyCondition = "EtcdMemberHealthy" ) diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/summary.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/summary.go similarity index 99% rename from vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/summary.go rename to vendor/sigs.k8s.io/cluster-api/util/conditions/summary.go index beb5fd461a71..78ea1ab0c4e9 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/summary.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conditions/summary.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1beta2 +package conditions import ( "github.com/pkg/errors" diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/doc.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/doc.go deleted file mode 100644 index ba311f8aa18c..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/doc.go +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Package v1beta2 implements utils for metav1.Conditions that will be used starting with the v1beta2 API. -// -// Please note that in order to make this change while respecting API deprecation rules, it is required -// to go through a phased approach: -// - Phase 1. metav1.Conditions will be added into v1beta1 API types under the Status.V1Beta2.Conditions struct (clusterv1.Conditions will remain in Status.Conditions) -// - Phase 2. when introducing v1beta2 API types: -// - clusterv1.Conditions will be moved from Status.Conditions to Status.Deprecated.V1Beta1.Conditions -// - metav1.Conditions will be moved from Status.V1Beta2.Conditions to Status.Conditions -// -// - Phase 3. when removing v1beta1 API types, Status.Deprecated will be dropped. -// -// Please see the proposal https://github.com/kubernetes-sigs/cluster-api/tree/main/docs/proposals/20240916-improve-status-in-CAPI-resources.md for more details. -// -// In order to make this transition easier both for CAPI and other projects using this package, -// utils automatically adapt to handle objects at different stage of the transition. -package v1beta2 diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/getter.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/getter.go deleted file mode 100644 index f76b9c0880e1..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/getter.go +++ /dev/null @@ -1,236 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta2 - -import ( - "github.com/pkg/errors" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - - "sigs.k8s.io/cluster-api/util" -) - -// TODO: Move to the API package. -const ( - // NoReasonReported identifies a clusterv1.Condition that reports no reason. - NoReasonReported = "NoReasonReported" -) - -// Getter interface defines methods that an API object should implement in order to -// use the conditions package for getting conditions. -type Getter interface { - // GetV1Beta2Conditions returns the list of conditions for a cluster API object. - // Note: GetV1Beta2Conditions will be renamed to GetConditions in a later stage of the transition to V1Beta2. - GetV1Beta2Conditions() []metav1.Condition -} - -// Get returns a condition from the object implementing the Getter interface. -// -// Please note that Get does not support reading conditions from unstructured objects nor from API types not implementing -// the Getter interface. Eventually, users can implement wrappers on those types implementing this interface and -// taking care of aligning the condition format if necessary. -func Get(sourceObj Getter, sourceConditionType string) *metav1.Condition { - // if obj is nil, the requested condition does not exist. - if util.IsNil(sourceObj) { - return nil - } - - // Otherwise get the requested condition. - return meta.FindStatusCondition(sourceObj.GetV1Beta2Conditions(), sourceConditionType) -} - -// Has returns true if a condition with the given type exists. -func Has(from Getter, conditionType string) bool { - return Get(from, conditionType) != nil -} - -// IsTrue is true if the condition with the given type is True, otherwise it returns false -// if the condition is not True or if the condition does not exist (is nil). -func IsTrue(from Getter, conditionType string) bool { - if c := Get(from, conditionType); c != nil { - return c.Status == metav1.ConditionTrue - } - return false -} - -// IsFalse is true if the condition with the given type is False, otherwise it returns false -// if the condition is not False or if the condition does not exist (is nil). -func IsFalse(from Getter, conditionType string) bool { - if c := Get(from, conditionType); c != nil { - return c.Status == metav1.ConditionFalse - } - return false -} - -// IsUnknown is true if the condition with the given type is Unknown or if the condition -// does not exist (is nil). -func IsUnknown(from Getter, conditionType string) bool { - if c := Get(from, conditionType); c != nil { - return c.Status == metav1.ConditionUnknown - } - return true -} - -// UnstructuredGetAll returns conditions from an Unstructured object. -// -// UnstructuredGetAll supports retrieving conditions from objects at different stages of the transition from -// clusterv1.conditions to the metav1.Condition type: -// - Objects with clusterv1.Conditions in status.conditions; in this case a best effort conversion -// to metav1.Condition is performed, just enough to allow surfacing a condition from a provider object with Mirror -// - Objects with metav1.Condition in status.v1beta2.conditions -// - Objects with metav1.Condition in status.conditions -func UnstructuredGetAll(sourceObj runtime.Unstructured) ([]metav1.Condition, error) { - if util.IsNil(sourceObj) { - return nil, errors.New("sourceObj is nil") - } - - ownerInfo := getConditionOwnerInfo(sourceObj) - - value, exists, err := unstructured.NestedFieldNoCopy(sourceObj.UnstructuredContent(), "status", "v1beta2", "conditions") - if exists && err == nil { - if conditions, ok := value.([]interface{}); ok { - r, err := convertFromUnstructuredConditions(conditions) - if err != nil { - return nil, errors.Wrapf(err, "failed to convert status.v1beta2.conditions from %s to []metav1.Condition", ownerInfo.Kind) - } - return r, nil - } - } - - value, exists, err = unstructured.NestedFieldNoCopy(sourceObj.UnstructuredContent(), "status", "conditions") - if exists && err == nil { - if conditions, ok := value.([]interface{}); ok { - r, err := convertFromUnstructuredConditions(conditions) - if err != nil { - return nil, errors.Wrapf(err, "failed to convert status.conditions from %s to []metav1.Condition", ownerInfo.Kind) - } - return r, nil - } - } - - // With unstructured, it is not possible to detect if conditions are not set if the type is wrongly defined. - // This methods assume condition are not set. - return nil, nil -} - -// UnstructuredGet returns a condition from an Unstructured object. -// -// UnstructuredGet supports retrieving conditions from objects at different stages of the transition from -// clusterv1.conditions to the metav1.Condition type: -// - Objects with clusterv1.Conditions in status.conditions; in this case a best effort conversion -// to metav1.Condition is performed, just enough to allow surfacing a condition from a provider object with Mirror -// - Objects with metav1.Condition in status.v1beta2.conditions -// - Objects with metav1.Condition in status.conditions -func UnstructuredGet(sourceObj runtime.Unstructured, sourceConditionType string) (*metav1.Condition, error) { - r, err := UnstructuredGetAll(sourceObj) - if err != nil { - return nil, err - } - return meta.FindStatusCondition(r, sourceConditionType), nil -} - -// convertFromUnstructuredConditions converts []interface{} to []metav1.Condition; this operation must account for -// objects which are not transitioning to metav1.Condition, or not yet fully transitioned, and thus a best -// effort conversion of values to metav1.Condition is performed. -func convertFromUnstructuredConditions(conditions []interface{}) ([]metav1.Condition, error) { - if conditions == nil { - return nil, nil - } - - convertedConditions := make([]metav1.Condition, 0, len(conditions)) - for _, c := range conditions { - cMap, ok := c.(map[string]interface{}) - if !ok || cMap == nil { - continue - } - - var conditionType string - if v, ok := cMap["type"]; ok { - conditionType = v.(string) - } - - var status string - if v, ok := cMap["status"]; ok { - status = v.(string) - } - - var observedGeneration int64 - if v, ok := cMap["observedGeneration"]; ok { - observedGeneration = v.(int64) - } - - var lastTransitionTime metav1.Time - if v, ok := cMap["lastTransitionTime"]; ok && v != nil && v.(string) != "" { - if err := lastTransitionTime.UnmarshalQueryParameter(v.(string)); err != nil { - return nil, errors.Wrapf(err, "failed to unmarshal lastTransitionTime value: %s", v) - } - } - - var reason string - if v, ok := cMap["reason"]; ok { - reason = v.(string) - } - - var message string - if v, ok := cMap["message"]; ok { - message = v.(string) - } - - c := metav1.Condition{ - Type: conditionType, - Status: metav1.ConditionStatus(status), - ObservedGeneration: observedGeneration, - LastTransitionTime: lastTransitionTime, - Reason: reason, - Message: message, - } - if err := validateAndFixConvertedCondition(&c); err != nil { - return nil, err - } - - convertedConditions = append(convertedConditions, c) - } - return convertedConditions, nil -} - -// validateAndFixConvertedCondition validates and fixes a clusterv1.Condition converted to a metav1.Condition. -// this operation assumes conditions have been set using Cluster API condition utils; -// also, only a few, minimal rules are enforced, just enough to allow surfacing a condition from a providers object with Mirror. -func validateAndFixConvertedCondition(c *metav1.Condition) error { - if c.Type == "" { - return errors.New("type must be set for all conditions") - } - if c.Status == "" { - return errors.Errorf("status must be set for the %s condition", c.Type) - } - switch c.Status { - case metav1.ConditionFalse, metav1.ConditionTrue, metav1.ConditionUnknown: - break - default: - return errors.Errorf("status for the %s condition must be one of %s, %s, %s", c.Type, metav1.ConditionTrue, metav1.ConditionFalse, metav1.ConditionUnknown) - } - if c.Reason == "" { - c.Reason = NoReasonReported - } - - // NOTE: Empty LastTransitionTime is tolerated because it will be set when assigning the newly generated mirror condition to an object. - // NOTE: Other metav1.Condition validations rules, e.g. regex, are not enforced at this stage; they will be enforced by the API server at a later stage. - - return nil -} diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/merge_strategies.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/merge_strategies.go deleted file mode 100644 index 1d45e6c271ca..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/merge_strategies.go +++ /dev/null @@ -1,650 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta2 - -import ( - "fmt" - "reflect" - "regexp" - "sort" - "strings" - - "github.com/gobuffalo/flect" - "github.com/pkg/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/sets" - - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" -) - -// ConditionWithOwnerInfo is a wrapper around metav1.Condition with additional ConditionOwnerInfo. -// These infos can be used when generating the message resulting from the merge operation. -type ConditionWithOwnerInfo struct { - OwnerResource ConditionOwnerInfo - metav1.Condition -} - -// ConditionOwnerInfo contains infos about the object that owns the condition. -type ConditionOwnerInfo struct { - Kind string - Name string - IsControlPlaneMachine bool -} - -// String returns a string representation of the ConditionOwnerInfo. -func (o ConditionOwnerInfo) String() string { - return fmt.Sprintf("%s %s", o.Kind, o.Name) -} - -// MergeOperation defines merge operations. -type MergeOperation string - -const ( - // SummaryMergeOperation defines a merge operation of type Summary. - // Summary should merge different conditions from the same object. - SummaryMergeOperation MergeOperation = "Summary" - - // AggregateMergeOperation defines a merge operation of type Aggregate. - // Aggregate should merge the same condition across many objects. - AggregateMergeOperation MergeOperation = "Aggregate" -) - -// MergeStrategy defines a strategy used to merge conditions during the aggregate or summary operation. -type MergeStrategy interface { - // Merge passed in conditions. - // - // It is up to the caller to ensure that all the expected conditions exist (e.g. by adding new conditions with status Unknown). - // Conditions passed in must be of the given conditionTypes (other condition types must be discarded). - // - // The list of conditionTypes has an implicit order; it is up to the implementation of merge to use this info or not. - Merge(operation MergeOperation, conditions []ConditionWithOwnerInfo, conditionTypes []string) (status metav1.ConditionStatus, reason, message string, err error) -} - -// DefaultMergeStrategyOption is some configuration that modifies the DefaultMergeStrategy behaviour. -type DefaultMergeStrategyOption interface { - // ApplyToDefaultMergeStrategy applies this configuration to the given DefaultMergeStrategy options. - ApplyToDefaultMergeStrategy(option *DefaultMergeStrategyOptions) -} - -// DefaultMergeStrategyOptions allows to set options for the DefaultMergeStrategy behaviour. -type DefaultMergeStrategyOptions struct { - getPriorityFunc func(condition metav1.Condition) MergePriority - targetConditionHasPositivePolarity bool - computeReasonFunc func(issueConditions []ConditionWithOwnerInfo, unknownConditions []ConditionWithOwnerInfo, infoConditions []ConditionWithOwnerInfo) string - summaryMessageTransformFunc func([]string) []string -} - -// ApplyOptions applies the given list options on these options, -// and then returns itself (for convenient chaining). -func (o *DefaultMergeStrategyOptions) ApplyOptions(opts []DefaultMergeStrategyOption) *DefaultMergeStrategyOptions { - for _, opt := range opts { - opt.ApplyToDefaultMergeStrategy(o) - } - return o -} - -// DefaultMergeStrategy returns the default merge strategy. -// -// Use the GetPriorityFunc option to customize how the MergePriority for a given condition is computed. -// If not specified, conditions are considered issues or not if not to their normal state given the polarity -// (e.g. a positive polarity condition is considered to be reporting an issue when status is false, -// otherwise the condition is considered to be reporting an info unless status is unknown). -// -// Use the TargetConditionHasPositivePolarity to define the polarity of the condition returned by the DefaultMergeStrategy. -// If not specified, the generate condition will have positive polarity (status true = good). -// -// Use the ComputeReasonFunc to customize how the reason for the resulting condition will be computed. -// If not specified, generic reasons will be used. -func DefaultMergeStrategy(opts ...DefaultMergeStrategyOption) MergeStrategy { - strategyOpt := &DefaultMergeStrategyOptions{ - targetConditionHasPositivePolarity: true, - computeReasonFunc: GetDefaultComputeMergeReasonFunc(issuesReportedReason, unknownReportedReason, infoReportedReason), // NOTE: when no specific reason are provided, generic ones are used. - getPriorityFunc: GetDefaultMergePriorityFunc(), - summaryMessageTransformFunc: nil, - } - strategyOpt.ApplyOptions(opts) - - return &defaultMergeStrategy{ - getPriorityFunc: strategyOpt.getPriorityFunc, - computeReasonFunc: strategyOpt.computeReasonFunc, - targetConditionHasPositivePolarity: strategyOpt.targetConditionHasPositivePolarity, - summaryMessageTransformFunc: strategyOpt.summaryMessageTransformFunc, - } -} - -// GetDefaultMergePriorityFunc returns the merge priority for each condition. -// It assigns following priority values to conditions: -// - issues: conditions with positive polarity (normal True) and status False or conditions with negative polarity (normal False) and status True. -// - unknown: conditions with status unknown. -// - info: conditions with positive polarity (normal True) and status True or conditions with negative polarity (normal False) and status False. -func GetDefaultMergePriorityFunc(negativePolarityConditionTypes ...string) func(condition metav1.Condition) MergePriority { - negativePolarityConditionTypesSet := sets.New[string](negativePolarityConditionTypes...) - return func(condition metav1.Condition) MergePriority { - switch condition.Status { - case metav1.ConditionTrue: - if negativePolarityConditionTypesSet.Has(condition.Type) { - return IssueMergePriority - } - return InfoMergePriority - case metav1.ConditionFalse: - if negativePolarityConditionTypesSet.Has(condition.Type) { - return InfoMergePriority - } - return IssueMergePriority - case metav1.ConditionUnknown: - return UnknownMergePriority - } - - // Note: this should never happen. In case, those conditions are considered like conditions with unknown status. - return UnknownMergePriority - } -} - -// MergePriority defines the priority for a condition during a merge operation. -type MergePriority uint8 - -const ( - // IssueMergePriority is the merge priority used by GetDefaultMergePriority in case the condition state is considered an issue. - IssueMergePriority MergePriority = iota - - // UnknownMergePriority is the merge priority used by GetDefaultMergePriority in case of unknown conditions. - UnknownMergePriority - - // InfoMergePriority is the merge priority used by GetDefaultMergePriority in case the condition state is not considered an issue. - InfoMergePriority -) - -// GetDefaultComputeMergeReasonFunc return a function picking one of the three reasons in input depending on -// the status of the conditions being merged. -func GetDefaultComputeMergeReasonFunc(issueReason, unknownReason, infoReason string) func(issueConditions []ConditionWithOwnerInfo, unknownConditions []ConditionWithOwnerInfo, infoConditions []ConditionWithOwnerInfo) string { - return func(issueConditions []ConditionWithOwnerInfo, unknownConditions []ConditionWithOwnerInfo, _ []ConditionWithOwnerInfo) string { - switch { - case len(issueConditions) > 0: - return issueReason - case len(unknownConditions) > 0: - return unknownReason - default: - // Note: This func can assume that there is at least one condition, so this branch is equivalent to len(infoReason) > 0, - // and it makes the linter happy. - return infoReason - } - } -} - -const ( - // issuesReportedReason is set on conditions generated during aggregate or summary operations when at least one conditions/objects are reporting issues. - // NOTE: This const is used by GetDefaultComputeMergeReasonFunc if no specific reasons are provided. - issuesReportedReason = "IssuesReported" - - // unknownReportedReason is set on conditions generated during aggregate or summary operations when at least one conditions/objects are reporting unknown. - // NOTE: This const is used by GetDefaultComputeMergeReasonFunc if no specific reasons are provided. - unknownReportedReason = "UnknownReported" - - // infoReportedReason is set on conditions generated during aggregate or summary operations when at least one conditions/objects are reporting info. - // NOTE: This const is used by GetDefaultComputeMergeReasonFunc if no specific reasons are provided. - infoReportedReason = "InfoReported" -) - -// defaultMergeStrategy defines the default merge strategy for Cluster API conditions. -type defaultMergeStrategy struct { - getPriorityFunc func(condition metav1.Condition) MergePriority - targetConditionHasPositivePolarity bool - computeReasonFunc func(issueConditions []ConditionWithOwnerInfo, unknownConditions []ConditionWithOwnerInfo, infoConditions []ConditionWithOwnerInfo) string - summaryMessageTransformFunc func([]string) []string -} - -// Merge all conditions in input based on a strategy that surfaces issues first, then unknown conditions, then info (if none of issues and unknown condition exists). -// - issues: conditions with positive polarity (normal True) and status False or conditions with negative polarity (normal False) and status True. -// - unknown: conditions with status unknown. -// - info: conditions with positive polarity (normal True) and status True or conditions with negative polarity (normal False) and status False. -func (d *defaultMergeStrategy) Merge(operation MergeOperation, conditions []ConditionWithOwnerInfo, conditionTypes []string) (status metav1.ConditionStatus, reason, message string, err error) { - if len(conditions) == 0 { - return "", "", "", errors.New("can't merge an empty list of conditions") - } - - if d.getPriorityFunc == nil { - return "", "", "", errors.New("can't merge without a getPriority func") - } - - // sortConditions the relevance defined by the users (the order of condition types), LastTransition time (older first). - sortConditions(conditions, conditionTypes) - - issueConditions, unknownConditions, infoConditions := splitConditionsByPriority(conditions, d.getPriorityFunc) - - // Compute the status for the target condition: - // Note: This function always returns a condition with positive polarity. - // - if there are issues, use false - // - else if there are unknown, use unknown - // - else if there are info, use true - switch { - case len(issueConditions) > 0: - if d.targetConditionHasPositivePolarity { - status = metav1.ConditionFalse - } else { - status = metav1.ConditionTrue - } - case len(unknownConditions) > 0: - status = metav1.ConditionUnknown - case len(infoConditions) > 0: - if d.targetConditionHasPositivePolarity { - status = metav1.ConditionTrue - } else { - status = metav1.ConditionFalse - } - default: - // NOTE: this is already handled above, but repeating also here for better readability. - return "", "", "", errors.New("can't merge an empty list of conditions") - } - - // Compute the reason for the target condition: - // - In case there is only one condition in the top group, use the reason from this condition - // - In case there are more than one condition in the top group, use a generic reason (for the target group) - reason = d.computeReasonFunc(issueConditions, unknownConditions, infoConditions) - - // Compute the message for the target condition, which is optimized for the operation being performed. - - // When performing the summary operation, usually we are merging a small set of conditions from the same object, - // Considering the small number of conditions, involved it is acceptable/preferred to provide as much detail - // as possible about the messages from the conditions being merged. - // - // Accordingly, the resulting message is composed by all the messages from conditions classified as issues/unknown; - // messages from conditions classified as info are included only if there are no issues/unknown. - // - // e.g. Condition-B (False): Message-B; Condition-!C (True): Message-!C; Condition-A (Unknown): Message-A - // - // When including messages from conditions, they are sorted by issue/unknown and by the implicit order of condition types - // provided by the user (it is considered as order of relevance). - if operation == SummaryMergeOperation { - message = summaryMessage(conditions, d, status) - } - - // When performing the aggregate operation, we are merging one single condition from potentially many objects. - // Considering the high number of conditions involved, the messages from the conditions being merged must be filtered/summarized - // using rules designed to surface the most important issues. - // - // Accordingly, the resulting message is composed by only three messages from conditions classified as issues/unknown; - // instead three messages from conditions classified as info are included only if there are no issues/unknown. - // - // Three criteria are used to pick the messages to be shown - // - Messages for control plane machines always go first - // - Messages for issues always go before messages for unknown, info messages goes last - // - The number of objects reporting the same message determine the order used to pick within the messages in the same bucket - // - // For each message it is reported a list of max 3 objects reporting the message; if more objects are reporting the same - // message, the number of those objects is surfaced. - // - // e.g. (False): Message-1 from obj0, obj1, obj2 and 2 more Objects - // - // If there are other objects - objects not included in the list above - reporting issues/unknown (or info there no issues/unknown), - // the number of those objects is surfaced. - // - // e.g. ...; 2 more Objects with issues; 1 more Objects with unknown status - // - if operation == AggregateMergeOperation { - n := 3 - messages := []string{} - - // Get max n issue/unknown messages, decrement n, and track if there are other objects reporting issues/unknown not included in the messages. - if len(issueConditions) > 0 || len(unknownConditions) > 0 { - issueMessages := aggregateMessages(append(issueConditions, unknownConditions...), &n, false, d.getPriorityFunc, map[MergePriority]string{IssueMergePriority: "with other issues", UnknownMergePriority: "with status unknown"}) - messages = append(messages, issueMessages...) - } - - // Only if there are no issue or unknown, - // Get max n info messages, decrement n, and track if there are other objects reporting info not included in the messages. - if len(issueConditions) == 0 && len(unknownConditions) == 0 && len(infoConditions) > 0 { - infoMessages := aggregateMessages(infoConditions, &n, true, d.getPriorityFunc, map[MergePriority]string{InfoMergePriority: "with additional info"}) - messages = append(messages, infoMessages...) - } - - message = strings.Join(messages, "\n") - } - - return status, reason, message, nil -} - -// sortConditions by condition types order, LastTransitionTime -// (the order of relevance defined by the users, the oldest first). -func sortConditions(conditions []ConditionWithOwnerInfo, orderedConditionTypes []string) { - conditionOrder := make(map[string]int, len(orderedConditionTypes)) - for i, conditionType := range orderedConditionTypes { - conditionOrder[conditionType] = i - } - - sort.SliceStable(conditions, func(i, j int) bool { - // Sort by condition order (user defined, useful when computing summary of different conditions from the same object) - return conditionOrder[conditions[i].Type] < conditionOrder[conditions[j].Type] || - // If same condition order, sort by last transition time (useful when computing aggregation of the same conditions from different objects) - (conditionOrder[conditions[i].Type] == conditionOrder[conditions[j].Type] && conditions[i].LastTransitionTime.Before(&conditions[j].LastTransitionTime)) - }) -} - -// splitConditionsByPriority split conditions in 3 groups: -// - conditions representing an issue. -// - conditions with status unknown. -// - conditions representing an info. -// NOTE: The order of conditions is preserved in each group. -func splitConditionsByPriority(conditions []ConditionWithOwnerInfo, getPriority func(condition metav1.Condition) MergePriority) (issueConditions, unknownConditions, infoConditions []ConditionWithOwnerInfo) { - for _, condition := range conditions { - switch getPriority(condition.Condition) { - case IssueMergePriority: - issueConditions = append(issueConditions, condition) - case UnknownMergePriority: - unknownConditions = append(unknownConditions, condition) - case InfoMergePriority: - infoConditions = append(infoConditions, condition) - } - } - return issueConditions, unknownConditions, infoConditions -} - -// summaryMessage returns message for the summary operation. -func summaryMessage(conditions []ConditionWithOwnerInfo, d *defaultMergeStrategy, status metav1.ConditionStatus) string { - messages := []string{} - - // Note: use conditions because we want to preserve the order of relevance defined by the users (the order of condition types). - for _, condition := range conditions { - priority := d.getPriorityFunc(condition.Condition) - if priority == InfoMergePriority { - // Drop info messages when we are surfacing issues or unknown. - if status != metav1.ConditionTrue { - continue - } - // Drop info conditions with empty messages. - if condition.Message == "" { - continue - } - } - - m := fmt.Sprintf("* %s:", condition.Type) - if condition.Message != "" { - m += indentIfMultiline(condition.Message) - } else { - m += fmt.Sprintf(" %s", condition.Reason) - } - messages = append(messages, m) - } - - if d.summaryMessageTransformFunc != nil { - messages = d.summaryMessageTransformFunc(messages) - } - - return strings.Join(messages, "\n") -} - -// aggregateMessages returns messages for the aggregate operation. -func aggregateMessages(conditions []ConditionWithOwnerInfo, n *int, dropEmpty bool, getPriority func(condition metav1.Condition) MergePriority, otherMessages map[MergePriority]string) (messages []string) { - // create a map with all the messages and the list of objects reporting the same message. - messageObjMap := map[string]map[string][]string{} - messagePriorityMap := map[string]MergePriority{} - messageMustGoFirst := map[string]bool{} - cpMachines := sets.Set[string]{} - for _, condition := range conditions { - if dropEmpty && condition.Message == "" { - continue - } - - // Keep track of the message and the list of objects it applies to. - m := condition.Message - if _, ok := messageObjMap[condition.OwnerResource.Kind]; !ok { - messageObjMap[condition.OwnerResource.Kind] = map[string][]string{} - } - messageObjMap[condition.OwnerResource.Kind][m] = append(messageObjMap[condition.OwnerResource.Kind][m], condition.OwnerResource.Name) - - // Keep track of CP machines - if condition.OwnerResource.IsControlPlaneMachine { - cpMachines.Insert(condition.OwnerResource.Name) - } - - // Keep track of the priority of the message. - // In case the same message exists with different priorities, the highest according to issue/unknown/info applies. - currentPriority, ok := messagePriorityMap[m] - newPriority := getPriority(condition.Condition) - switch { - case !ok: - messagePriorityMap[m] = newPriority - case currentPriority == IssueMergePriority: - // No-op, issue is already the highest priority. - case currentPriority == UnknownMergePriority: - // If current priority is unknown, use new one only if higher. - if newPriority == IssueMergePriority { - messagePriorityMap[m] = newPriority - } - case currentPriority == InfoMergePriority: - // if current priority is info, new one can be equal or higher, use it. - messagePriorityMap[m] = newPriority - } - - // Keep track if this message belongs to control plane machines, and thus it should go first. - // Note: it is enough that on object is a control plane machine to move the message as first. - first, ok := messageMustGoFirst[m] - if !ok || !first { - if condition.OwnerResource.IsControlPlaneMachine { - messageMustGoFirst[m] = true - } - } - } - - // Gets the objects kind (with a stable order). - kinds := make([]string, 0, len(messageObjMap)) - for kind := range messageObjMap { - kinds = append(kinds, kind) - } - sort.Strings(kinds) - - // Aggregate messages for each object kind. - for _, kind := range kinds { - kindPlural := flect.Pluralize(kind) - messageObjMapForKind := messageObjMap[kind] - - // compute the order of messages according to: - // - message should go first (e.g. it applies to a control plane machine) - // - message priority (e.g. first issues, then unknown) - // - the number of objects reporting the same message. - // Note: The list of object names is used as a secondary criteria to sort messages with the same number of objects. - messageIndex := make([]string, 0, len(messageObjMapForKind)) - for m := range messageObjMapForKind { - messageIndex = append(messageIndex, m) - } - - sort.SliceStable(messageIndex, func(i, j int) bool { - return sortMessage(messageIndex[i], messageIndex[j], messageMustGoFirst, messagePriorityMap, messageObjMapForKind) - }) - - // Pick the first n messages, decrement n. - // For each message, add up to three objects; if more add the number of the remaining objects with the same message. - // Count the number of objects reporting messages not included in the above. - // Note: we are showing up to three objects because usually control plane has 3 machines, and we want to show all issues - // to control plane machines if any, - others := map[MergePriority]int{} - for _, m := range messageIndex { - if *n == 0 { - others[messagePriorityMap[m]] += len(messageObjMapForKind[m]) - continue - } - - msg := "" - allObjects := messageObjMapForKind[m] - sort.Slice(allObjects, func(i, j int) bool { - return sortObj(allObjects[i], allObjects[j], cpMachines) - }) - switch { - case len(allObjects) == 0: - // This should never happen, entry in the map exists only when an object reports a message. - case len(allObjects) == 1: - msg += fmt.Sprintf("* %s %s:", kind, strings.Join(allObjects, ", ")) - case len(allObjects) <= 3: - msg += fmt.Sprintf("* %s %s:", kindPlural, strings.Join(allObjects, ", ")) - default: - msg += fmt.Sprintf("* %s %s, ... (%d more):", kindPlural, strings.Join(allObjects[:3], ", "), len(allObjects)-3) - } - msg += indentIfMultiline(m) - - messages = append(messages, msg) - *n-- - } - - for _, p := range []MergePriority{IssueMergePriority, UnknownMergePriority, InfoMergePriority} { - other, ok := others[p] - if !ok { - continue - } - - otherMessage, ok := otherMessages[p] - if !ok { - continue - } - if other == 1 { - messages = append(messages, fmt.Sprintf("And %d %s %s", other, kind, otherMessage)) - } - if other > 1 { - messages = append(messages, fmt.Sprintf("And %d %s %s", other, kindPlural, otherMessage)) - } - } - } - - return messages -} - -func sortMessage(i, j string, messageMustGoFirst map[string]bool, messagePriorityMap map[string]MergePriority, messageObjMapForKind map[string][]string) bool { - if messageMustGoFirst[i] && !messageMustGoFirst[j] { - return true - } - if !messageMustGoFirst[i] && messageMustGoFirst[j] { - return false - } - - if messagePriorityMap[i] < messagePriorityMap[j] { - return true - } - if messagePriorityMap[i] > messagePriorityMap[j] { - return false - } - - if len(messageObjMapForKind[i]) > len(messageObjMapForKind[j]) { - return true - } - if len(messageObjMapForKind[i]) < len(messageObjMapForKind[j]) { - return false - } - - return strings.Join(messageObjMapForKind[i], ",") < strings.Join(messageObjMapForKind[j], ",") -} - -func sortObj(i, j string, cpMachines sets.Set[string]) bool { - if cpMachines.Has(i) && !cpMachines.Has(j) { - return true - } - if !cpMachines.Has(i) && cpMachines.Has(j) { - return false - } - return i < j -} - -var re = regexp.MustCompile(`\s*\*\s+`) - -func indentIfMultiline(m string) string { - msg := "" - // If it is a multiline string or if it start with a bullet, indent the message. - if strings.Contains(m, "\n") || re.MatchString(m) { - msg += "\n" - - // Split the message in lines, and add a prefix; prefix can be - // " " when indenting a line starting in a bullet - // " * " when indenting a line starting without a bullet (indent + add a bullet) - // " " when indenting a line starting with a bullet, but other lines required adding a bullet - lines := strings.Split(m, "\n") - prefix := " " - hasLinesWithoutBullet := false - for i := range lines { - if !re.MatchString(lines[i]) { - hasLinesWithoutBullet = true - break - } - } - for i, l := range lines { - prefix := prefix - if hasLinesWithoutBullet { - if !re.MatchString(lines[i]) { - prefix += "* " - } else { - prefix += " " - } - } - lines[i] = prefix + l - } - msg += strings.Join(lines, "\n") - } else { - msg += " " + m - } - return msg -} - -// getConditionsWithOwnerInfo return all the conditions from an object each one with the corresponding ConditionOwnerInfo. -func getConditionsWithOwnerInfo(obj Getter) []ConditionWithOwnerInfo { - ret := make([]ConditionWithOwnerInfo, 0, 10) - conditions := obj.GetV1Beta2Conditions() - ownerInfo := getConditionOwnerInfo(obj) - for _, condition := range conditions { - ret = append(ret, ConditionWithOwnerInfo{ - OwnerResource: ownerInfo, - Condition: condition, - }) - } - return ret -} - -// getConditionOwnerInfo return the ConditionOwnerInfo for the given object. -// Note: Given that controller runtime often does not set typeMeta for objects, -// in case kind is missing we are falling back to the type name, which in most cases -// is the same as kind. -func getConditionOwnerInfo(obj any) ConditionOwnerInfo { - var kind, name string - var isControlPlaneMachine bool - if runtimeObject, ok := obj.(runtime.Object); ok { - kind = runtimeObject.GetObjectKind().GroupVersionKind().Kind - } - - if kind == "" { - t := reflect.TypeOf(obj) - if t.Kind() == reflect.Pointer { - kind = t.Elem().Name() - } else { - kind = t.Name() - } - } - - if objMeta, ok := obj.(objectWithNameAndLabels); ok { - name = objMeta.GetName() - if kind == "Machine" { - _, isControlPlaneMachine = objMeta.GetLabels()[clusterv1.MachineControlPlaneLabel] - } - } - - return ConditionOwnerInfo{ - Kind: kind, - Name: name, - IsControlPlaneMachine: isControlPlaneMachine, - } -} - -// objectWithNameAndLabels is a subset of metav1.Object. -type objectWithNameAndLabels interface { - GetName() string - GetLabels() map[string]string -} diff --git a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/setter.go b/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/setter.go deleted file mode 100644 index 75b1042b94e7..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/util/conditions/v1beta2/setter.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta2 - -import ( - "sort" - "time" - - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "sigs.k8s.io/cluster-api/util" -) - -// Setter interface defines methods that a Cluster API object should implement in order to -// use the conditions package for setting conditions. -type Setter interface { - Getter - - // SetV1Beta2Conditions sets conditions for an API object. - // Note: SetV1Beta2Conditions will be renamed to SetConditions in a later stage of the transition to V1Beta2. - SetV1Beta2Conditions([]metav1.Condition) -} - -// SetOption is some configuration that modifies options for a Set request. -type SetOption interface { - // ApplyToSet applies this configuration to the given Set options. - ApplyToSet(option *SetOptions) -} - -// SetOptions allows to define options for the set operation. -type SetOptions struct { - conditionSortFunc ConditionSortFunc -} - -// ApplyOptions applies the given list options on these options, -// and then returns itself (for convenient chaining). -func (o *SetOptions) ApplyOptions(opts []SetOption) *SetOptions { - for _, opt := range opts { - opt.ApplyToSet(o) - } - return o -} - -// Set a condition on the given object implementing the Setter interface; if the object is nil, the operation is a no-op. -// -// When setting a condition: -// - condition.ObservedGeneration will be set to object.Metadata.Generation if targetObj is a metav1.Object. -// - If the condition does not exist and condition.LastTransitionTime is not set, time.Now is used. -// - If the condition already exists, condition.Status is changing and condition.LastTransitionTime is not set, time.Now is used. -// - If the condition already exists, condition.Status is NOT changing, all the fields can be changed except for condition.LastTransitionTime. -// -// Additionally, Set enforces a default condition order (Available and Ready fist, everything else in alphabetical order), -// but this can be changed by using the ConditionSortFunc option. -// -// Please note that Set does not support setting conditions to an unstructured object nor to API types not implementing -// the Setter interface. Eventually, users can implement wrappers on those types implementing this interface and -// taking care of aligning the condition format if necessary. -func Set(targetObj Setter, condition metav1.Condition, opts ...SetOption) { - if util.IsNil(targetObj) { - return - } - - setOpt := &SetOptions{ - // By default, sort conditions by the default condition order: available and ready always first, deleting and paused always last, all the other conditions in alphabetical order. - conditionSortFunc: defaultSortLessFunc, - } - setOpt.ApplyOptions(opts) - - if objMeta, ok := targetObj.(metav1.Object); ok { - condition.ObservedGeneration = objMeta.GetGeneration() - } - - conditions := targetObj.GetV1Beta2Conditions() - if changed := setStatusCondition(&conditions, condition); !changed { - return - } - - if setOpt.conditionSortFunc != nil { - sort.SliceStable(conditions, func(i, j int) bool { - return setOpt.conditionSortFunc(conditions[i], conditions[j]) - }) - } - - targetObj.SetV1Beta2Conditions(conditions) -} - -func setStatusCondition(conditions *[]metav1.Condition, condition metav1.Condition) bool { - // Truncate last transition time to seconds. - // This prevents inconsistencies from what we have in objects in memory and what Marshal/Unmarshal - // will do while the data is sent to/read from the API server. - if condition.LastTransitionTime.IsZero() { - condition.LastTransitionTime = metav1.Now() - } - condition.LastTransitionTime.Time = condition.LastTransitionTime.Truncate(1 * time.Second) - return meta.SetStatusCondition(conditions, condition) -} - -// Delete deletes the condition with the given type. -func Delete(to Setter, conditionType string) { - if to == nil { - return - } - - conditions := to.GetV1Beta2Conditions() - newConditions := make([]metav1.Condition, 0, len(conditions)-1) - for _, condition := range conditions { - if condition.Type != conditionType { - newConditions = append(newConditions, condition) - } - } - to.SetV1Beta2Conditions(newConditions) -} diff --git a/vendor/sigs.k8s.io/cluster-api/util/contract/contract.go b/vendor/sigs.k8s.io/cluster-api/util/contract/contract.go deleted file mode 100644 index fbb8067f8d99..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/util/contract/contract.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2022 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package contract - -import ( - "fmt" - "strings" - - "github.com/gobuffalo/flect" -) - -// CalculateCRDName generates a CRD name based on group and kind according to -// the naming conventions in the contract. -func CalculateCRDName(group, kind string) string { - return fmt.Sprintf("%s.%s", flect.Pluralize(strings.ToLower(kind)), group) -} diff --git a/vendor/sigs.k8s.io/cluster-api/util/contract/doc.go b/vendor/sigs.k8s.io/cluster-api/util/contract/doc.go deleted file mode 100644 index eeae81d5ff5b..000000000000 --- a/vendor/sigs.k8s.io/cluster-api/util/contract/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2022 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Package contract contains utils related to the Cluster API contract. -package contract diff --git a/vendor/sigs.k8s.io/cluster-api/util/conversion/conversion.go b/vendor/sigs.k8s.io/cluster-api/util/conversion/conversion.go index b10a428b77b3..916d77c1f563 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/conversion/conversion.go +++ b/vendor/sigs.k8s.io/cluster-api/util/conversion/conversion.go @@ -18,19 +18,23 @@ limitations under the License. package conversion import ( - "context" - "sort" - "strings" - - "github.com/pkg/errors" - corev1 "k8s.io/api/core/v1" + "math/rand" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/onsi/gomega" + "k8s.io/apimachinery/pkg/api/apitesting/fuzzer" + apiequality "k8s.io/apimachinery/pkg/api/equality" + metafuzzer "k8s.io/apimachinery/pkg/apis/meta/fuzzer" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/json" - "sigs.k8s.io/controller-runtime/pkg/client" - - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" - "sigs.k8s.io/cluster-api/util" + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/conversion" + "sigs.k8s.io/randfill" ) const ( @@ -39,52 +43,6 @@ const ( DataAnnotation = "cluster.x-k8s.io/conversion-data" ) -var ( - contract = clusterv1.GroupVersion.String() -) - -// UpdateReferenceAPIContract takes a client and object reference, queries the API Server for -// the Custom Resource Definition and looks which one is the stored version available. -// -// The object passed as input is modified in place if an updated compatible version is found. -// NOTE: This version depends on CRDs being named correctly as defined by contract.CalculateCRDName. -func UpdateReferenceAPIContract(ctx context.Context, c client.Client, ref *corev1.ObjectReference) error { - gvk := ref.GroupVersionKind() - - metadata, err := util.GetGVKMetadata(ctx, c, gvk) - if err != nil { - return errors.Wrapf(err, "failed to update apiVersion in ref") - } - - chosen, err := getLatestAPIVersionFromContract(metadata) - if err != nil { - return errors.Wrapf(err, "failed to update apiVersion in ref") - } - - // Modify the GroupVersionKind with the new version. - if gvk.Version != chosen { - gvk.Version = chosen - ref.SetGroupVersionKind(gvk) - } - - return nil -} - -func getLatestAPIVersionFromContract(metadata metav1.Object) (string, error) { - labels := metadata.GetLabels() - - // If there is no label, return early without changing the reference. - supportedVersions, ok := labels[contract] - if !ok || supportedVersions == "" { - return "", errors.Errorf("cannot find any versions matching contract %q for CRD %v as contract version label(s) are either missing or empty (see https://cluster-api.sigs.k8s.io/developer/providers/contracts.html#api-version-labels)", contract, metadata.GetName()) - } - - // Pick the latest version in the slice and validate it. - kubeVersions := util.KubeAwareAPIVersions(strings.Split(supportedVersions, "_")) - sort.Sort(kubeVersions) - return kubeVersions[len(kubeVersions)-1], nil -} - // MarshalData stores the source object as json data in the destination object annotations map. // It ignores the metadata of the source object. func MarshalData(src metav1.Object, dst metav1.Object) error { @@ -122,3 +80,139 @@ func UnmarshalData(from metav1.Object, to interface{}) (bool, error) { return true, nil } +// GetFuzzer returns a new fuzzer to be used for testing. +func GetFuzzer(scheme *runtime.Scheme, funcs ...fuzzer.FuzzerFuncs) *randfill.Filler { + funcs = append([]fuzzer.FuzzerFuncs{ + metafuzzer.Funcs, + func(_ runtimeserializer.CodecFactory) []interface{} { + return []interface{}{ + // Custom fuzzer for metav1.Time pointers which weren't + // fuzzed and always resulted in `nil` values. + // This implementation is somewhat similar to the one provided + // in the metafuzzer.Funcs. + func(input **metav1.Time, c randfill.Continue) { + if c.Bool() { + // Leave the Time sometimes nil to also get coverage for this case. + return + } + if c.Bool() { + // Set the Time sometimes empty to also get coverage for this case. + *input = &metav1.Time{} + return + } + var sec, nsec uint32 + c.Fill(&sec) + c.Fill(&nsec) + fuzzed := metav1.Unix(int64(sec), int64(nsec)).Rfc3339Copy() + *input = &metav1.Time{Time: fuzzed.Time} + }, + // Custom fuzzer for intstr.IntOrString which does not get fuzzed otherwise. + func(in **intstr.IntOrString, c randfill.Continue) { + if c.Bool() { + // Leave the IntOrString sometimes nil to also get coverage for this case. + return + } + if c.Bool() { + // Set the IntOrString sometimes empty to also get coverage for this case. + *in = &intstr.IntOrString{} + return + } + *in = ptr.To(intstr.FromInt32(c.Int31n(50))) + }, + } + }, + }, funcs...) + return fuzzer.FuzzerFor( + fuzzer.MergeFuzzerFuncs(funcs...), + rand.NewSource(rand.Int63()), //nolint:gosec + runtimeserializer.NewCodecFactory(scheme), + ) +} + +// FuzzTestFuncInput contains input parameters +// for the FuzzTestFunc function. +type FuzzTestFuncInput struct { + Scheme *runtime.Scheme + + Hub conversion.Hub + HubAfterMutation func(conversion.Hub) + + Spoke conversion.Convertible + SpokeAfterMutation func(convertible conversion.Convertible) + SkipSpokeAnnotationCleanup bool + + FuzzerFuncs []fuzzer.FuzzerFuncs +} + +// FuzzTestFunc returns a new testing function to be used in tests to make sure conversions between +// the Hub version of an object and an older version aren't lossy. +func FuzzTestFunc(input FuzzTestFuncInput) func(*testing.T) { + if input.Scheme == nil { + input.Scheme = scheme.Scheme + } + + return func(t *testing.T) { + t.Helper() + t.Run("spoke-hub-spoke", func(t *testing.T) { + g := gomega.NewWithT(t) + fuzzer := GetFuzzer(input.Scheme, input.FuzzerFuncs...) + + for range 10000 { + // Create the spoke and fuzz it + spokeBefore := input.Spoke.DeepCopyObject().(conversion.Convertible) + fuzzer.Fill(spokeBefore) + + // First convert spoke to hub + hubCopy := input.Hub.DeepCopyObject().(conversion.Hub) + g.Expect(spokeBefore.ConvertTo(hubCopy)).To(gomega.Succeed()) + + // Convert hub back to spoke and check if the resulting spoke is equal to the spoke before the round trip + spokeAfter := input.Spoke.DeepCopyObject().(conversion.Convertible) + g.Expect(spokeAfter.ConvertFrom(hubCopy)).To(gomega.Succeed()) + + // Remove data annotation eventually added by ConvertFrom for avoiding data loss in hub-spoke-hub round trips + // NOTE: There are use case when we want to skip this operation, e.g. if the spoke object does not have ObjectMeta (e.g. kubeadm types). + if !input.SkipSpokeAnnotationCleanup { + metaAfter := spokeAfter.(metav1.Object) + delete(metaAfter.GetAnnotations(), DataAnnotation) + } + + if input.SpokeAfterMutation != nil { + input.SpokeAfterMutation(spokeAfter) + } + + if !apiequality.Semantic.DeepEqual(spokeBefore, spokeAfter) { + diff := cmp.Diff(spokeBefore, spokeAfter) + g.Expect(false).To(gomega.BeTrue(), diff) + } + } + }) + t.Run("hub-spoke-hub", func(t *testing.T) { + g := gomega.NewWithT(t) + fuzzer := GetFuzzer(input.Scheme, input.FuzzerFuncs...) + + for range 10000 { + // Create the hub and fuzz it + hubBefore := input.Hub.DeepCopyObject().(conversion.Hub) + fuzzer.Fill(hubBefore) + + // First convert hub to spoke + dstCopy := input.Spoke.DeepCopyObject().(conversion.Convertible) + g.Expect(dstCopy.ConvertFrom(hubBefore)).To(gomega.Succeed()) + + // Convert spoke back to hub and check if the resulting hub is equal to the hub before the round trip + hubAfter := input.Hub.DeepCopyObject().(conversion.Hub) + g.Expect(dstCopy.ConvertTo(hubAfter)).To(gomega.Succeed()) + + if input.HubAfterMutation != nil { + input.HubAfterMutation(hubAfter) + } + + if !apiequality.Semantic.DeepEqual(hubBefore, hubAfter) { + diff := cmp.Diff(hubBefore, hubAfter) + g.Expect(false).To(gomega.BeTrue(), diff) + } + } + }) + } +} diff --git a/vendor/sigs.k8s.io/cluster-api/util/patch/options.go b/vendor/sigs.k8s.io/cluster-api/util/patch/options.go index ba185c6dfc94..6d7ef5e188e9 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/patch/options.go +++ b/vendor/sigs.k8s.io/cluster-api/util/patch/options.go @@ -16,7 +16,7 @@ limitations under the License. package patch -import clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" +import clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" // Option is some configuration that modifies options for a patch request. type Option interface { @@ -46,7 +46,7 @@ type HelperOptions struct { // Please note that the default value for this option is inferred from the object struct. // This means, that if the correct path cannot be detected, this option has to be specified. One example // is if you pass a wrapper to unstructured. - // The override for this option is considered only if the object implements the v1beta2conditions.Setter interface. + // The override for this option is considered only if the object implements the conditions.Setter interface. Metav1ConditionsFieldPath []string // Clusterv1ConditionsFieldPath allows to override the path for the field hosting clusterv1.Conditions. @@ -75,31 +75,31 @@ func (w WithStatusObservedGeneration) ApplyToHelper(in *HelperOptions) { in.IncludeStatusObservedGeneration = true } -// WithOwnedConditions allows to define condition types owned by the controller. +// WithOwnedV1Beta1Conditions allows to define condition types owned by the controller. // In case of conflicts for the owned conditions, the patch helper will always use the value provided by the controller. -type WithOwnedConditions struct { +type WithOwnedV1Beta1Conditions struct { Conditions []clusterv1.ConditionType } // ApplyToHelper applies this configuration to the given HelperOptions. -func (w WithOwnedConditions) ApplyToHelper(in *HelperOptions) { +func (w WithOwnedV1Beta1Conditions) ApplyToHelper(in *HelperOptions) { in.OwnedConditions = w.Conditions } -// WithOwnedV1Beta2Conditions allows to define condition types owned by the controller. +// WithOwnedConditions allows to define condition types owned by the controller. // In case of conflicts for the owned conditions, the patch helper will always use the value provided by the controller. -type WithOwnedV1Beta2Conditions struct { +type WithOwnedConditions struct { Conditions []string } // ApplyToHelper applies this configuration to the given HelperOptions. -func (w WithOwnedV1Beta2Conditions) ApplyToHelper(in *HelperOptions) { +func (w WithOwnedConditions) ApplyToHelper(in *HelperOptions) { in.OwnedV1Beta2Conditions = w.Conditions } // Metav1ConditionsFieldPath allows to override the path for the field hosting []metav1.Condition. // Please note that the default value for this option is inferred from the object struct. -// The override for this option is considered only if the object implements the v1beta2conditions.Setter interface. +// The override for this option is considered only if the object implements the conditions.Setter interface. type Metav1ConditionsFieldPath []string // ApplyToHelper applies this configuration to the given HelperOptions. diff --git a/vendor/sigs.k8s.io/cluster-api/util/patch/patch.go b/vendor/sigs.k8s.io/cluster-api/util/patch/patch.go index 73e60f253d39..1c994e3b88e1 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/patch/patch.go +++ b/vendor/sigs.k8s.io/cluster-api/util/patch/patch.go @@ -33,10 +33,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/cluster-api/util" "sigs.k8s.io/cluster-api/util/conditions" - v1beta2conditions "sigs.k8s.io/cluster-api/util/conditions/v1beta2" + v1beta1conditions "sigs.k8s.io/cluster-api/util/conditions/deprecated/v1beta1" ) // Helper is a utility for ensuring the proper patching of objects. @@ -56,7 +56,7 @@ type Helper struct { // obj. After changing obj use Helper.Patch to persist your changes. // // Please note that patch helper implements a custom handling for objects implementing -// the condition.Setter interface or the v1beta2conditions.Setter interface. +// the condition.Setter interface or the conditions.Setter interface. // // It is also possible to implement wrappers for object not implementing those interfaces; // in case those objects have custom conditions types the wrapper should take care of conversions. @@ -124,10 +124,10 @@ func (h *Helper) Patch(ctx context.Context, obj client.Object, opts ...Option) e } // Check if the object satisfies the Cluster API contract setter interfaces; if not, ignore condition field path entirely. - if _, canInterfaceConditions := obj.(conditions.Setter); !canInterfaceConditions { + if _, canInterfaceConditions := obj.(v1beta1conditions.Setter); !canInterfaceConditions { h.clusterv1ConditionsFieldPath = nil } - if _, canInterfaceV1Beta2Conditions := obj.(v1beta2conditions.Setter); !canInterfaceV1Beta2Conditions { + if _, canInterfaceV1Beta2Conditions := obj.(conditions.Setter); !canInterfaceV1Beta2Conditions { h.metav1ConditionsFieldPath = nil } @@ -180,6 +180,7 @@ func (h *Helper) Patch(ctx context.Context, obj client.Object, opts ...Option) e } if err := h.patchStatus(ctx, obj); err != nil { + //nolint:staticcheck if !(apierrors.IsNotFound(err) && !obj.GetDeletionTimestamp().IsZero() && len(obj.GetFinalizers()) == 0) { errs = append(errs, err) } @@ -237,16 +238,16 @@ func (h *Helper) patchStatusConditions(ctx context.Context, obj client.Object, f // // NOTE: The checks and error below are done so that we don't panic if any of the objects don't satisfy the // interface any longer, although this shouldn't happen because we already check when creating the patcher. - before, ok := h.beforeObject.(conditions.Getter) + before, ok := h.beforeObject.(v1beta1conditions.Getter) if !ok { return errors.Errorf("%s %s doesn't satisfy conditions.Getter, cannot patch", h.gvk.Kind, klog.KObj(h.beforeObject)) } - after, ok := obj.(conditions.Getter) + after, ok := obj.(v1beta1conditions.Getter) if !ok { return errors.Errorf("%s %s doesn't satisfy conditions.Getter, cannot compute patch", h.gvk.Kind, klog.KObj(obj)) } - diff, err := conditions.NewPatch( + diff, err := v1beta1conditions.NewPatch( before, after, ) @@ -255,12 +256,12 @@ func (h *Helper) patchStatusConditions(ctx context.Context, obj client.Object, f } if !diff.IsZero() { clusterv1ApplyPatch = func(latest client.Object) error { - latestSetter, ok := latest.(conditions.Setter) + latestSetter, ok := latest.(v1beta1conditions.Setter) if !ok { return errors.Errorf("%s %s doesn't satisfy conditions.Setter, cannot apply patch", h.gvk.Kind, klog.KObj(latest)) } - return diff.Apply(latestSetter, conditions.WithForceOverwrite(forceOverwrite), conditions.WithOwnedConditions(ownedConditions...)) + return diff.Apply(latestSetter, v1beta1conditions.WithForceOverwrite(forceOverwrite), v1beta1conditions.WithOwnedConditions(ownedConditions...)) } } } @@ -272,16 +273,16 @@ func (h *Helper) patchStatusConditions(ctx context.Context, obj client.Object, f // // NOTE: The checks and error below are done so that we don't panic if any of the objects don't satisfy the // interface any longer, although this shouldn't happen because we already check when creating the patcher. - before, ok := h.beforeObject.(v1beta2conditions.Getter) + before, ok := h.beforeObject.(conditions.Getter) if !ok { - return errors.Errorf("%s %s doesn't satisfy v1beta2conditions.Getter, cannot patch", h.gvk.Kind, klog.KObj(h.beforeObject)) + return errors.Errorf("%s %s doesn't satisfy conditions.Getter, cannot patch", h.gvk.Kind, klog.KObj(h.beforeObject)) } - after, ok := obj.(v1beta2conditions.Getter) + after, ok := obj.(conditions.Getter) if !ok { - return errors.Errorf("%s %s doesn't satisfy v1beta2conditions.Getter, cannot compute patch", h.gvk.Kind, klog.KObj(obj)) + return errors.Errorf("%s %s doesn't satisfy conditions.Getter, cannot compute patch", h.gvk.Kind, klog.KObj(obj)) } - diff, err := v1beta2conditions.NewPatch( + diff, err := conditions.NewPatch( before, after, ) @@ -291,12 +292,12 @@ func (h *Helper) patchStatusConditions(ctx context.Context, obj client.Object, f if !diff.IsZero() { metav1ApplyPatch = func(latest client.Object) error { - latestSetter, ok := latest.(v1beta2conditions.Setter) + latestSetter, ok := latest.(conditions.Setter) if !ok { return errors.Errorf("%s %s doesn't satisfy conditions.Setter, cannot apply patch", h.gvk.Kind, klog.KObj(latest)) } - return diff.Apply(latestSetter, v1beta2conditions.ForceOverwrite(forceOverwrite), v1beta2conditions.OwnedConditionTypes(ownedV1beta2Conditions)) + return diff.Apply(latestSetter, conditions.ForceOverwrite(forceOverwrite), conditions.OwnedConditionTypes(ownedV1beta2Conditions)) } } } diff --git a/vendor/sigs.k8s.io/cluster-api/util/patch/utils.go b/vendor/sigs.k8s.io/cluster-api/util/patch/utils.go index d16fa9734841..460b95a3c669 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/patch/utils.go +++ b/vendor/sigs.k8s.io/cluster-api/util/patch/utils.go @@ -25,7 +25,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) type patchType string diff --git a/vendor/sigs.k8s.io/cluster-api/util/topology/topology.go b/vendor/sigs.k8s.io/cluster-api/util/topology/topology.go index f1a9cb6cf5d8..eb903e156c74 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/topology/topology.go +++ b/vendor/sigs.k8s.io/cluster-api/util/topology/topology.go @@ -21,14 +21,22 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" ) // ShouldSkipImmutabilityChecks returns true if it is a dry-run request and the object has the // TopologyDryRunAnnotation annotation set, false otherwise. // This ensures that the immutability check is skipped only when dry-running and when the operations has been invoked by the topology controller. // Instead, kubectl dry-run behavior remains consistent with the one user gets when doing kubectl apply (immutability is enforced). +// +// Deprecated: Please use IsDryRunRequest instead. func ShouldSkipImmutabilityChecks(req admission.Request, obj metav1.Object) bool { + return IsDryRunRequest(req, obj) +} + +// IsDryRunRequest returns true if it is a dry-run request and the object has the +// TopologyDryRunAnnotation annotation set, false otherwise. +func IsDryRunRequest(req admission.Request, obj metav1.Object) bool { // Check if the request is a dry-run if req.DryRun == nil || !*req.DryRun { return false diff --git a/vendor/sigs.k8s.io/cluster-api/util/util.go b/vendor/sigs.k8s.io/cluster-api/util/util.go index dfe38100ef8e..684ef3d07b8c 100644 --- a/vendor/sigs.k8s.io/cluster-api/util/util.go +++ b/vendor/sigs.k8s.io/cluster-api/util/util.go @@ -30,7 +30,6 @@ import ( "github.com/blang/semver/v4" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -38,7 +37,6 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - k8sversion "k8s.io/apimachinery/pkg/version" "k8s.io/utils/ptr" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -46,9 +44,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/reconcile" - clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/cluster-api/util/annotations" - "sigs.k8s.io/cluster-api/util/contract" "sigs.k8s.io/cluster-api/util/labels/format" ) @@ -133,7 +130,7 @@ func GetMachineIfExists(ctx context.Context, c client.Client, namespace, name st // IsControlPlaneMachine checks machine is a control plane node. func IsControlPlaneMachine(machine *clusterv1.Machine) bool { - _, ok := machine.ObjectMeta.Labels[clusterv1.MachineControlPlaneLabel] + _, ok := machine.Labels[clusterv1.MachineControlPlaneLabel] return ok } @@ -207,12 +204,12 @@ func ClusterToInfrastructureMapFunc(ctx context.Context, gvk schema.GroupVersion } // Return early if the InfrastructureRef is nil. - if cluster.Spec.InfrastructureRef == nil { + if !cluster.Spec.InfrastructureRef.IsDefined() { return nil } gk := gvk.GroupKind() // Return early if the GroupKind doesn't match what we expect. - infraGK := cluster.Spec.InfrastructureRef.GroupVersionKind().GroupKind() + infraGK := cluster.Spec.InfrastructureRef.GroupKind() if gk != infraGK { return nil } @@ -275,7 +272,7 @@ func MachineToInfrastructureMapFunc(gvk schema.GroupVersionKind) handler.MapFunc gk := gvk.GroupKind() // Return early if the GroupKind doesn't match what we expect. - infraGK := m.Spec.InfrastructureRef.GroupVersionKind().GroupKind() + infraGK := m.Spec.InfrastructureRef.GroupKind() if gk != infraGK { return nil } @@ -456,33 +453,6 @@ func HasOwner(refList []metav1.OwnerReference, apiVersion string, kinds []string return false } -// GetGVKMetadata retrieves a CustomResourceDefinition metadata from the API server using partial object metadata. -// -// This function is greatly more efficient than GetCRDWithContract and should be preferred in most cases. -func GetGVKMetadata(ctx context.Context, c client.Client, gvk schema.GroupVersionKind) (*metav1.PartialObjectMetadata, error) { - meta := &metav1.PartialObjectMetadata{} - meta.SetName(contract.CalculateCRDName(gvk.Group, gvk.Kind)) - meta.SetGroupVersionKind(apiextensionsv1.SchemeGroupVersion.WithKind("CustomResourceDefinition")) - if err := c.Get(ctx, client.ObjectKeyFromObject(meta), meta); err != nil { - return meta, errors.Wrap(err, "failed to retrieve metadata from GVK resource") - } - return meta, nil -} - -// KubeAwareAPIVersions is a sortable slice of kube-like version strings. -// -// Kube-like version strings are starting with a v, followed by a major version, -// optional "alpha" or "beta" strings followed by a minor version (e.g. v1, v2beta1). -// Versions will be sorted based on GA/alpha/beta first and then major and minor -// versions. e.g. v2, v1, v1beta2, v1beta1, v1alpha1. -type KubeAwareAPIVersions []string - -func (k KubeAwareAPIVersions) Len() int { return len(k) } -func (k KubeAwareAPIVersions) Swap(i, j int) { k[i], k[j] = k[j], k[i] } -func (k KubeAwareAPIVersions) Less(i, j int) bool { - return k8sversion.CompareKubeAwareVersionStrings(k[i], k[j]) < 0 -} - // ClusterToTypedObjectsMapper returns a mapper function that gets a cluster and lists all objects for the object passed in // and returns a list of requests. // Note: This function uses the passed in typed ObjectList and thus with the default client configuration all list calls diff --git a/vendor/sigs.k8s.io/kustomize/api/filters/nameref/nameref.go b/vendor/sigs.k8s.io/kustomize/api/filters/nameref/nameref.go index ff83420cb18a..c25cf82823ab 100644 --- a/vendor/sigs.k8s.io/kustomize/api/filters/nameref/nameref.go +++ b/vendor/sigs.k8s.io/kustomize/api/filters/nameref/nameref.go @@ -205,16 +205,14 @@ func getRoleRefGvk(n *resource.Resource) (*resid.Gvk, error) { return nil, err } if apiGroup.IsNil() { - return nil, fmt.Errorf( - "apiGroup cannot be found in roleRef %s", roleRef.MustString()) + return nil, fmt.Errorf("apiGroup cannot be found in roleRef %s", roleRef.MustString()) } kind, err := roleRef.Pipe(yaml.Lookup("kind")) if err != nil { return nil, err } if kind.IsNil() { - return nil, fmt.Errorf( - "kind cannot be found in roleRef %s", roleRef.MustString()) + return nil, fmt.Errorf("kind cannot be found in roleRef %s", roleRef.MustString()) } return &resid.Gvk{ Group: apiGroup.YNode().Value, diff --git a/vendor/sigs.k8s.io/kustomize/api/filters/replacement/replacement.go b/vendor/sigs.k8s.io/kustomize/api/filters/replacement/replacement.go index 56e70d875620..8afc646d26ec 100644 --- a/vendor/sigs.k8s.io/kustomize/api/filters/replacement/replacement.go +++ b/vendor/sigs.k8s.io/kustomize/api/filters/replacement/replacement.go @@ -4,6 +4,7 @@ package replacement import ( + "encoding/json" "fmt" "strings" @@ -11,7 +12,6 @@ import ( "sigs.k8s.io/kustomize/api/resource" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/errors" - "sigs.k8s.io/kustomize/kyaml/resid" kyaml_utils "sigs.k8s.io/kustomize/kyaml/utils" "sigs.k8s.io/kustomize/kyaml/yaml" ) @@ -117,6 +117,10 @@ func applyReplacement(nodes []*yaml.RNode, value *yaml.RNode, targetSelectors [] if len(selector.FieldPaths) == 0 { selector.FieldPaths = []string{types.DefaultReplacementFieldPath} } + tsr, err := types.NewTargetSelectorRegex(selector) + if err != nil { + return nil, fmt.Errorf("error creating target selector: %w", err) + } for _, possibleTarget := range nodes { ids, err := utils.MakeResIds(possibleTarget) if err != nil { @@ -132,9 +136,13 @@ func applyReplacement(nodes []*yaml.RNode, value *yaml.RNode, targetSelectors [] continue } + if tsr.RejectsAny(ids) { + continue + } + // filter targets by matching resource IDs for _, id := range ids { - if id.IsSelectedBy(selector.Select.ResId) && !containsRejectId(selector.Reject, ids) { + if tsr.Selects(id) { err := copyValueToTarget(possibleTarget, value, selector) if err != nil { return nil, err @@ -175,43 +183,37 @@ func matchesAnnoAndLabelSelector(n *yaml.RNode, selector *types.Selector) (bool, return annoMatch && labelMatch, nil } -func containsRejectId(rejects []*types.Selector, ids []resid.ResId) bool { - for _, r := range rejects { - if r.ResId.IsEmpty() { - continue - } - for _, id := range ids { - if id.IsSelectedBy(r.ResId) { - return true - } - } - } - return false -} - func copyValueToTarget(target *yaml.RNode, value *yaml.RNode, selector *types.TargetSelector) error { for _, fp := range selector.FieldPaths { createKind := yaml.Kind(0) // do not create if selector.Options != nil && selector.Options.Create { createKind = value.YNode().Kind } + + // Check if this fieldPath contains structured data access + if err := setValueInStructuredData(target, value, fp, createKind); err == nil { + // Successfully handled as structured data + continue + } + + // Fall back to normal path handling targetFieldList, err := target.Pipe(&yaml.PathMatcher{ Path: kyaml_utils.SmarterPathSplitter(fp, "."), Create: createKind}) if err != nil { - return errors.WrapPrefixf(err, fieldRetrievalError(fp, createKind != 0)) //nolint:govet + return errors.WrapPrefixf(err, "%s", fieldRetrievalError(fp, createKind != 0)) } targetFields, err := targetFieldList.Elements() if err != nil { - return errors.WrapPrefixf(err, fieldRetrievalError(fp, createKind != 0)) //nolint:govet + return errors.WrapPrefixf(err, "%s", fieldRetrievalError(fp, createKind != 0)) } if len(targetFields) == 0 { - return errors.Errorf(fieldRetrievalError(fp, createKind != 0)) //nolint:govet + return errors.Errorf("%s", fieldRetrievalError(fp, createKind != 0)) } for _, t := range targetFields { if err := setFieldValue(selector.Options, t, value); err != nil { - return err + return fmt.Errorf("%w", err) } } } @@ -254,3 +256,146 @@ func setFieldValue(options *types.FieldOptions, targetField *yaml.RNode, value * return nil } + +// setValueInStructuredData handles setting values within structured data (JSON/YAML) in scalar fields +func setValueInStructuredData(target *yaml.RNode, value *yaml.RNode, fieldPath string, createKind yaml.Kind) error { + pathParts := kyaml_utils.SmarterPathSplitter(fieldPath, ".") + if len(pathParts) < 2 { + return fmt.Errorf("not a structured data path") + } + + // Find the potential scalar field that might contain structured data + var scalarFieldPath []string + var structuredDataPath []string + var foundScalar = false + + // Try to find where the scalar field ends and structured data begins + for i := 1; i <= len(pathParts); i++ { + potentialScalarPath := pathParts[:i] + scalarField, err := target.Pipe(yaml.Lookup(potentialScalarPath...)) + if err != nil { + continue + } + if scalarField != nil && scalarField.YNode().Kind == yaml.ScalarNode && i < len(pathParts) { + // Try to parse the scalar value as structured data + scalarValue := scalarField.YNode().Value + var parsedNode yaml.Node + if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err == nil { + // Successfully parsed - this is structured data + scalarFieldPath = potentialScalarPath + structuredDataPath = pathParts[i:] + foundScalar = true + break + } + } + } + + if !foundScalar { + return fmt.Errorf("no structured data found in path") + } + + // Get the scalar field containing structured data + scalarField, err := target.Pipe(yaml.Lookup(scalarFieldPath...)) + if err != nil { + return fmt.Errorf("%w", err) + } + + // Parse the structured data + scalarValue := scalarField.YNode().Value + var parsedNode yaml.Node + if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err != nil { + return fmt.Errorf("%w", err) + } + + structuredData := yaml.NewRNode(&parsedNode) + + // Navigate to the target location within the structured data + targetInStructured, err := structuredData.Pipe(&yaml.PathMatcher{ + Path: structuredDataPath, + Create: createKind, + }) + if err != nil { + return fmt.Errorf("%w", err) + } + + targetFields, err := targetInStructured.Elements() + if err != nil { + return fmt.Errorf("%w", err) + } + + if len(targetFields) == 0 { + return fmt.Errorf("unable to find field in structured data") + } + + // Set the value in the structured data + for _, t := range targetFields { + if t.YNode().Kind == yaml.ScalarNode { + t.YNode().Value = value.YNode().Value + } else { + t.SetYNode(value.YNode()) + } + } + + // Serialize the modified structured data back to the scalar field + // Try to detect if original was JSON or YAML and preserve formatting + serializedData, err := serializeStructuredData(structuredData, scalarValue) + if err != nil { + return fmt.Errorf("%w", err) + } + + // Update the original scalar field + scalarField.YNode().Value = serializedData + + return nil +} + +// serializeStructuredData handles the serialization of structured data back to string format +// preserving the original format (JSON vs YAML) and style (pretty vs compact) +func serializeStructuredData(structuredData *yaml.RNode, originalValue string) (string, error) { + firstChar := rune(strings.TrimSpace(originalValue)[0]) + if firstChar == '{' || firstChar == '[' { + return serializeAsJSON(structuredData, originalValue) + } + + // Fallback to YAML format + return serializeAsYAML(structuredData) +} + +// serializeAsJSON converts structured data back to JSON format +func serializeAsJSON(structuredData *yaml.RNode, originalValue string) (string, error) { + modifiedData, err := structuredData.String() + if err != nil { + return "", fmt.Errorf("failed to serialize structured data: %w", err) + } + + // Parse the YAML output as JSON + var jsonData interface{} + if err := yaml.Unmarshal([]byte(modifiedData), &jsonData); err != nil { + return "", fmt.Errorf("failed to unmarshal YAML data: %w", err) + } + + // Check if original was pretty-printed by looking for newlines and indentation + if strings.Contains(originalValue, "\n") && strings.Contains(originalValue, " ") { + // Pretty-print the JSON to match original formatting + if prettyJSON, err := json.MarshalIndent(jsonData, "", " "); err == nil { + return string(prettyJSON), nil + } + } + + // Compact JSON + if compactJSON, err := json.Marshal(jsonData); err == nil { + return string(compactJSON), nil + } + + return "", fmt.Errorf("failed to marshal JSON data") +} + +// serializeAsYAML converts structured data back to YAML format +func serializeAsYAML(structuredData *yaml.RNode) (string, error) { + modifiedData, err := structuredData.String() + if err != nil { + return "", fmt.Errorf("failed to serialize YAML data: %w", err) + } + + return strings.TrimSpace(modifiedData), nil +} diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/AnnotationsTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/AnnotationsTransformer.go index 0910c472b8f3..d3b3fc8c2028 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/AnnotationsTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/AnnotationsTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on AnnotationsTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ConfigMapGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ConfigMapGenerator.go index dc18bce858ab..180a6c2c11d5 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ConfigMapGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ConfigMapGenerator.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ConfigMapGenerator; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HashTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HashTransformer.go index ec23312651a3..08dd37d0633b 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HashTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HashTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on HashTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go index 5811e73eca85..7a148f81e632 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/HelmChartInflationGenerator.go @@ -1,6 +1,4 @@ // Code generated by pluginator on HelmChartInflationGenerator; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( @@ -13,6 +11,7 @@ import ( "slices" "strings" + "sigs.k8s.io/kustomize/api/konfig" "sigs.k8s.io/kustomize/api/resmap" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/errors" @@ -178,12 +177,11 @@ func (p *HelmChartInflationGeneratorPlugin) runHelmCommand( } if err != nil { helm := p.h.GeneralConfig().HelmConfig.Command - //nolint:govet err = errors.WrapPrefixf( fmt.Errorf( "unable to run: '%s %s' with env=%s (is '%s' installed?): %w", helm, strings.Join(args, " "), env, helm, err), - errorOutput, + "%s", errorOutput, ) } return stdout.Bytes(), err @@ -297,6 +295,9 @@ func (p *HelmChartInflationGeneratorPlugin) Generate() (rm resmap.ResMap, err er rm, resMapErr := p.h.ResmapFactory().NewResMapFromBytes(stdout) if resMapErr == nil { + if err := p.markHelmGeneratedResources(rm); err != nil { + return nil, err + } return rm, nil } // try to remove the contents before first "---" because @@ -312,6 +313,9 @@ func (p *HelmChartInflationGeneratorPlugin) Generate() (rm resmap.ResMap, err er if err != nil { return nil, fmt.Errorf("could not parse rnode slice into resource map: %w", err) } + if err := p.markHelmGeneratedResources(rm); err != nil { + return nil, err + } return rm, nil } return nil, fmt.Errorf("could not parse bytes into resource map: %w", resMapErr) @@ -354,6 +358,15 @@ func (p *HelmChartInflationGeneratorPlugin) chartExistsLocally() (string, bool) return path, s.IsDir() } +func (p *HelmChartInflationGeneratorPlugin) markHelmGeneratedResources(rm resmap.ResMap) error { + for _, r := range rm.Resources() { + if err := r.RNode.PipeE(kyaml.SetAnnotation(konfig.HelmGeneratedAnnotation, "true")); err != nil { + return fmt.Errorf("failed to set helm annotation: %w", err) + } + } + return nil +} + // checkHelmVersion will return an error if the helm version is not V3 func (p *HelmChartInflationGeneratorPlugin) checkHelmVersion() error { stdout, err := p.runHelmCommand([]string{"version", "-c", "--short"}) diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/IAMPolicyGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/IAMPolicyGenerator.go index cfb1fa81b6f0..314e60c7c4f1 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/IAMPolicyGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/IAMPolicyGenerator.go @@ -1,6 +1,4 @@ // Code generated by pluginator on IAMPolicyGenerator; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ImageTagTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ImageTagTransformer.go index ffde73a7a13f..c5284cb70d7d 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ImageTagTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ImageTagTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ImageTagTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/LabelTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/LabelTransformer.go index c45731b54bff..8ebbd19f788e 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/LabelTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/LabelTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on LabelTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/NamespaceTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/NamespaceTransformer.go index d839fb975182..3b98195b3f29 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/NamespaceTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/NamespaceTransformer.go @@ -1,12 +1,11 @@ // Code generated by pluginator on NamespaceTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( "fmt" "sigs.k8s.io/kustomize/api/filters/namespace" + "sigs.k8s.io/kustomize/api/konfig" "sigs.k8s.io/kustomize/api/resmap" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/errors" @@ -53,6 +52,10 @@ func (p *NamespaceTransformerPlugin) Transform(m resmap.ResMap) error { // Don't mutate empty objects? continue } + if annotations := r.GetAnnotations(konfig.HelmGeneratedAnnotation); annotations[konfig.HelmGeneratedAnnotation] == "true" { + // Don't apply namespace on Helm generated manifest. Helm should take care of it. + continue + } r.StorePreviousId() if err := r.ApplyFilter(namespace.Filter{ Namespace: p.Namespace, diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchJson6902Transformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchJson6902Transformer.go index 04625e5109b3..348863263fb4 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchJson6902Transformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchJson6902Transformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on PatchJson6902Transformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchStrategicMergeTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchStrategicMergeTransformer.go index d68f2425ea8a..29f8f2b9d7de 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchStrategicMergeTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchStrategicMergeTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on PatchStrategicMergeTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchTransformer.go index 05d96f23ca2e..278d1009383f 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PatchTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on PatchTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( @@ -24,10 +22,10 @@ type PatchTransformerPlugin struct { patchText string // patchSource is patch source message patchSource string - Path string `json:"path,omitempty" yaml:"path,omitempty"` - Patch string `json:"patch,omitempty" yaml:"patch,omitempty"` - Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"` - Options map[string]bool `json:"options,omitempty" yaml:"options,omitempty"` + Path string `json:"path,omitempty" yaml:"path,omitempty"` + Patch string `json:"patch,omitempty" yaml:"patch,omitempty"` + Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"` + Options *types.PatchArgs `json:"options,omitempty" yaml:"options,omitempty"` } func (p *PatchTransformerPlugin) Config(h *resmap.PluginHelpers, c []byte) error { @@ -70,10 +68,14 @@ func (p *PatchTransformerPlugin) Config(h *resmap.PluginHelpers, c []byte) error if errSM == nil { p.smPatches = patchesSM for _, loadedPatch := range p.smPatches { - if p.Options["allowNameChange"] { + if p.Options == nil { + continue + } + + if p.Options.AllowNameChange { loadedPatch.AllowNameChange() } - if p.Options["allowKindChange"] { + if p.Options.AllowKindChange { loadedPatch.AllowKindChange() } } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PrefixTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PrefixTransformer.go index 33700bb4b18a..fc26de228f4a 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PrefixTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/PrefixTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on PrefixTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplacementTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplacementTransformer.go index ef0c93212825..795af7b87bc6 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplacementTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplacementTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ReplacementTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplicaCountTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplicaCountTransformer.go index c87d64251c05..afbd4b105c71 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplicaCountTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ReplicaCountTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ReplicaCountTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SecretGenerator.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SecretGenerator.go index 2a4ef1c903ba..fbb4efa402cf 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SecretGenerator.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SecretGenerator.go @@ -1,6 +1,4 @@ // Code generated by pluginator on SecretGenerator; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go index 90e290719e62..8b88b129f900 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SortOrderTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on SortOrderTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SuffixTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SuffixTransformer.go index 31b5b8fea026..2999711ab625 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SuffixTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/SuffixTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on SuffixTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ValueAddTransformer.go b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ValueAddTransformer.go index 1d70c98c2c8a..2bab5b6b6676 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ValueAddTransformer.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/builtins/ValueAddTransformer.go @@ -1,6 +1,4 @@ // Code generated by pluginator on ValueAddTransformer; DO NOT EDIT. -// pluginator {(devel) unknown } - package builtins import ( diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/loader/fileloader.go b/vendor/sigs.k8s.io/kustomize/api/internal/loader/fileloader.go index 69b8295eb7ab..e4202815c99c 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/loader/fileloader.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/loader/fileloader.go @@ -169,7 +169,7 @@ func (fl *FileLoader) New(path string) (ifc.Loader, error) { } root, err := filesys.ConfirmDir(fl.fSys, fl.root.Join(path)) if err != nil { - return nil, errors.WrapPrefixf(err, ErrRtNotDir.Error()) //nolint:govet + return nil, errors.WrapPrefixf(err, "%s", ErrRtNotDir.Error()) } if err = fl.errIfGitContainmentViolation(root); err != nil { return nil, err @@ -311,7 +311,11 @@ func (fl *FileLoader) httpClientGetContent(path string) ([]byte, error) { } else { hc = &http.Client{} } - resp, err := hc.Get(path) + parsedURL, err := url.ParseRequestURI(path) + if err != nil { + return nil, errors.Wrap(err) + } + resp, err := hc.Get(parsedURL.String()) if err != nil { return nil, errors.Wrap(err) } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/loader/loader.go b/vendor/sigs.k8s.io/kustomize/api/internal/loader/loader.go index 60b254fa7e71..36b246fb4e2b 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/loader/loader.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/loader/loader.go @@ -28,7 +28,7 @@ func NewLoader( } root, err := filesys.ConfirmDir(fSys, target) if err != nil { - return nil, errors.WrapPrefixf(err, ErrRtNotDir.Error()) //nolint:govet + return nil, errors.WrapPrefixf(err, "%s", ErrRtNotDir.Error()) } return newLoaderAtConfirmedDir( lr, root, fSys, nil, git.ClonerUsingGitExec), nil diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/execplugin/execplugin.go b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/execplugin/execplugin.go index f6c1dba3ce61..f6cc0b53f5ec 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/execplugin/execplugin.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/execplugin/execplugin.go @@ -161,14 +161,13 @@ func (p *ExecPlugin) invokePlugin(input []byte) ([]byte, error) { _, err = f.Write(p.cfg) if err != nil { return nil, errors.WrapPrefixf( - err, "writing plugin config to "+f.Name()) + err, "writing plugin config to %s", f.Name()) } err = f.Close() if err != nil { return nil, errors.WrapPrefixf( - err, "closing plugin config file "+f.Name()) + err, "closing plugin config file %s", f.Name()) } - //nolint:gosec cmd := exec.Command( p.path, append([]string{f.Name()}, p.args...)...) cmd.Env = p.getEnv() @@ -180,10 +179,9 @@ func (p *ExecPlugin) invokePlugin(input []byte) ([]byte, error) { } result, err := cmd.Output() if err != nil { - //nolint:govet return nil, errors.WrapPrefixf( - fmt.Errorf("failure in plugin configured via %s; %w", - f.Name(), err), stdErr.String()) + fmt.Errorf("failure in plugin configured via %s; %w", f.Name(), err), + "%s", stdErr.String()) } return result, os.Remove(f.Name()) } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/loader/loader.go b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/loader/loader.go index 2edf8791ff14..afae8940dfb1 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/plugins/loader/loader.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/plugins/loader/loader.go @@ -251,7 +251,7 @@ func (l *Loader) loadPlugin(res *resource.Resource) (resmap.Configurable, error) return nil, errors.Errorf("plugin %s with mount path '%s' is not permitted; "+ "mount paths must be relative to the current kustomization directory", res.OrgId(), mount.Src) } - if strings.HasPrefix(filepath.Clean(mount.Src), "../") { + if strings.HasPrefix(filepath.Clean(mount.Src), "..") { return nil, errors.Errorf("plugin %s with mount path '%s' is not permitted; "+ "mount paths must be under the current kustomization directory", res.OrgId(), mount.Src) } diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go index 5f1d1095a178..3eb4c00c099f 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget.go @@ -496,6 +496,11 @@ func (kt *KustTarget) accumulateDirectory( } subKt.kustomization.BuildMetadata = kt.kustomization.BuildMetadata subKt.origin = kt.origin + // Propagate namespace to child kustomization if child doesn't have one + // This ensures Helm charts in base kustomizations inherit namespace from overlays + if subKt.kustomization.Namespace == "" && kt.kustomization.Namespace != "" { + subKt.kustomization.Namespace = kt.kustomization.Namespace + } var bytes []byte if openApiPath, exists := subKt.Kustomization().OpenAPI["path"]; exists { bytes, err = ldr.Load(openApiPath) diff --git a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget_configplugin.go b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget_configplugin.go index 1ba028a36fed..c41d6c84fcf2 100644 --- a/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget_configplugin.go +++ b/vendor/sigs.k8s.io/kustomize/api/internal/target/kusttarget_configplugin.go @@ -166,6 +166,11 @@ var generatorConfigurators = map[builtinhelpers.BuiltinPluginType]func( for _, chart := range kt.kustomization.HelmCharts { c.HelmGlobals = globals c.HelmChart = chart + // Pass kustomize namespace to helm + // Fixes https://github.com/kubernetes-sigs/kustomize/issues/5566 + if c.HelmChart.Namespace == "" && kt.kustomization.Namespace != "" { + c.HelmChart.Namespace = kt.kustomization.Namespace + } p := f() if err = kt.configureBuiltinPlugin(p, c, bpt); err != nil { return nil, err @@ -250,10 +255,10 @@ var transformerConfigurators = map[builtinhelpers.BuiltinPluginType]func( return } var c struct { - Path string `json:"path,omitempty" yaml:"path,omitempty"` - Patch string `json:"patch,omitempty" yaml:"patch,omitempty"` - Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"` - Options map[string]bool `json:"options,omitempty" yaml:"options,omitempty"` + Path string `json:"path,omitempty" yaml:"path,omitempty"` + Patch string `json:"patch,omitempty" yaml:"patch,omitempty"` + Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"` + Options *types.PatchArgs `json:"options,omitempty" yaml:"options,omitempty"` } for _, pc := range kt.kustomization.Patches { c.Target = pc.Target diff --git a/vendor/sigs.k8s.io/kustomize/api/konfig/general.go b/vendor/sigs.k8s.io/kustomize/api/konfig/general.go index 712bfe7894fe..c66188388322 100644 --- a/vendor/sigs.k8s.io/kustomize/api/konfig/general.go +++ b/vendor/sigs.k8s.io/kustomize/api/konfig/general.go @@ -46,4 +46,7 @@ const ( // Label key that indicates the resources are validated by a validator ValidatedByLabelKey = "validated-by" + + // Annotation key for marking helm-generated resources to skip namespace transformation + HelmGeneratedAnnotation = ConfigAnnoDomain + "/helm-generated" ) diff --git a/vendor/sigs.k8s.io/kustomize/api/resmap/reswrangler.go b/vendor/sigs.k8s.io/kustomize/api/resmap/reswrangler.go index f6443539f1bc..33578a0bbe59 100644 --- a/vendor/sigs.k8s.io/kustomize/api/resmap/reswrangler.go +++ b/vendor/sigs.k8s.io/kustomize/api/resmap/reswrangler.go @@ -597,7 +597,7 @@ func (m *resWrangler) appendReplaceOrMerge(res *resource.Resource) error { default: return fmt.Errorf( - "id %#v exists; behavior must be merge or replace", id) + "id %#v exists; can not use behavior: '%s', behavior must be merge or replace", id, res.Behavior()) } i, err := m.Replace(res) if err != nil { diff --git a/vendor/sigs.k8s.io/kustomize/api/resource/resource.go b/vendor/sigs.k8s.io/kustomize/api/resource/resource.go index 9884a672c563..dc6995799b0e 100644 --- a/vendor/sigs.k8s.io/kustomize/api/resource/resource.go +++ b/vendor/sigs.k8s.io/kustomize/api/resource/resource.go @@ -11,6 +11,7 @@ import ( "sigs.k8s.io/kustomize/api/filters/patchstrategicmerge" "sigs.k8s.io/kustomize/api/ifc" "sigs.k8s.io/kustomize/api/internal/utils" + "sigs.k8s.io/kustomize/api/konfig" "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/kio" "sigs.k8s.io/kustomize/kyaml/kio/kioutil" @@ -47,6 +48,8 @@ var BuildAnnotations = []string{ kioutil.LegacyPathAnnotation, kioutil.LegacyIndexAnnotation, kioutil.LegacyIdAnnotation, + + konfig.HelmGeneratedAnnotation, } func (r *Resource) ResetRNode(incoming *Resource) { diff --git a/vendor/sigs.k8s.io/kustomize/api/types/patch.go b/vendor/sigs.k8s.io/kustomize/api/types/patch.go index 5310a6e66dba..7ad141975c61 100644 --- a/vendor/sigs.k8s.io/kustomize/api/types/patch.go +++ b/vendor/sigs.k8s.io/kustomize/api/types/patch.go @@ -3,8 +3,6 @@ package types -import "reflect" - // Patch represent either a Strategic Merge Patch or a JSON patch // and its targets. // The content of the patch can either be from a file @@ -20,15 +18,17 @@ type Patch struct { Target *Selector `json:"target,omitempty" yaml:"target,omitempty"` // Options is a list of options for the patch - Options map[string]bool `json:"options,omitempty" yaml:"options,omitempty"` + Options *PatchArgs `json:"options,omitempty" yaml:"options,omitempty"` } // Equals return true if p equals o. func (p *Patch) Equals(o Patch) bool { targetEqual := (p.Target == o.Target) || (p.Target != nil && o.Target != nil && *p.Target == *o.Target) + optionsEqual := (p.Options == o.Options) || + (p.Options != nil && o.Options != nil && *p.Options == *o.Options) return p.Path == o.Path && p.Patch == o.Patch && targetEqual && - reflect.DeepEqual(p.Options, o.Options) + optionsEqual } diff --git a/vendor/sigs.k8s.io/kustomize/api/types/patchargs.go b/vendor/sigs.k8s.io/kustomize/api/types/patchargs.go new file mode 100644 index 000000000000..453849fa6b17 --- /dev/null +++ b/vendor/sigs.k8s.io/kustomize/api/types/patchargs.go @@ -0,0 +1,13 @@ +// Copyright 2019 The Kubernetes Authors. +// SPDX-License-Identifier: Apache-2.0 + +package types + +// PatchArgs represent set of options on resources of a patch. +type PatchArgs struct { + // AllowNameChange allows name changes to the resource. + AllowNameChange bool `json:"allowNameChange,omitempty" yaml:"allowNameChange,omitempty"` + + // AllowKindChange allows kind changes to the resource. + AllowKindChange bool `json:"allowKindChange,omitempty" yaml:"allowKindChange,omitempty"` +} diff --git a/vendor/sigs.k8s.io/kustomize/api/types/replacement.go b/vendor/sigs.k8s.io/kustomize/api/types/replacement.go index b110322e78fd..dd8ed5dc4c49 100644 --- a/vendor/sigs.k8s.io/kustomize/api/types/replacement.go +++ b/vendor/sigs.k8s.io/kustomize/api/types/replacement.go @@ -66,6 +66,53 @@ type TargetSelector struct { Options *FieldOptions `json:"options,omitempty" yaml:"options,omitempty"` } +type TargetSelectorRegex struct { + targetSelector *TargetSelector + selectRegex *SelectorRegex + rejectRegex []*SelectorRegex +} + +func NewTargetSelectorRegex(ts *TargetSelector) (*TargetSelectorRegex, error) { + tsr := new(TargetSelectorRegex) + tsr.targetSelector = ts + var err error + + tsr.selectRegex, err = NewSelectorRegex(ts.Select) + if err != nil { + return nil, err + } + + rej := []*SelectorRegex{} + for _, r := range ts.Reject { + rr, err := NewSelectorRegex(r) + if err != nil { + return nil, err + } + rej = append(rej, rr) + } + tsr.rejectRegex = rej + + return tsr, nil +} + +func (tsr *TargetSelectorRegex) Selects(id resid.ResId) bool { + return tsr.selectRegex.MatchGvk(id.Gvk) && tsr.selectRegex.MatchName(id.Name) && tsr.selectRegex.MatchNamespace(id.Namespace) +} + +func (tsr *TargetSelectorRegex) RejectsAny(ids []resid.ResId) bool { + for _, r := range tsr.rejectRegex { + if r.selector.ResId.IsEmpty() { + continue + } + for _, id := range ids { + if r.MatchGvk(id.Gvk) && r.MatchName(id.Name) && r.MatchNamespace(id.Namespace) { + return true + } + } + } + return false +} + // FieldOptions refine the interpretation of FieldPaths. type FieldOptions struct { // Used to split/join the field. diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/filesys/filesystem.go b/vendor/sigs.k8s.io/kustomize/kyaml/filesys/filesystem.go index c29d5ad8a7df..4e1c3d896609 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/filesys/filesystem.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/filesys/filesystem.go @@ -4,7 +4,6 @@ package filesys import ( - "fmt" "path/filepath" "sigs.k8s.io/kustomize/kyaml/errors" @@ -78,8 +77,7 @@ func ConfirmDir(fSys FileSystem, path string) (ConfirmedDir, error) { return "", errors.WrapPrefixf(err, "not a valid directory") } if f != "" { - //nolint:govet - return "", errors.WrapPrefixf(errors.Errorf("file is not directory"), fmt.Sprintf("'%s'", path)) + return "", errors.WrapPrefixf(errors.Errorf("file is not directory"), "'%s'", path) } return d, nil } diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/exec/exec.go b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/exec/exec.go index 562dab30f792..7425d183e5fa 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/exec/exec.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/fn/runtime/exec/exec.go @@ -37,7 +37,7 @@ func (c *Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) { } func (c *Filter) Run(reader io.Reader, writer io.Writer) error { - cmd := exec.Command(c.Path, c.Args...) //nolint:gosec + cmd := exec.Command(c.Path, c.Args...) cmd.Env = append(os.Environ(), c.Env...) cmd.Stdin = reader cmd.Stdout = writer diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/kioutil/kioutil.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/kioutil/kioutil.go index 510ecae18f8d..818d6ca0065b 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/kioutil/kioutil.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/kio/kioutil/kioutil.go @@ -387,7 +387,7 @@ func ConfirmInternalAnnotationUnchanged(r1 *yaml.RNode, r2 *yaml.RNode, exclusio for _, key := range keys { errorString = errorString + key + ", " } - return errors.Errorf(errorString[0 : len(errorString)-2]) + return errors.Errorf("%s", errorString[0:len(errorString)-2]) } return nil diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/kio/pkgio_reader.go b/vendor/sigs.k8s.io/kustomize/kyaml/kio/pkgio_reader.go index 609a791f390c..d7eeda7932cc 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/kio/pkgio_reader.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/kio/pkgio_reader.go @@ -268,7 +268,7 @@ func (r LocalPackageReader) Read() ([]*yaml.RNode, error) { // to another location. relPath, err := filepath.Rel(pathRelativeTo, path) if err != nil { - return errors.WrapPrefixf(err, pathRelativeTo) + return errors.WrapPrefixf(err, "%s", pathRelativeTo) } if match, err := r.shouldSkipFile(path, relPath, ignoreFilesMatcher); err != nil { return err @@ -280,7 +280,7 @@ func (r LocalPackageReader) Read() ([]*yaml.RNode, error) { r.initReaderAnnotations(relPath, info) nodes, err := r.readFile(path, info) if err != nil { - return errors.WrapPrefixf(err, path) + return errors.WrapPrefixf(err, "%s", path) } operand = append(operand, nodes...) return nil diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go b/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go index bf8863c57279..4fd175cd8883 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/runfn/runfn.go @@ -230,7 +230,7 @@ func (r RunFns) runFunctions( } } if len(errs) > 0 { - return fmt.Errorf(strings.Join(errs, "\n---\n")) + return fmt.Errorf("%s", strings.Join(errs, "\n---\n")) } return nil } diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/fns.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/fns.go index 740a28ed021f..9c26055ed7ca 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/fns.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/fns.go @@ -830,6 +830,10 @@ func (e *InvalidNodeKindError) Error() string { return msg } +func (e *InvalidNodeKindError) Unwrap() error { + return errors.Errorf("InvalidNodeKindError") +} + func (e *InvalidNodeKindError) ActualNodeKind() Kind { return e.node.YNode().Kind } diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/match.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/match.go index 28ea03ca6f80..1e70de3c9487 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/match.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/match.go @@ -14,7 +14,7 @@ import ( ) // PathMatcher returns all RNodes matching the path wrapped in a SequenceNode. -// Lists may have multiple elements matching the path, and each matching element +// Lists may have multiple elements matching the pafunc cleanPath(path []string) []string {g element // is added to the return result. // If Path points to a SequenceNode, the SequenceNode is wrapped in another SequenceNode // If Path does not contain any lists, the result is still wrapped in a SequenceNode of len == 1 @@ -137,10 +137,14 @@ func (p *PathMatcher) visitEveryElem(elem *RNode) error { func (p *PathMatcher) doField(rn *RNode) (*RNode, error) { // lookup the field field, err := rn.Pipe(Get(p.Path[0])) - if err != nil || (!IsCreate(p.Create) && field == nil) { + if err != nil { return nil, err } + if !IsCreate(p.Create) && field == nil { + return nil, nil + } + if IsCreate(p.Create) && field == nil { var nextPart string if len(p.Path) > 1 { @@ -154,6 +158,11 @@ func (p *PathMatcher) doField(rn *RNode) (*RNode, error) { } } + // Check if the field is a scalar and there are remaining path segments + if field != nil && field.YNode().Kind == yaml.ScalarNode && len(p.Path) > 1 { + return p.handleStructuredDataInScalar(field) + } + // recurse on the field, removing the first element of the path pm := &PathMatcher{Path: p.Path[1:], Create: p.Create} p.val, err = pm.filter(field) @@ -253,12 +262,12 @@ func (p *PathMatcher) doSeq(rn *RNode) (*RNode, error) { func (p *PathMatcher) visitPrimitiveElem(elem *RNode) error { r, err := regexp.Compile(p.matchRegex) if err != nil { - return err + return fmt.Errorf("%w", err) } str, err := elem.String() if err != nil { - return err + return fmt.Errorf("%w", err) } str = strings.TrimSpace(str) if !r.MatchString(str) { @@ -272,7 +281,7 @@ func (p *PathMatcher) visitPrimitiveElem(elem *RNode) error { func (p *PathMatcher) visitElem(elem *RNode) error { r, err := regexp.Compile(p.matchRegex) if err != nil { - return err + return fmt.Errorf("%w", err) } // check if this elements field matches the regex @@ -282,7 +291,7 @@ func (p *PathMatcher) visitElem(elem *RNode) error { } str, err := val.Value.String() if err != nil { - return err + return fmt.Errorf("%w", err) } str = strings.TrimSpace(str) if !r.MatchString(str) { @@ -331,3 +340,26 @@ func cleanPath(path []string) []string { } return p } + +// handleStructuredDataInScalar processes a scalar field that contains structured data (JSON/YAML) +// and allows path navigation within that structured data +func (p *PathMatcher) handleStructuredDataInScalar(scalarField *RNode) (*RNode, error) { + scalarValue := scalarField.YNode().Value + var parsedNode yaml.Node + if err := yaml.Unmarshal([]byte(scalarValue), &parsedNode); err != nil { + return nil, fmt.Errorf("%w", err) + } + + // Create a structured field from the parsed data + structuredField := NewRNode(&parsedNode) + + // Process the remaining path on the structured data + pm := &PathMatcher{Path: p.Path[1:], Create: p.Create} + result, err := pm.filter(structuredField) + if err != nil { + return nil, err + } + p.Matches = pm.Matches + + return result, nil +} diff --git a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/rnode.go b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/rnode.go index 0059ec2eb969..43cad97e5d5b 100644 --- a/vendor/sigs.k8s.io/kustomize/kyaml/yaml/rnode.go +++ b/vendor/sigs.k8s.io/kustomize/kyaml/yaml/rnode.go @@ -718,10 +718,11 @@ func (rn *RNode) MustString() string { // Content returns Node Content field. func (rn *RNode) Content() []*yaml.Node { - if rn == nil { + yNode := rn.YNode() + if yNode == nil { return nil } - return rn.YNode().Content + return yNode.Content } // Fields returns the list of field names for a MappingNode. @@ -756,7 +757,11 @@ func (rn *RNode) FieldRNodes() ([]*RNode, error) { // Field returns a fieldName, fieldValue pair for MappingNodes. // Returns nil for non-MappingNodes. func (rn *RNode) Field(field string) *MapNode { - if rn.YNode().Kind != yaml.MappingNode { + yNode := rn.YNode() + if yNode == nil { + return nil + } + if yNode.Kind != yaml.MappingNode { return nil } var result *MapNode @@ -892,7 +897,11 @@ func (rn *RNode) ElementValuesList(keys []string) ([][]string, error) { // Element returns the element in the list which contains the field matching the value. // Returns nil for non-SequenceNodes or if no Element matches. func (rn *RNode) Element(key, value string) *RNode { - if rn.YNode().Kind != yaml.SequenceNode { + yNode := rn.YNode() + if yNode == nil { + return nil + } + if yNode.Kind != yaml.SequenceNode { return nil } elem, err := rn.Pipe(MatchElement(key, value)) @@ -906,7 +915,11 @@ func (rn *RNode) Element(key, value string) *RNode { // corresponding values[i]. // Returns nil for non-SequenceNodes or if no Element matches. func (rn *RNode) ElementList(keys []string, values []string) *RNode { - if rn.YNode().Kind != yaml.SequenceNode { + yNode := rn.YNode() + if yNode == nil { + return nil + } + if yNode.Kind != yaml.SequenceNode { return nil } elem, err := rn.Pipe(MatchElementList(keys, values)) @@ -960,12 +973,17 @@ func (rn *RNode) GetAssociativeKey() string { // MarshalJSON creates a byte slice from the RNode. func (rn *RNode) MarshalJSON() ([]byte, error) { + yNode := rn.YNode() + if yNode == nil { + return []byte("null"), nil + } + s, err := rn.String() if err != nil { return nil, err } - if rn.YNode().Kind == SequenceNode { + if yNode.Kind == SequenceNode { var a []interface{} if err := Unmarshal([]byte(s), &a); err != nil { return nil, err @@ -977,6 +995,7 @@ func (rn *RNode) MarshalJSON() ([]byte, error) { if err := Unmarshal([]byte(s), &m); err != nil { return nil, err } + return json.Marshal(m) } diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go index 5d3707a5b50c..c8138a6548a5 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go @@ -18,6 +18,7 @@ package schema import ( "sync" + "sync/atomic" ) // Schema is a list of named types. @@ -28,7 +29,7 @@ type Schema struct { Types []TypeDef `yaml:"types,omitempty"` once sync.Once - m map[string]TypeDef + m atomic.Pointer[map[string]TypeDef] lock sync.Mutex // Cached results of resolving type references to atoms. Only stores @@ -144,26 +145,28 @@ type Map struct { ElementRelationship ElementRelationship `yaml:"elementRelationship,omitempty"` once sync.Once - m map[string]StructField + m atomic.Pointer[map[string]StructField] } // FindField is a convenience function that returns the referenced StructField, // if it exists, or (nil, false) if it doesn't. func (m *Map) FindField(name string) (StructField, bool) { m.once.Do(func() { - m.m = make(map[string]StructField, len(m.Fields)) + mm := make(map[string]StructField, len(m.Fields)) for _, field := range m.Fields { - m.m[field.Name] = field + mm[field.Name] = field } + m.m.Store(&mm) }) - sf, ok := m.m[name] + sf, ok := (*m.m.Load())[name] return sf, ok } -// CopyInto this instance of Map into the other -// If other is nil this method does nothing. -// If other is already initialized, overwrites it with this instance -// Warning: Not thread safe +// CopyInto clones this instance of Map into dst +// +// If dst is nil this method does nothing. +// If dst is already initialized, overwrites it with this instance. +// Warning: Not thread safe. Only use dst after this function returns. func (m *Map) CopyInto(dst *Map) { if dst == nil { return @@ -175,12 +178,13 @@ func (m *Map) CopyInto(dst *Map) { dst.Unions = m.Unions dst.ElementRelationship = m.ElementRelationship - if m.m != nil { + mm := m.m.Load() + if mm != nil { // If cache is non-nil then the once token had been consumed. // Must reset token and use it again to ensure same semantics. dst.once = sync.Once{} dst.once.Do(func() { - dst.m = m.m + dst.m.Store(mm) }) } } @@ -274,12 +278,13 @@ type List struct { // if it exists, or (nil, false) if it doesn't. func (s *Schema) FindNamedType(name string) (TypeDef, bool) { s.once.Do(func() { - s.m = make(map[string]TypeDef, len(s.Types)) + sm := make(map[string]TypeDef, len(s.Types)) for _, t := range s.Types { - s.m[t.Name] = t + sm[t.Name] = t } + s.m.Store(&sm) }) - t, ok := s.m[name] + t, ok := (*s.m.Load())[name] return t, ok } @@ -352,10 +357,11 @@ func (s *Schema) Resolve(tr TypeRef) (Atom, bool) { return result, true } -// Clones this instance of Schema into the other -// If other is nil this method does nothing. -// If other is already initialized, overwrites it with this instance -// Warning: Not thread safe +// CopyInto clones this instance of Schema into dst +// +// If dst is nil this method does nothing. +// If dst is already initialized, overwrites it with this instance. +// Warning: Not thread safe. Only use dst after this function returns. func (s *Schema) CopyInto(dst *Schema) { if dst == nil { return @@ -364,12 +370,13 @@ func (s *Schema) CopyInto(dst *Schema) { // Schema type is considered immutable so sharing references dst.Types = s.Types - if s.m != nil { + sm := s.m.Load() + if sm != nil { // If cache is non-nil then the once token had been consumed. // Must reset token and use it again to ensure same semantics. dst.once = sync.Once{} dst.once.Do(func() { - dst.m = s.m + dst.m.Store(sm) }) } } diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v6/typed/remove.go b/vendor/sigs.k8s.io/structured-merge-diff/v6/typed/remove.go index 86de5105d7c1..0db1734f941b 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v6/typed/remove.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v6/typed/remove.go @@ -58,6 +58,10 @@ func (w *removingWalker) doList(t *schema.List) (errs ValidationErrors) { defer w.allocator.Free(l) // If list is null or empty just return if l == nil || l.Length() == 0 { + // For extraction, we just return the value as is (which is nil or empty). For extraction the difference matters. + if w.shouldExtract { + w.out = w.value.Unstructured() + } return nil } @@ -71,6 +75,7 @@ func (w *removingWalker) doList(t *schema.List) (errs ValidationErrors) { } var newItems []interface{} + hadMatches := false iter := l.RangeUsing(w.allocator) defer w.allocator.Free(iter) for iter.Next() { @@ -80,24 +85,40 @@ func (w *removingWalker) doList(t *schema.List) (errs ValidationErrors) { path, _ := fieldpath.MakePath(pe) // save items on the path when we shouldExtract // but ignore them when we are removing (i.e. !w.shouldExtract) - if w.toRemove.Has(path) { - if w.shouldExtract { - newItems = append(newItems, removeItemsWithSchema(item, w.toRemove, w.schema, t.ElementType, w.shouldExtract).Unstructured()) - } else { - continue + isExactPathMatch := w.toRemove.Has(path) + isPrefixMatch := !w.toRemove.WithPrefix(pe).Empty() + if w.shouldExtract { + if isPrefixMatch { + item = removeItemsWithSchema(item, w.toRemove.WithPrefix(pe), w.schema, t.ElementType, w.shouldExtract) + } + if isExactPathMatch || isPrefixMatch { + newItems = append(newItems, item.Unstructured()) } - } - if subset := w.toRemove.WithPrefix(pe); !subset.Empty() { - item = removeItemsWithSchema(item, subset, w.schema, t.ElementType, w.shouldExtract) } else { - // don't save items not on the path when we shouldExtract. - if w.shouldExtract { + if isExactPathMatch { continue } + if isPrefixMatch { + // Removing nested items within this list item and preserve if it becomes empty + hadMatches = true + wasMap := item.IsMap() + wasList := item.IsList() + item = removeItemsWithSchema(item, w.toRemove.WithPrefix(pe), w.schema, t.ElementType, w.shouldExtract) + // If item returned null but we're removing items within the structure(not the item itself), + // preserve the empty container structure + if item.IsNull() && !w.shouldExtract { + if wasMap { + item = value.NewValueInterface(map[string]interface{}{}) + } else if wasList { + item = value.NewValueInterface([]interface{}{}) + } + } + } + newItems = append(newItems, item.Unstructured()) } - newItems = append(newItems, item.Unstructured()) } - if len(newItems) > 0 { + // Preserve empty lists (non-nil) instead of converting to null when items were matched and removed + if len(newItems) > 0 || (hadMatches && !w.shouldExtract) { w.out = newItems } return nil @@ -113,6 +134,10 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors { } // If map is null or empty just return if m == nil || m.Empty() { + // For extraction, we just return the value as is (which is nil or empty). For extraction the difference matters. + if w.shouldExtract { + w.out = w.value.Unstructured() + } return nil } @@ -131,6 +156,7 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors { } newMap := map[string]interface{}{} + hadMatches := false m.Iterate(func(k string, val value.Value) bool { pe := fieldpath.PathElement{FieldName: &k} path, _ := fieldpath.MakePath(pe) @@ -148,7 +174,19 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors { return true } if subset := w.toRemove.WithPrefix(pe); !subset.Empty() { + hadMatches = true + wasMap := val.IsMap() + wasList := val.IsList() val = removeItemsWithSchema(val, subset, w.schema, fieldType, w.shouldExtract) + // If val returned null but we're removing items within the structure (not the field itself), + // preserve the empty container structure + if val.IsNull() && !w.shouldExtract { + if wasMap { + val = value.NewValueInterface(map[string]interface{}{}) + } else if wasList { + val = value.NewValueInterface([]interface{}{}) + } + } } else { // don't save values not on the path when we shouldExtract. if w.shouldExtract { @@ -158,7 +196,8 @@ func (w *removingWalker) doMap(t *schema.Map) ValidationErrors { newMap[k] = val.Unstructured() return true }) - if len(newMap) > 0 { + // Preserve empty maps (non-nil) instead of converting to null when items were matched and removed + if len(newMap) > 0 || (hadMatches && !w.shouldExtract) { w.out = newMap } return nil